blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
82bd3a1e4e603059afadb57610996a24b2dc5a1d | [
"content = '\\n\\n Welcome to the club! We are delighted you\\'ve decided to let Vinely make your wine experience easy, fun, and convenient.\\n You\\'re in good hands.\\n\\n Your first delicious surprise will arrive within 7 - 10 business days.\\n Remember, someone 21 years or older must... | <|body_start_0|>
content = '\n\n Welcome to the club! We are delighted you\'ve decided to let Vinely make your wine experience easy, fun, and convenient.\n You\'re in good hands.\n\n Your first delicious surprise will arrive within 7 - 10 business days.\n Remember, someone 21 years o... | Migration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Write your forwards methods here."""
<|body_0|>
def backwards(self, orm):
"""Write your backwards methods here."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
content = '\n\n Welcome to the club! We are... | stack_v2_sparse_classes_36k_train_023000 | 3,432 | no_license | [
{
"docstring": "Write your forwards methods here.",
"name": "forwards",
"signature": "def forwards(self, orm)"
},
{
"docstring": "Write your backwards methods here.",
"name": "backwards",
"signature": "def backwards(self, orm)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000697 | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Write your forwards methods here.
- def backwards(self, orm): Write your backwards methods here. | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Write your forwards methods here.
- def backwards(self, orm): Write your backwards methods here.
<|skeleton|>
class Migration:
def forwards(self,... | c5c7d8a0b1a297e07302870017d3fb03c5dbb009 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Write your forwards methods here."""
<|body_0|>
def backwards(self, orm):
"""Write your backwards methods here."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Migration:
def forwards(self, orm):
"""Write your forwards methods here."""
content = '\n\n Welcome to the club! We are delighted you\'ve decided to let Vinely make your wine experience easy, fun, and convenient.\n You\'re in good hands.\n\n Your first delicious surprise w... | the_stack_v2_python_sparse | cms/migrations/0027_join_the_club_anon_email.py | RSV3/nuvine | train | 0 | |
150526e2268e028666be9eed2338ff75ac2e6966 | [
"expected_obj = self.resize_prep_start_obj\nactual_json = json.dumps(self.base_resize_prep_dict)\nactual_obj = InstanceResizePrepStart.deserialize(actual_json, 'json')\nself.assertEqual(expected_obj, actual_obj)\nself.assertFalse(actual_obj.is_empty())",
"modified_dict = self.base_resize_prep_dict.copy()\nmodifie... | <|body_start_0|>
expected_obj = self.resize_prep_start_obj
actual_json = json.dumps(self.base_resize_prep_dict)
actual_obj = InstanceResizePrepStart.deserialize(actual_json, 'json')
self.assertEqual(expected_obj, actual_obj)
self.assertFalse(actual_obj.is_empty())
<|end_body_0|>
... | InstanceResizePrepStartTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstanceResizePrepStartTest:
def test_instance_resize_prep_start_valid_json(self):
"""Verify that the valid event deserialized correctly"""
<|body_0|>
def test_instance_resize_prep_start_missing_attribute_json(self):
"""Verify event missing expected attribute does no... | stack_v2_sparse_classes_36k_train_023001 | 5,720 | permissive | [
{
"docstring": "Verify that the valid event deserialized correctly",
"name": "test_instance_resize_prep_start_valid_json",
"signature": "def test_instance_resize_prep_start_valid_json(self)"
},
{
"docstring": "Verify event missing expected attribute does not deserialize",
"name": "test_insta... | 3 | stack_v2_sparse_classes_30k_train_003743 | Implement the Python class `InstanceResizePrepStartTest` described below.
Class description:
Implement the InstanceResizePrepStartTest class.
Method signatures and docstrings:
- def test_instance_resize_prep_start_valid_json(self): Verify that the valid event deserialized correctly
- def test_instance_resize_prep_sta... | Implement the Python class `InstanceResizePrepStartTest` described below.
Class description:
Implement the InstanceResizePrepStartTest class.
Method signatures and docstrings:
- def test_instance_resize_prep_start_valid_json(self): Verify that the valid event deserialized correctly
- def test_instance_resize_prep_sta... | 7d49cf6bfd7e1a6e5b739e7de52f2e18e5ccf924 | <|skeleton|>
class InstanceResizePrepStartTest:
def test_instance_resize_prep_start_valid_json(self):
"""Verify that the valid event deserialized correctly"""
<|body_0|>
def test_instance_resize_prep_start_missing_attribute_json(self):
"""Verify event missing expected attribute does no... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InstanceResizePrepStartTest:
def test_instance_resize_prep_start_valid_json(self):
"""Verify that the valid event deserialized correctly"""
expected_obj = self.resize_prep_start_obj
actual_json = json.dumps(self.base_resize_prep_dict)
actual_obj = InstanceResizePrepStart.deseri... | the_stack_v2_python_sparse | metatests/events/models/compute/test_instance_resize_prep.py | kurhula/cloudcafe | train | 0 | |
a8ed9d8b69a7474ccdbaa941680cdfcd1ad48d01 | [
"if not root:\n return ''\narr = []\nqueue = [[root, 0]]\nn = 1\nwhile queue:\n node, ind = queue.pop(0)\n arr.append([node.val])\n if node.left:\n queue.append([node.left, len(queue)])\n arr[-1].append(n)\n n += 1\n elif node.right:\n arr[-1].append(None)\n if node.rig... | <|body_start_0|>
if not root:
return ''
arr = []
queue = [[root, 0]]
n = 1
while queue:
node, ind = queue.pop(0)
arr.append([node.val])
if node.left:
queue.append([node.left, len(queue)])
arr[-1].appe... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_023002 | 1,563 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 4bf1a7814b5c76e11242e7933e09c59ede3284a3 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
arr = []
queue = [[root, 0]]
n = 1
while queue:
node, ind = queue.pop(0)
arr.append([node.val])... | the_stack_v2_python_sparse | Explore/Binary Tree/Conclusions/0297_Serialize_and_Deserialize_Binary_Tree.py | actcheng/leetcode-solutions | train | 2 | |
a3b6bc0ccb33ab8708f664a5bb1303f0991144d9 | [
"ret = []\nfor num in nums:\n if num % 2 == 0:\n ret.append(num)\n else:\n ret.insert(0, num)\nreturn ret",
"n = len(nums)\nleft, right = (0, n - 1)\nret_nums = [0] * n\nfor num in nums:\n if num % 2 == 0:\n ret_nums[right] = num\n right -= 1\n else:\n ret_nums[left]... | <|body_start_0|>
ret = []
for num in nums:
if num % 2 == 0:
ret.append(num)
else:
ret.insert(0, num)
return ret
<|end_body_0|>
<|body_start_1|>
n = len(nums)
left, right = (0, n - 1)
ret_nums = [0] * n
for n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def exchange3(self, nums: List[int]) -> List[int]:
"""创建新的数组,遍历nums,将奇数从左插入,偶数从右插入。 这里用到了python list特性,可以从左右插入,并且会动态扩容。 时间复杂度:O(n) 控件复杂度:O(n)"""
<|body_0|>
def exchange2(self, nums: List[int]) -> List[int]:
"""纯数组特性,而不是用python list特性 创建新的数组,使用left和right记录数组... | stack_v2_sparse_classes_36k_train_023003 | 2,511 | no_license | [
{
"docstring": "创建新的数组,遍历nums,将奇数从左插入,偶数从右插入。 这里用到了python list特性,可以从左右插入,并且会动态扩容。 时间复杂度:O(n) 控件复杂度:O(n)",
"name": "exchange3",
"signature": "def exchange3(self, nums: List[int]) -> List[int]"
},
{
"docstring": "纯数组特性,而不是用python list特性 创建新的数组,使用left和right记录数组两端索引,然后遍历,将奇数从左填入,left+1,将偶数从右插入,right... | 3 | stack_v2_sparse_classes_30k_train_021296 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def exchange3(self, nums: List[int]) -> List[int]: 创建新的数组,遍历nums,将奇数从左插入,偶数从右插入。 这里用到了python list特性,可以从左右插入,并且会动态扩容。 时间复杂度:O(n) 控件复杂度:O(n)
- def exchange2(self, nums: List[int]) ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def exchange3(self, nums: List[int]) -> List[int]: 创建新的数组,遍历nums,将奇数从左插入,偶数从右插入。 这里用到了python list特性,可以从左右插入,并且会动态扩容。 时间复杂度:O(n) 控件复杂度:O(n)
- def exchange2(self, nums: List[int]) ... | c0dd577481b46129d950354d567d332a4d091137 | <|skeleton|>
class Solution:
def exchange3(self, nums: List[int]) -> List[int]:
"""创建新的数组,遍历nums,将奇数从左插入,偶数从右插入。 这里用到了python list特性,可以从左右插入,并且会动态扩容。 时间复杂度:O(n) 控件复杂度:O(n)"""
<|body_0|>
def exchange2(self, nums: List[int]) -> List[int]:
"""纯数组特性,而不是用python list特性 创建新的数组,使用left和right记录数组... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def exchange3(self, nums: List[int]) -> List[int]:
"""创建新的数组,遍历nums,将奇数从左插入,偶数从右插入。 这里用到了python list特性,可以从左右插入,并且会动态扩容。 时间复杂度:O(n) 控件复杂度:O(n)"""
ret = []
for num in nums:
if num % 2 == 0:
ret.append(num)
else:
ret.insert... | the_stack_v2_python_sparse | leetcode/剑指offer/剑指 Offer 21. 调整数组顺序使奇数位于偶数前面.py | tenqaz/crazy_arithmetic | train | 0 | |
baab8f8a464fcfd7a24d2b2a7fc7fd366a130468 | [
"super().__init__(vehicle, target_speed * 3.6)\nself._vehicle = vehicle\nself._navigation_sensor = navigation_sensor\nself._alf_world = alf_world\nself._global_planner = self._alf_world._global_route_planner",
"self._local_planner._waypoint_buffer.clear()\nroute_trace = self._navigation_sensor._route\nself._local... | <|body_start_0|>
super().__init__(vehicle, target_speed * 3.6)
self._vehicle = vehicle
self._navigation_sensor = navigation_sensor
self._alf_world = alf_world
self._global_planner = self._alf_world._global_route_planner
<|end_body_0|>
<|body_start_1|>
self._local_planner... | SimpleNavigationAgent is derived from BasicAgent, which is an agent that navigates the scene and respects traffic lights and other vehicles, but ignores stop signs. Here we adapt it to follow the navigation route from the navigation sensor. TODO: Implement more advanced control logics. | SimpleNavigationAgent | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleNavigationAgent:
"""SimpleNavigationAgent is derived from BasicAgent, which is an agent that navigates the scene and respects traffic lights and other vehicles, but ignores stop signs. Here we adapt it to follow the navigation route from the navigation sensor. TODO: Implement more advanced ... | stack_v2_sparse_classes_36k_train_023004 | 2,657 | permissive | [
{
"docstring": "Args: vehicle (carla.Actor): the vehicle actor to apply the control onto navigation_sensor (NavigationSensor): the navigation sensor which will provide the navigation route for the agent to follow alf_world (World): an instance of World which keeps all the data of the world. target_speed (float)... | 2 | stack_v2_sparse_classes_30k_train_014427 | Implement the Python class `SimpleNavigationAgent` described below.
Class description:
SimpleNavigationAgent is derived from BasicAgent, which is an agent that navigates the scene and respects traffic lights and other vehicles, but ignores stop signs. Here we adapt it to follow the navigation route from the navigation... | Implement the Python class `SimpleNavigationAgent` described below.
Class description:
SimpleNavigationAgent is derived from BasicAgent, which is an agent that navigates the scene and respects traffic lights and other vehicles, but ignores stop signs. Here we adapt it to follow the navigation route from the navigation... | b00ff2fa5e660de31020338ba340263183fbeaa4 | <|skeleton|>
class SimpleNavigationAgent:
"""SimpleNavigationAgent is derived from BasicAgent, which is an agent that navigates the scene and respects traffic lights and other vehicles, but ignores stop signs. Here we adapt it to follow the navigation route from the navigation sensor. TODO: Implement more advanced ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleNavigationAgent:
"""SimpleNavigationAgent is derived from BasicAgent, which is an agent that navigates the scene and respects traffic lights and other vehicles, but ignores stop signs. Here we adapt it to follow the navigation route from the navigation sensor. TODO: Implement more advanced control logic... | the_stack_v2_python_sparse | alf/environments/carla_env/carla_agents.py | HorizonRobotics/alf | train | 288 |
5e84a3217a705093d7824b7b5fdc7a31813134ac | [
"try:\n note = get_single_note(id, self.request.user.id)\n return note\nexcept NotesNotFoundError:\n raise RequestObjectDoesNotExixts(code=409, msg=response_code[409])",
"try:\n note = self.get_object(id)\n return Response({'data': note, 'code': 200, 'msg': response_code[200]})\nexcept RequestObjec... | <|body_start_0|>
try:
note = get_single_note(id, self.request.user.id)
return note
except NotesNotFoundError:
raise RequestObjectDoesNotExixts(code=409, msg=response_code[409])
<|end_body_0|>
<|body_start_1|>
try:
note = self.get_object(id)
... | EditNote | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditNote:
def get_object(self, id):
"""param id: Note id returns: single note for perticular user if user is authenticated or user in collaborators else raise RequestObjectDoesNotExixts"""
<|body_0|>
def get(self, request, id=None):
"""param request, id: Http request... | stack_v2_sparse_classes_36k_train_023005 | 9,190 | no_license | [
{
"docstring": "param id: Note id returns: single note for perticular user if user is authenticated or user in collaborators else raise RequestObjectDoesNotExixts",
"name": "get_object",
"signature": "def get_object(self, id)"
},
{
"docstring": "param request, id: Http request contains user deta... | 3 | stack_v2_sparse_classes_30k_val_001194 | Implement the Python class `EditNote` described below.
Class description:
Implement the EditNote class.
Method signatures and docstrings:
- def get_object(self, id): param id: Note id returns: single note for perticular user if user is authenticated or user in collaborators else raise RequestObjectDoesNotExixts
- def... | Implement the Python class `EditNote` described below.
Class description:
Implement the EditNote class.
Method signatures and docstrings:
- def get_object(self, id): param id: Note id returns: single note for perticular user if user is authenticated or user in collaborators else raise RequestObjectDoesNotExixts
- def... | 8513e544cc635c372998cb8ac57bd4c93c431a9a | <|skeleton|>
class EditNote:
def get_object(self, id):
"""param id: Note id returns: single note for perticular user if user is authenticated or user in collaborators else raise RequestObjectDoesNotExixts"""
<|body_0|>
def get(self, request, id=None):
"""param request, id: Http request... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EditNote:
def get_object(self, id):
"""param id: Note id returns: single note for perticular user if user is authenticated or user in collaborators else raise RequestObjectDoesNotExixts"""
try:
note = get_single_note(id, self.request.user.id)
return note
except ... | the_stack_v2_python_sparse | fundoo/note/views.py | deep-sarkar/keep | train | 0 | |
4d5e4ad90895baf7ad4c0b44e8ec0015c92e2192 | [
"self.playerCount = 0\nself.names = []\nscreen = GameSetupScreen()\nConsoleController.__init__(self, screen, commands={'1': self.setPlayerCount, '2': self.setPlayerCount, '3': self.setPlayerCount, '4': self.setPlayerCount, '5': self.setPlayerCount, '6': self.setPlayerCount})",
"self.playerCount = int(event)\nfor ... | <|body_start_0|>
self.playerCount = 0
self.names = []
screen = GameSetupScreen()
ConsoleController.__init__(self, screen, commands={'1': self.setPlayerCount, '2': self.setPlayerCount, '3': self.setPlayerCount, '4': self.setPlayerCount, '5': self.setPlayerCount, '6': self.setPlayerCount})... | Controller for Game Setup | GameSetupController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameSetupController:
"""Controller for Game Setup"""
def __init__(self):
"""Initialize the Game Setup Controller"""
<|body_0|>
def setPlayerCount(self, event):
"""Set the player Count"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.playerCo... | stack_v2_sparse_classes_36k_train_023006 | 1,367 | permissive | [
{
"docstring": "Initialize the Game Setup Controller",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Set the player Count",
"name": "setPlayerCount",
"signature": "def setPlayerCount(self, event)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007703 | Implement the Python class `GameSetupController` described below.
Class description:
Controller for Game Setup
Method signatures and docstrings:
- def __init__(self): Initialize the Game Setup Controller
- def setPlayerCount(self, event): Set the player Count | Implement the Python class `GameSetupController` described below.
Class description:
Controller for Game Setup
Method signatures and docstrings:
- def __init__(self): Initialize the Game Setup Controller
- def setPlayerCount(self, event): Set the player Count
<|skeleton|>
class GameSetupController:
"""Controller... | 2a54293181c1c2b1a2b840ddee4d4d80177efb33 | <|skeleton|>
class GameSetupController:
"""Controller for Game Setup"""
def __init__(self):
"""Initialize the Game Setup Controller"""
<|body_0|>
def setPlayerCount(self, event):
"""Set the player Count"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GameSetupController:
"""Controller for Game Setup"""
def __init__(self):
"""Initialize the Game Setup Controller"""
self.playerCount = 0
self.names = []
screen = GameSetupScreen()
ConsoleController.__init__(self, screen, commands={'1': self.setPlayerCount, '2': sel... | the_stack_v2_python_sparse | data/train/python/4d9ee7bf7dbec4d310606d1b54cadb8a00648191game_setup_controller.py | harshp8l/deep-learning-lang-detection | train | 0 |
efa3617ec1b40971144d93c92122f7aa9c1e3097 | [
"res = []\nif not root:\n return res\nq1 = collections.deque()\nq2 = collections.deque()\norder = 1\nq1.append(root)\nwhile q1 or q2:\n res.append([])\n if order == 1:\n while q1:\n node = q1.popleft()\n res[-1].append(node.val)\n if node.left:\n q2.ap... | <|body_start_0|>
res = []
if not root:
return res
q1 = collections.deque()
q2 = collections.deque()
order = 1
q1.append(root)
while q1 or q2:
res.append([])
if order == 1:
while q1:
node = q1.... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def levelOrder(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def levelOrder2(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = []
if not ... | stack_v2_sparse_classes_36k_train_023007 | 1,923 | permissive | [
{
"docstring": ":type root: TreeNode :rtype: List[List[int]]",
"name": "levelOrder",
"signature": "def levelOrder(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[List[int]]",
"name": "levelOrder2",
"signature": "def levelOrder2(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrder(self, root): :type root: TreeNode :rtype: List[List[int]]
- def levelOrder2(self, root): :type root: TreeNode :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrder(self, root): :type root: TreeNode :rtype: List[List[int]]
- def levelOrder2(self, root): :type root: TreeNode :rtype: List[List[int]]
<|skeleton|>
class Solution:... | 34d34280170c991ea7a28d74a3f2338753844917 | <|skeleton|>
class Solution:
def levelOrder(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def levelOrder2(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def levelOrder(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
res = []
if not root:
return res
q1 = collections.deque()
q2 = collections.deque()
order = 1
q1.append(root)
while q1 or q2:
res.appe... | the_stack_v2_python_sparse | binary_tree_level_order_traversal_102.py | danielsunzhongyuan/my_leetcode_in_python | train | 0 | |
3969dc90b7c962862b6dba2b05616060dc6f6065 | [
"for project_id, instance_groups in resource_from_api.iteritems():\n for instance_group in instance_groups:\n yield {'project_id': project_id, 'id': instance_group.get('id'), 'creation_timestamp': parser.format_timestamp(instance_group.get('creationTimestamp'), self.MYSQL_DATETIME_FORMAT), 'name': instanc... | <|body_start_0|>
for project_id, instance_groups in resource_from_api.iteritems():
for instance_group in instance_groups:
yield {'project_id': project_id, 'id': instance_group.get('id'), 'creation_timestamp': parser.format_timestamp(instance_group.get('creationTimestamp'), self.MYSQL... | Load compute instance groups for all projects. | LoadInstanceGroupsPipeline | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadInstanceGroupsPipeline:
"""Load compute instance groups for all projects."""
def _transform(self, resource_from_api):
"""Create an iterator of instance groups to load into database. Args: resource_from_api (dict): Instance groups, keyed by project id, from GCP API. Yields: iterat... | stack_v2_sparse_classes_36k_train_023008 | 3,722 | permissive | [
{
"docstring": "Create an iterator of instance groups to load into database. Args: resource_from_api (dict): Instance groups, keyed by project id, from GCP API. Yields: iterator: Instance group properties in a dict.",
"name": "_transform",
"signature": "def _transform(self, resource_from_api)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_004651 | Implement the Python class `LoadInstanceGroupsPipeline` described below.
Class description:
Load compute instance groups for all projects.
Method signatures and docstrings:
- def _transform(self, resource_from_api): Create an iterator of instance groups to load into database. Args: resource_from_api (dict): Instance ... | Implement the Python class `LoadInstanceGroupsPipeline` described below.
Class description:
Load compute instance groups for all projects.
Method signatures and docstrings:
- def _transform(self, resource_from_api): Create an iterator of instance groups to load into database. Args: resource_from_api (dict): Instance ... | a6a1aa7464cda2ad5948e3e8876eb8dded5e2514 | <|skeleton|>
class LoadInstanceGroupsPipeline:
"""Load compute instance groups for all projects."""
def _transform(self, resource_from_api):
"""Create an iterator of instance groups to load into database. Args: resource_from_api (dict): Instance groups, keyed by project id, from GCP API. Yields: iterat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoadInstanceGroupsPipeline:
"""Load compute instance groups for all projects."""
def _transform(self, resource_from_api):
"""Create an iterator of instance groups to load into database. Args: resource_from_api (dict): Instance groups, keyed by project id, from GCP API. Yields: iterator: Instance ... | the_stack_v2_python_sparse | google/cloud/security/inventory/pipelines/load_instance_groups_pipeline.py | shimizu19691210/forseti-security | train | 1 |
b1d75ca008dc2c4bc2a9acebac2bcbc494260560 | [
"cfg = self.dnn_cfg\nif cfg.width % 32:\n wh = int(round(cfg.width / 32)) * 32\nelif cfg.height % 32:\n wh = int(round(cfg.height / 32)) * 32\nelse:\n wh = None\nif wh:\n cfg.override(size=(wh, wh))\n self.log.warn(f'YOLO width and height must be multiple of 32. Using width scale to: {wh}')\nself.fra... | <|body_start_0|>
cfg = self.dnn_cfg
if cfg.width % 32:
wh = int(round(cfg.width / 32)) * 32
elif cfg.height % 32:
wh = int(round(cfg.height / 32)) * 32
else:
wh = None
if wh:
cfg.override(size=(wh, wh))
self.log.warn(f'Y... | YOLODarknet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YOLODarknet:
def _pre_process(self, im):
"""Pre-process image"""
<|body_0|>
def _post_process(self, outs):
"""Post process net output for YOLO object detection Network produces output blob with a shape NxC where N is a number of detected objects and C is a number of ... | stack_v2_sparse_classes_36k_train_023009 | 2,708 | permissive | [
{
"docstring": "Pre-process image",
"name": "_pre_process",
"signature": "def _pre_process(self, im)"
},
{
"docstring": "Post process net output for YOLO object detection Network produces output blob with a shape NxC where N is a number of detected objects and C is a number of classes + 4 where ... | 2 | null | Implement the Python class `YOLODarknet` described below.
Class description:
Implement the YOLODarknet class.
Method signatures and docstrings:
- def _pre_process(self, im): Pre-process image
- def _post_process(self, outs): Post process net output for YOLO object detection Network produces output blob with a shape N... | Implement the Python class `YOLODarknet` described below.
Class description:
Implement the YOLODarknet class.
Method signatures and docstrings:
- def _pre_process(self, im): Pre-process image
- def _post_process(self, outs): Post process net output for YOLO object detection Network produces output blob with a shape N... | 5c490cb72607f60e33467a9a0f412d23024e5963 | <|skeleton|>
class YOLODarknet:
def _pre_process(self, im):
"""Pre-process image"""
<|body_0|>
def _post_process(self, outs):
"""Post process net output for YOLO object detection Network produces output blob with a shape NxC where N is a number of detected objects and C is a number of ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class YOLODarknet:
def _pre_process(self, im):
"""Pre-process image"""
cfg = self.dnn_cfg
if cfg.width % 32:
wh = int(round(cfg.width / 32)) * 32
elif cfg.height % 32:
wh = int(round(cfg.height / 32)) * 32
else:
wh = None
if wh:
... | the_stack_v2_python_sparse | src/vframe/image/processors/yolo_darknet.py | vframeio/vframe | train | 50 | |
49a9cd289962c290240368efa084ef814dea3d5c | [
"ebuild_path = 'chromeos-base/platform2/platform2-9999.ebuild'\ncomponents = ['chromeos-base', 'platform2', 'platform2-9999']\nfor path in (ebuild_path, './' + ebuild_path, 'foo.bar/' + ebuild_path):\n self.assertEquals(components, portage_util.SplitEbuildPath(path))",
"pv = 'bar-1.2.3_rc1-r5'\npackage, versio... | <|body_start_0|>
ebuild_path = 'chromeos-base/platform2/platform2-9999.ebuild'
components = ['chromeos-base', 'platform2', 'platform2-9999']
for path in (ebuild_path, './' + ebuild_path, 'foo.bar/' + ebuild_path):
self.assertEquals(components, portage_util.SplitEbuildPath(path))
<|en... | Tests related to Proejct Mapping. | ProjectMappingTest | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectMappingTest:
"""Tests related to Proejct Mapping."""
def testSplitEbuildPath(self):
"""Test if we can split an ebuild path into its components."""
<|body_0|>
def testSplitPV(self):
"""Test splitting PVs into package and version components."""
<|bod... | stack_v2_sparse_classes_36k_train_023010 | 44,982 | permissive | [
{
"docstring": "Test if we can split an ebuild path into its components.",
"name": "testSplitEbuildPath",
"signature": "def testSplitEbuildPath(self)"
},
{
"docstring": "Test splitting PVs into package and version components.",
"name": "testSplitPV",
"signature": "def testSplitPV(self)"
... | 4 | null | Implement the Python class `ProjectMappingTest` described below.
Class description:
Tests related to Proejct Mapping.
Method signatures and docstrings:
- def testSplitEbuildPath(self): Test if we can split an ebuild path into its components.
- def testSplitPV(self): Test splitting PVs into package and version compone... | Implement the Python class `ProjectMappingTest` described below.
Class description:
Tests related to Proejct Mapping.
Method signatures and docstrings:
- def testSplitEbuildPath(self): Test if we can split an ebuild path into its components.
- def testSplitPV(self): Test splitting PVs into package and version compone... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class ProjectMappingTest:
"""Tests related to Proejct Mapping."""
def testSplitEbuildPath(self):
"""Test if we can split an ebuild path into its components."""
<|body_0|>
def testSplitPV(self):
"""Test splitting PVs into package and version components."""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectMappingTest:
"""Tests related to Proejct Mapping."""
def testSplitEbuildPath(self):
"""Test if we can split an ebuild path into its components."""
ebuild_path = 'chromeos-base/platform2/platform2-9999.ebuild'
components = ['chromeos-base', 'platform2', 'platform2-9999']
... | the_stack_v2_python_sparse | third_party/chromite/lib/portage_util_unittest.py | metux/chromium-suckless | train | 5 |
43cba6372cd98ed59049500c685395f4ade5b964 | [
"def dfsSum(root, base):\n if not root:\n return 0\n rt = base * 10 + root.val\n if not root.left and (not root.right):\n return rt\n else:\n return dfsSum(root.left, rt) + dfsSum(root.right, rt)\nreturn dfsSum(root, 0)",
"stk = [(root, 0)]\ns = 0\nwhile stk:\n p = stk.pop()\n ... | <|body_start_0|>
def dfsSum(root, base):
if not root:
return 0
rt = base * 10 + root.val
if not root.left and (not root.right):
return rt
else:
return dfsSum(root.left, rt) + dfsSum(root.right, rt)
return dfs... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sumNumbers_dfs(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def sumNumbers_recuisive(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
def sumNumbers_bfs(self, root):
""":type root: TreeNode :rtype: in... | stack_v2_sparse_classes_36k_train_023011 | 1,781 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "sumNumbers_dfs",
"signature": "def sumNumbers_dfs(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "sumNumbers_recuisive",
"signature": "def sumNumbers_recuisive(self, root)"
},
{
"docstring": "... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumNumbers_dfs(self, root): :type root: TreeNode :rtype: int
- def sumNumbers_recuisive(self, root): :type root: TreeNode :rtype: int
- def sumNumbers_bfs(self, root): :type ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumNumbers_dfs(self, root): :type root: TreeNode :rtype: int
- def sumNumbers_recuisive(self, root): :type root: TreeNode :rtype: int
- def sumNumbers_bfs(self, root): :type ... | 0e99f9a5226507706b3ee66fd04bae813755ef40 | <|skeleton|>
class Solution:
def sumNumbers_dfs(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def sumNumbers_recuisive(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
def sumNumbers_bfs(self, root):
""":type root: TreeNode :rtype: in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sumNumbers_dfs(self, root):
""":type root: TreeNode :rtype: int"""
def dfsSum(root, base):
if not root:
return 0
rt = base * 10 + root.val
if not root.left and (not root.right):
return rt
else:
... | the_stack_v2_python_sparse | medium/tree/test_129_Sum_Root_to_Leaf_Numbers.py | wuxu1019/leetcode_sophia | train | 1 | |
a1d5e7eaf1af13478f592cc8054788993b873189 | [
"super(CopyTask, self).__init__(*args, **kwargs)\nself.setMetadata('dispatch.split', True)\nself.setMetadata('dispatch.splitSize', 20)",
"for crawler in self.crawlers():\n filePath = self.target(crawler)\n try:\n os.makedirs(os.path.dirname(filePath))\n except OSError:\n pass\n sourceFil... | <|body_start_0|>
super(CopyTask, self).__init__(*args, **kwargs)
self.setMetadata('dispatch.split', True)
self.setMetadata('dispatch.splitSize', 20)
<|end_body_0|>
<|body_start_1|>
for crawler in self.crawlers():
filePath = self.target(crawler)
try:
... | Copies a file to the filePath. | CopyTask | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CopyTask:
"""Copies a file to the filePath."""
def __init__(self, *args, **kwargs):
"""Create a CopyTask task."""
<|body_0|>
def _perform(self):
"""Perform the task."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(CopyTask, self).__init__(... | stack_v2_sparse_classes_36k_train_023012 | 1,671 | permissive | [
{
"docstring": "Create a CopyTask task.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Perform the task.",
"name": "_perform",
"signature": "def _perform(self)"
}
] | 2 | null | Implement the Python class `CopyTask` described below.
Class description:
Copies a file to the filePath.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create a CopyTask task.
- def _perform(self): Perform the task. | Implement the Python class `CopyTask` described below.
Class description:
Copies a file to the filePath.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create a CopyTask task.
- def _perform(self): Perform the task.
<|skeleton|>
class CopyTask:
"""Copies a file to the filePath."""
... | 046dbb0c1b4ff20ea5f2e1679f8d89f3089b6aa4 | <|skeleton|>
class CopyTask:
"""Copies a file to the filePath."""
def __init__(self, *args, **kwargs):
"""Create a CopyTask task."""
<|body_0|>
def _perform(self):
"""Perform the task."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CopyTask:
"""Copies a file to the filePath."""
def __init__(self, *args, **kwargs):
"""Create a CopyTask task."""
super(CopyTask, self).__init__(*args, **kwargs)
self.setMetadata('dispatch.split', True)
self.setMetadata('dispatch.splitSize', 20)
def _perform(self):
... | the_stack_v2_python_sparse | src/lib/kombi/Task/Fs/CopyTask.py | kombiHQ/kombi | train | 2 |
84f6f9206b1e7c91ec3abb807cff1a4b56950ce8 | [
"data = {}\nif not self.url or '?' not in self.url:\n return data\nsplit_fields = self.url.replace('#info-right', '').split('?')[1].split('&')\nfor field in split_fields:\n pair = field.split('=')\n data[pair[0]] = pair[1]\nreturn data",
"if not self.url:\n return None\nrow = self.parsed_url\nif row a... | <|body_start_0|>
data = {}
if not self.url or '?' not in self.url:
return data
split_fields = self.url.replace('#info-right', '').split('?')[1].split('&')
for field in split_fields:
pair = field.split('=')
data[pair[0]] = pair[1]
return data
<|... | Abstract base class for disclosure-related interactions | DisclosureBase | [
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DisclosureBase:
"""Abstract base class for disclosure-related interactions"""
def parsed_url(self):
"""parses a disclosure URL and returns a field:value dict"""
<|body_0|>
def school(self):
"""Returns a school object, derived from a feedback url"""
<|body... | stack_v2_sparse_classes_36k_train_023013 | 31,435 | permissive | [
{
"docstring": "parses a disclosure URL and returns a field:value dict",
"name": "parsed_url",
"signature": "def parsed_url(self)"
},
{
"docstring": "Returns a school object, derived from a feedback url",
"name": "school",
"signature": "def school(self)"
},
{
"docstring": "Calcul... | 5 | stack_v2_sparse_classes_30k_train_009992 | Implement the Python class `DisclosureBase` described below.
Class description:
Abstract base class for disclosure-related interactions
Method signatures and docstrings:
- def parsed_url(self): parses a disclosure URL and returns a field:value dict
- def school(self): Returns a school object, derived from a feedback ... | Implement the Python class `DisclosureBase` described below.
Class description:
Abstract base class for disclosure-related interactions
Method signatures and docstrings:
- def parsed_url(self): parses a disclosure URL and returns a field:value dict
- def school(self): Returns a school object, derived from a feedback ... | 7c63c31fd6bb95ed4f7d368f1e1252175f0c71ca | <|skeleton|>
class DisclosureBase:
"""Abstract base class for disclosure-related interactions"""
def parsed_url(self):
"""parses a disclosure URL and returns a field:value dict"""
<|body_0|>
def school(self):
"""Returns a school object, derived from a feedback url"""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DisclosureBase:
"""Abstract base class for disclosure-related interactions"""
def parsed_url(self):
"""parses a disclosure URL and returns a field:value dict"""
data = {}
if not self.url or '?' not in self.url:
return data
split_fields = self.url.replace('#info... | the_stack_v2_python_sparse | cfgov/paying_for_college/models/disclosures.py | raft-tech/cfgov-refresh | train | 4 |
91ff456eec8fb1c6dd81c91e33e58bb700157511 | [
"FeatureDefinition.__init__(self)\nnbTypes = self._getTypeNumber(kwargs)\nprint('BETTER FEATURES')\nblock_transformer = FeatureUnion([('xywh', Pipeline([('selector', NodeTransformerXYWH_v2()), ('xywh', QuantileTransformer(n_quantiles=self.n_QUANTILES, copy=False))])), ('neighbors', Pipeline([('selector', NodeTransf... | <|body_start_0|>
FeatureDefinition.__init__(self)
nbTypes = self._getTypeNumber(kwargs)
print('BETTER FEATURES')
block_transformer = FeatureUnion([('xywh', Pipeline([('selector', NodeTransformerXYWH_v2()), ('xywh', QuantileTransformer(n_quantiles=self.n_QUANTILES, copy=False))])), ('neig... | Multitype version: so the node_transformer actually is a list of node_transformer of length n_class the edge_transformer actually is a list of node_transformer of length n_class^2 We also inherit from FeatureDefinition_T !!! | My_FeatureDefinition_v2 | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class My_FeatureDefinition_v2:
"""Multitype version: so the node_transformer actually is a list of node_transformer of length n_class the edge_transformer actually is a list of node_transformer of length n_class^2 We also inherit from FeatureDefinition_T !!!"""
def __init__(self, **kwargs):
... | stack_v2_sparse_classes_36k_train_023014 | 9,141 | permissive | [
{
"docstring": "set _node_transformer, _edge_transformer, tdifNodeTextVectorizer",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Fit the transformers using the graphs, but TYPE BY TYPE !!! return True",
"name": "fitTranformers",
"signature": "def fitT... | 2 | stack_v2_sparse_classes_30k_train_007554 | Implement the Python class `My_FeatureDefinition_v2` described below.
Class description:
Multitype version: so the node_transformer actually is a list of node_transformer of length n_class the edge_transformer actually is a list of node_transformer of length n_class^2 We also inherit from FeatureDefinition_T !!!
Meth... | Implement the Python class `My_FeatureDefinition_v2` described below.
Class description:
Multitype version: so the node_transformer actually is a list of node_transformer of length n_class the edge_transformer actually is a list of node_transformer of length n_class^2 We also inherit from FeatureDefinition_T !!!
Meth... | 9f2fed81672dc222ca52ee4329eac3126b500d21 | <|skeleton|>
class My_FeatureDefinition_v2:
"""Multitype version: so the node_transformer actually is a list of node_transformer of length n_class the edge_transformer actually is a list of node_transformer of length n_class^2 We also inherit from FeatureDefinition_T !!!"""
def __init__(self, **kwargs):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class My_FeatureDefinition_v2:
"""Multitype version: so the node_transformer actually is a list of node_transformer of length n_class the edge_transformer actually is a list of node_transformer of length n_class^2 We also inherit from FeatureDefinition_T !!!"""
def __init__(self, **kwargs):
"""set _nod... | the_stack_v2_python_sparse | TranskribusDU/tasks/TablePrototypes/DU_ABPTableRG2.py | Transkribus/TranskribusDU | train | 24 |
65b250f783047d680d35ebac429a3658e12390b5 | [
"super().__init__()\nself.forward_func = forward_func\nself.loss_func = loss_func\nself.bound = lambda x: torch.clamp(x, min=lower_bound, max=upper_bound)\nself.zero_thresh = 10 ** (-6)",
"is_inputs_tuple = _is_tuple(inputs)\ninputs: Tuple[Tensor, ...] = _format_tensor_into_tuples(inputs)\nmasks: Union[Tuple[int,... | <|body_start_0|>
super().__init__()
self.forward_func = forward_func
self.loss_func = loss_func
self.bound = lambda x: torch.clamp(x, min=lower_bound, max=upper_bound)
self.zero_thresh = 10 ** (-6)
<|end_body_0|>
<|body_start_1|>
is_inputs_tuple = _is_tuple(inputs)
... | Fast Gradient Sign Method is a one-step method that can generate adversarial examples. For non-targeted attack, the formulation is:: x' = x + epsilon * sign(gradient of L(theta, x, y)) For targeted attack on t, the formulation is:: x' = x - epsilon * sign(gradient of L(theta, x, t)) ``L(theta, x, y)`` is the model's lo... | FGSM | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FGSM:
"""Fast Gradient Sign Method is a one-step method that can generate adversarial examples. For non-targeted attack, the formulation is:: x' = x + epsilon * sign(gradient of L(theta, x, y)) For targeted attack on t, the formulation is:: x' = x - epsilon * sign(gradient of L(theta, x, t)) ``L(... | stack_v2_sparse_classes_36k_train_023015 | 8,725 | permissive | [
{
"docstring": "Args: forward_func (Callable): The pytorch model for which the attack is computed. loss_func (Callable, optional): Loss function of which the gradient computed. The loss function should take in outputs of the model and labels, and return a loss tensor. The default loss function is negative log. ... | 3 | stack_v2_sparse_classes_30k_train_017071 | Implement the Python class `FGSM` described below.
Class description:
Fast Gradient Sign Method is a one-step method that can generate adversarial examples. For non-targeted attack, the formulation is:: x' = x + epsilon * sign(gradient of L(theta, x, y)) For targeted attack on t, the formulation is:: x' = x - epsilon ... | Implement the Python class `FGSM` described below.
Class description:
Fast Gradient Sign Method is a one-step method that can generate adversarial examples. For non-targeted attack, the formulation is:: x' = x + epsilon * sign(gradient of L(theta, x, y)) For targeted attack on t, the formulation is:: x' = x - epsilon ... | 945c582cc0b08885c4e2bfecb020abdfac0122f3 | <|skeleton|>
class FGSM:
"""Fast Gradient Sign Method is a one-step method that can generate adversarial examples. For non-targeted attack, the formulation is:: x' = x + epsilon * sign(gradient of L(theta, x, y)) For targeted attack on t, the formulation is:: x' = x - epsilon * sign(gradient of L(theta, x, t)) ``L(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FGSM:
"""Fast Gradient Sign Method is a one-step method that can generate adversarial examples. For non-targeted attack, the formulation is:: x' = x + epsilon * sign(gradient of L(theta, x, y)) For targeted attack on t, the formulation is:: x' = x - epsilon * sign(gradient of L(theta, x, t)) ``L(theta, x, y)`... | the_stack_v2_python_sparse | captum/robust/_core/fgsm.py | pytorch/captum | train | 4,230 |
7a53427c2b19e39e219c77b79603212d8ac9029f | [
"self.R = R\nself.B = B\nself.N_leaves = N_leaves\nself.alignment = alignment",
"X = [math.exp(x) for x in X_logs]\nB_subs = {}\nfor v_parent, v_child in self.R:\n edge = frozenset([v_parent, v_child])\n r = X[v_child]\n t = self.B[edge]\n B_subs[edge] = r * t\nnewick_string = FtreeIO.RBN_to_newick(se... | <|body_start_0|>
self.R = R
self.B = B
self.N_leaves = N_leaves
self.alignment = alignment
<|end_body_0|>
<|body_start_1|>
X = [math.exp(x) for x in X_logs]
B_subs = {}
for v_parent, v_child in self.R:
edge = frozenset([v_parent, v_child])
... | This is for maximum likelihood search of lineage rates. | Opt | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Opt:
"""This is for maximum likelihood search of lineage rates."""
def __init__(self, R, B, N_leaves, alignment):
"""The vertices should be consecutive integers starting at zero. The largest vertex should be the root."""
<|body_0|>
def __call__(self, X_logs):
"""... | stack_v2_sparse_classes_36k_train_023016 | 18,637 | no_license | [
{
"docstring": "The vertices should be consecutive integers starting at zero. The largest vertex should be the root.",
"name": "__init__",
"signature": "def __init__(self, R, B, N_leaves, alignment)"
},
{
"docstring": "The vth entry of X corresponds to the log rate of the branch above v. Return ... | 2 | stack_v2_sparse_classes_30k_train_004493 | Implement the Python class `Opt` described below.
Class description:
This is for maximum likelihood search of lineage rates.
Method signatures and docstrings:
- def __init__(self, R, B, N_leaves, alignment): The vertices should be consecutive integers starting at zero. The largest vertex should be the root.
- def __c... | Implement the Python class `Opt` described below.
Class description:
This is for maximum likelihood search of lineage rates.
Method signatures and docstrings:
- def __init__(self, R, B, N_leaves, alignment): The vertices should be consecutive integers starting at zero. The largest vertex should be the root.
- def __c... | 91c6f8331f18c914eb3dfc51bc166915998c5081 | <|skeleton|>
class Opt:
"""This is for maximum likelihood search of lineage rates."""
def __init__(self, R, B, N_leaves, alignment):
"""The vertices should be consecutive integers starting at zero. The largest vertex should be the root."""
<|body_0|>
def __call__(self, X_logs):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Opt:
"""This is for maximum likelihood search of lineage rates."""
def __init__(self, R, B, N_leaves, alignment):
"""The vertices should be consecutive integers starting at zero. The largest vertex should be the root."""
self.R = R
self.B = B
self.N_leaves = N_leaves
... | the_stack_v2_python_sparse | 20120403a.py | argriffing/xgcode | train | 1 |
c8c13e327eb79364fc25a3b4f759301b3f28bf8f | [
"FileUtils.CreateLink(FileUtils.GetEDir(), FileUtils.GetBinDir())\nif os.path.exists(FileUtils.GetWebTestHtmlLink()):\n FileUtils.CreateLink(FileUtils.GetWebTestHtmlLink(), FileUtils.GetWebTestHtmlDir())\ngen_makefile = GenMakefile(Flags.ARGS.debug)\ngen_makefile.GenMainMakeFile()\nsuccess_genmake, failed_genmak... | <|body_start_0|>
FileUtils.CreateLink(FileUtils.GetEDir(), FileUtils.GetBinDir())
if os.path.exists(FileUtils.GetWebTestHtmlLink()):
FileUtils.CreateLink(FileUtils.GetWebTestHtmlLink(), FileUtils.GetWebTestHtmlDir())
gen_makefile = GenMakefile(Flags.ARGS.debug)
gen_makefile.G... | Class to handle build. | Builder | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Builder:
"""Class to handle build."""
def WorkHorse(cls, rules):
"""Runs the workhorse for the command. Args: rules: list: List of rules to be handled. Return: (list, list): Returns a tuple of list in the form (successful_rules, failed_rules) specifying rules that succeeded and ones ... | stack_v2_sparse_classes_36k_train_023017 | 3,912 | permissive | [
{
"docstring": "Runs the workhorse for the command. Args: rules: list: List of rules to be handled. Return: (list, list): Returns a tuple of list in the form (successful_rules, failed_rules) specifying rules that succeeded and ones that failed.",
"name": "WorkHorse",
"signature": "def WorkHorse(cls, rul... | 3 | stack_v2_sparse_classes_30k_test_000831 | Implement the Python class `Builder` described below.
Class description:
Class to handle build.
Method signatures and docstrings:
- def WorkHorse(cls, rules): Runs the workhorse for the command. Args: rules: list: List of rules to be handled. Return: (list, list): Returns a tuple of list in the form (successful_rules... | Implement the Python class `Builder` described below.
Class description:
Class to handle build.
Method signatures and docstrings:
- def WorkHorse(cls, rules): Runs the workhorse for the command. Args: rules: list: List of rules to be handled. Return: (list, list): Returns a tuple of list in the form (successful_rules... | 70280110ec342a6f6db1c102e96756fcc3c3c01b | <|skeleton|>
class Builder:
"""Class to handle build."""
def WorkHorse(cls, rules):
"""Runs the workhorse for the command. Args: rules: list: List of rules to be handled. Return: (list, list): Returns a tuple of list in the form (successful_rules, failed_rules) specifying rules that succeeded and ones ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Builder:
"""Class to handle build."""
def WorkHorse(cls, rules):
"""Runs the workhorse for the command. Args: rules: list: List of rules to be handled. Return: (list, list): Returns a tuple of list in the form (successful_rules, failed_rules) specifying rules that succeeded and ones that failed."... | the_stack_v2_python_sparse | pylib/flash/build.py | room77/py77 | train | 0 |
32b464885e7af08e47856a4b21b072ffd93bd536 | [
"self.building_use_type_param_id = building_use_type_param_id\nself.elevator_type_param_id = elevator_type_param_id\nself.floors = floors\nself.elevator_capacity_cargo = elevator_capacity_cargo\nself.elevator_capacity = elevator_capacity\nself.risk_level_id = risk_level_id\nself.insurance_policy_terms = insurance_p... | <|body_start_0|>
self.building_use_type_param_id = building_use_type_param_id
self.elevator_type_param_id = elevator_type_param_id
self.floors = floors
self.elevator_capacity_cargo = elevator_capacity_cargo
self.elevator_capacity = elevator_capacity
self.risk_level_id = r... | Implementation of the 'ElevatorInsurancePolicyFilter' model. TODO: type model description here. Attributes: building_use_type_param_id (string): TODO: type description here. elevator_type_param_id (string): TODO: type description here. floors (string): TODO: type description here. elevator_capacity_cargo (string): TODO... | ElevatorInsurancePolicyFilter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElevatorInsurancePolicyFilter:
"""Implementation of the 'ElevatorInsurancePolicyFilter' model. TODO: type model description here. Attributes: building_use_type_param_id (string): TODO: type description here. elevator_type_param_id (string): TODO: type description here. floors (string): TODO: type... | stack_v2_sparse_classes_36k_train_023018 | 7,877 | permissive | [
{
"docstring": "Constructor for the ElevatorInsurancePolicyFilter class",
"name": "__init__",
"signature": "def __init__(self, owner_coverage=None, is_search_query=None, building_use_type_param_id=None, elevator_type_param_id=None, floors=None, elevator_capacity_cargo=None, elevator_capacity=None, risk_... | 2 | stack_v2_sparse_classes_30k_train_002570 | Implement the Python class `ElevatorInsurancePolicyFilter` described below.
Class description:
Implementation of the 'ElevatorInsurancePolicyFilter' model. TODO: type model description here. Attributes: building_use_type_param_id (string): TODO: type description here. elevator_type_param_id (string): TODO: type descri... | Implement the Python class `ElevatorInsurancePolicyFilter` described below.
Class description:
Implementation of the 'ElevatorInsurancePolicyFilter' model. TODO: type model description here. Attributes: building_use_type_param_id (string): TODO: type description here. elevator_type_param_id (string): TODO: type descri... | b574a76a8805b306a423229b572c36dae0159def | <|skeleton|>
class ElevatorInsurancePolicyFilter:
"""Implementation of the 'ElevatorInsurancePolicyFilter' model. TODO: type model description here. Attributes: building_use_type_param_id (string): TODO: type description here. elevator_type_param_id (string): TODO: type description here. floors (string): TODO: type... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ElevatorInsurancePolicyFilter:
"""Implementation of the 'ElevatorInsurancePolicyFilter' model. TODO: type model description here. Attributes: building_use_type_param_id (string): TODO: type description here. elevator_type_param_id (string): TODO: type description here. floors (string): TODO: type description ... | the_stack_v2_python_sparse | easybimehlanding/models/elevator_insurance_policy_filter.py | kmelodi/EasyBimehLanding_Python | train | 0 |
cd53676714d2a0786986abfc8454c325f43b6803 | [
"gtk.Frame.__init__(self)\nself.contents = contents\nself.contentBox = gtk.VBox()\nself.contentBox.pack_start(self.contents, True, True, 0)\nself.add(self.contentBox)\nframeWidget = gtk.Expander(title)\nframeWidget.connect('notify::expanded', self._toggle_content_box)\nself.set_label_widget(frameWidget)\nself.show_... | <|body_start_0|>
gtk.Frame.__init__(self)
self.contents = contents
self.contentBox = gtk.VBox()
self.contentBox.pack_start(self.contents, True, True, 0)
self.add(self.contentBox)
frameWidget = gtk.Expander(title)
frameWidget.connect('notify::expanded', self._toggl... | A frame with a toggle button and a title that can show or hide its contents | OptionalToggleFrame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptionalToggleFrame:
"""A frame with a toggle button and a title that can show or hide its contents"""
def __init__(self, contents, title=None, startHidden=True):
"""contents should be a container of some sort to be packed into the frame @param title: the frame title of course @type ... | stack_v2_sparse_classes_36k_train_023019 | 1,230 | no_license | [
{
"docstring": "contents should be a container of some sort to be packed into the frame @param title: the frame title of course @type title: string",
"name": "__init__",
"signature": "def __init__(self, contents, title=None, startHidden=True)"
},
{
"docstring": "shows or hides the contents",
... | 2 | null | Implement the Python class `OptionalToggleFrame` described below.
Class description:
A frame with a toggle button and a title that can show or hide its contents
Method signatures and docstrings:
- def __init__(self, contents, title=None, startHidden=True): contents should be a container of some sort to be packed into... | Implement the Python class `OptionalToggleFrame` described below.
Class description:
A frame with a toggle button and a title that can show or hide its contents
Method signatures and docstrings:
- def __init__(self, contents, title=None, startHidden=True): contents should be a container of some sort to be packed into... | a47152d558081a9ebeb5630acfe5f46a49ab4246 | <|skeleton|>
class OptionalToggleFrame:
"""A frame with a toggle button and a title that can show or hide its contents"""
def __init__(self, contents, title=None, startHidden=True):
"""contents should be a container of some sort to be packed into the frame @param title: the frame title of course @type ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OptionalToggleFrame:
"""A frame with a toggle button and a title that can show or hide its contents"""
def __init__(self, contents, title=None, startHidden=True):
"""contents should be a container of some sort to be packed into the frame @param title: the frame title of course @type title: string... | the_stack_v2_python_sparse | client/gui/gtk/widget/OptionalToggleFrame.py | clawplach/BitBlinder | train | 0 |
7e23f7f706da45b6f8ad1fc8ec1bde009a0c8ca8 | [
"self.obj_type = ''\nself.truncated = float(-1.0)\nself.occlusion = int(-1)\nself.observ_angle = float(-10.0)\nself.box2d_x1 = float(0.0)\nself.box2d_y1 = float(0.0)\nself.box2d_x2 = float(0.0)\nself.box2d_y2 = float(0.0)\nself.box3d_height = float(-1)\nself.box3d_width = float(-1)\nself.box3d_length = float(-1)\ns... | <|body_start_0|>
self.obj_type = ''
self.truncated = float(-1.0)
self.occlusion = int(-1)
self.observ_angle = float(-10.0)
self.box2d_x1 = float(0.0)
self.box2d_y1 = float(0.0)
self.box2d_x2 = float(0.0)
self.box2d_y2 = float(0.0)
self.box3d_height... | The KittiDetection class represents an entry in the kitti object detection results file. It provides default values and the right structure for the string line to be saved in an output file in the kitti object detection format. | KittiDetection | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KittiDetection:
"""The KittiDetection class represents an entry in the kitti object detection results file. It provides default values and the right structure for the string line to be saved in an output file in the kitti object detection format."""
def __init__(self):
"""Create a Ki... | stack_v2_sparse_classes_36k_train_023020 | 12,335 | permissive | [
{
"docstring": "Create a KittiDetection object.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Return a string representing a detection. It is properly formatted for kitti object detection benchmark. @return: str",
"name": "to_string",
"signature": "def to_str... | 2 | null | Implement the Python class `KittiDetection` described below.
Class description:
The KittiDetection class represents an entry in the kitti object detection results file. It provides default values and the right structure for the string line to be saved in an output file in the kitti object detection format.
Method sig... | Implement the Python class `KittiDetection` described below.
Class description:
The KittiDetection class represents an entry in the kitti object detection results file. It provides default values and the right structure for the string line to be saved in an output file in the kitti object detection format.
Method sig... | ff8950abbb72366ed3072de790c405de8875ecc3 | <|skeleton|>
class KittiDetection:
"""The KittiDetection class represents an entry in the kitti object detection results file. It provides default values and the right structure for the string line to be saved in an output file in the kitti object detection format."""
def __init__(self):
"""Create a Ki... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KittiDetection:
"""The KittiDetection class represents an entry in the kitti object detection results file. It provides default values and the right structure for the string line to be saved in an output file in the kitti object detection format."""
def __init__(self):
"""Create a KittiDetection ... | the_stack_v2_python_sparse | src/tools/benchmark_tool/benchmark_tool/kittiobjdetsdk/kitti_obj_detection_utils.py | bytetok/vde | train | 0 |
a07ba5c45fb5217290c9325946ba4963b07b7852 | [
"if 'OC' not in value:\n raise serializers.ValidationError('The car must have OC')\nreturn value",
"car_id = data['car'].id\nleasing = 'L'\ninsurance = data['type_of_insurance']\ncar_qs = Car.objects.filter(id=car_id)\nif not car_qs.exists():\n raise serializers.ValidationError('This car not exist...!')\nca... | <|body_start_0|>
if 'OC' not in value:
raise serializers.ValidationError('The car must have OC')
return value
<|end_body_0|>
<|body_start_1|>
car_id = data['car'].id
leasing = 'L'
insurance = data['type_of_insurance']
car_qs = Car.objects.filter(id=car_id)
... | InsuranceSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InsuranceSerializer:
def validate_type_of_insurance(self, value):
"""Validation of type of insurance. Checks if the car has compulsory OC insurance."""
<|body_0|>
def validate(self, data):
"""Validation of car data and insurance data relation. Checks that if the car ... | stack_v2_sparse_classes_36k_train_023021 | 1,814 | no_license | [
{
"docstring": "Validation of type of insurance. Checks if the car has compulsory OC insurance.",
"name": "validate_type_of_insurance",
"signature": "def validate_type_of_insurance(self, value)"
},
{
"docstring": "Validation of car data and insurance data relation. Checks that if the car is leas... | 2 | stack_v2_sparse_classes_30k_train_020377 | Implement the Python class `InsuranceSerializer` described below.
Class description:
Implement the InsuranceSerializer class.
Method signatures and docstrings:
- def validate_type_of_insurance(self, value): Validation of type of insurance. Checks if the car has compulsory OC insurance.
- def validate(self, data): Val... | Implement the Python class `InsuranceSerializer` described below.
Class description:
Implement the InsuranceSerializer class.
Method signatures and docstrings:
- def validate_type_of_insurance(self, value): Validation of type of insurance. Checks if the car has compulsory OC insurance.
- def validate(self, data): Val... | 2201042cf7893c1e78e92cbc10e129a2631bf2a4 | <|skeleton|>
class InsuranceSerializer:
def validate_type_of_insurance(self, value):
"""Validation of type of insurance. Checks if the car has compulsory OC insurance."""
<|body_0|>
def validate(self, data):
"""Validation of car data and insurance data relation. Checks that if the car ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InsuranceSerializer:
def validate_type_of_insurance(self, value):
"""Validation of type of insurance. Checks if the car has compulsory OC insurance."""
if 'OC' not in value:
raise serializers.ValidationError('The car must have OC')
return value
def validate(self, data)... | the_stack_v2_python_sparse | car_rental/rent/serializers/insurance.py | IzabelaTymoszuk/car_rental_rest | train | 0 | |
bcb887e2d2149c6acfbc481b0eef11ae275d3a8f | [
"params = Differ.get_valid_params()\nparams.add_param('rel_err', '', 'Relative Error for csv files')\nparams.add_param('zero_threshold', sys.float_info.min * 4.0, 'it represents ' + 'the value below which a float is considered zero (XML comparison only)')\nparams.add_param('ignore_sign', False, 'if true, then only ... | <|body_start_0|>
params = Differ.get_valid_params()
params.add_param('rel_err', '', 'Relative Error for csv files')
params.add_param('zero_threshold', sys.float_info.min * 4.0, 'it represents ' + 'the value below which a float is considered zero (XML comparison only)')
params.add_param('... | This is the class to use for handling the parameters block. | OrderedCSV | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrderedCSV:
"""This is the class to use for handling the parameters block."""
def get_valid_params():
"""Returns the valid parameters for this class. @ In, None @ Out, params, _ValidParameters, return the parameters."""
<|body_0|>
def __init__(self, name, params, test_di... | stack_v2_sparse_classes_36k_train_023022 | 10,387 | permissive | [
{
"docstring": "Returns the valid parameters for this class. @ In, None @ Out, params, _ValidParameters, return the parameters.",
"name": "get_valid_params",
"signature": "def get_valid_params()"
},
{
"docstring": "Initializer for the class. Takes a String name and a dictionary params @ In, name... | 3 | null | Implement the Python class `OrderedCSV` described below.
Class description:
This is the class to use for handling the parameters block.
Method signatures and docstrings:
- def get_valid_params(): Returns the valid parameters for this class. @ In, None @ Out, params, _ValidParameters, return the parameters.
- def __in... | Implement the Python class `OrderedCSV` described below.
Class description:
This is the class to use for handling the parameters block.
Method signatures and docstrings:
- def get_valid_params(): Returns the valid parameters for this class. @ In, None @ Out, params, _ValidParameters, return the parameters.
- def __in... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class OrderedCSV:
"""This is the class to use for handling the parameters block."""
def get_valid_params():
"""Returns the valid parameters for this class. @ In, None @ Out, params, _ValidParameters, return the parameters."""
<|body_0|>
def __init__(self, name, params, test_di... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OrderedCSV:
"""This is the class to use for handling the parameters block."""
def get_valid_params():
"""Returns the valid parameters for this class. @ In, None @ Out, params, _ValidParameters, return the parameters."""
params = Differ.get_valid_params()
params.add_param('rel_err'... | the_stack_v2_python_sparse | rook/OrderedCSVDiffer.py | idaholab/raven | train | 201 |
dd4e8dd9fe073747786f729ea5d57c32bbcb92ad | [
"super(APIDomainLimitsTestCase, cls).setUpTestData()\ncls.localconfig.parameters.set_value('enable_domain_limits', True)\nfor name, _definition in utils.get_domain_limit_templates():\n cls.localconfig.parameters.set_value('deflt_domain_{0}_limit'.format(name), 2)\ncls.localconfig.save()\npopulate_database()",
... | <|body_start_0|>
super(APIDomainLimitsTestCase, cls).setUpTestData()
cls.localconfig.parameters.set_value('enable_domain_limits', True)
for name, _definition in utils.get_domain_limit_templates():
cls.localconfig.parameters.set_value('deflt_domain_{0}_limit'.format(name), 2)
... | Check that limits are used also by the API. | APIDomainLimitsTestCase | [
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class APIDomainLimitsTestCase:
"""Check that limits are used also by the API."""
def setUpTestData(cls):
"""Create test data."""
<|body_0|>
def test_mailboxes_limit(self):
"""Check mailboxes limit."""
<|body_1|>
def test_domain_aliases_limit(self):
... | stack_v2_sparse_classes_36k_train_023023 | 13,614 | permissive | [
{
"docstring": "Create test data.",
"name": "setUpTestData",
"signature": "def setUpTestData(cls)"
},
{
"docstring": "Check mailboxes limit.",
"name": "test_mailboxes_limit",
"signature": "def test_mailboxes_limit(self)"
},
{
"docstring": "Check domain_aliases limit.",
"name"... | 4 | null | Implement the Python class `APIDomainLimitsTestCase` described below.
Class description:
Check that limits are used also by the API.
Method signatures and docstrings:
- def setUpTestData(cls): Create test data.
- def test_mailboxes_limit(self): Check mailboxes limit.
- def test_domain_aliases_limit(self): Check domai... | Implement the Python class `APIDomainLimitsTestCase` described below.
Class description:
Check that limits are used also by the API.
Method signatures and docstrings:
- def setUpTestData(cls): Create test data.
- def test_mailboxes_limit(self): Check mailboxes limit.
- def test_domain_aliases_limit(self): Check domai... | df699aab0799ec1725b6b89be38e56285821c889 | <|skeleton|>
class APIDomainLimitsTestCase:
"""Check that limits are used also by the API."""
def setUpTestData(cls):
"""Create test data."""
<|body_0|>
def test_mailboxes_limit(self):
"""Check mailboxes limit."""
<|body_1|>
def test_domain_aliases_limit(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class APIDomainLimitsTestCase:
"""Check that limits are used also by the API."""
def setUpTestData(cls):
"""Create test data."""
super(APIDomainLimitsTestCase, cls).setUpTestData()
cls.localconfig.parameters.set_value('enable_domain_limits', True)
for name, _definition in utils.... | the_stack_v2_python_sparse | modoboa/limits/api/v1/tests.py | modoboa/modoboa | train | 2,201 |
18caca1a2a63fb5b6fdcf091f66659ed18b841c2 | [
"super().__init__()\nself.largo = 75\nself.alto = 15\nself.image = pygame.Surface([self.largo, self.alto])\nself.image.fill(BLANCO)\nself.rect = self.image.get_rect()\nself.alto_pantalla = pygame.display.get_surface().get_height()\nself.largo_pantalla = pygame.display.get_surface().get_width()\nself.rect.x = 0\nsel... | <|body_start_0|>
super().__init__()
self.largo = 75
self.alto = 15
self.image = pygame.Surface([self.largo, self.alto])
self.image.fill(BLANCO)
self.rect = self.image.get_rect()
self.alto_pantalla = pygame.display.get_surface().get_height()
self.largo_pant... | Esta clase representa la barra de la parte inferior que controla el protagonista. | Protagonista | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Protagonista:
"""Esta clase representa la barra de la parte inferior que controla el protagonista."""
def __init__(self):
"""Constructor para Protagonista."""
<|body_0|>
def update(self):
"""Actualiza la posición del protagonista."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k_train_023024 | 8,991 | no_license | [
{
"docstring": "Constructor para Protagonista.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Actualiza la posición del protagonista.",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001769 | Implement the Python class `Protagonista` described below.
Class description:
Esta clase representa la barra de la parte inferior que controla el protagonista.
Method signatures and docstrings:
- def __init__(self): Constructor para Protagonista.
- def update(self): Actualiza la posición del protagonista. | Implement the Python class `Protagonista` described below.
Class description:
Esta clase representa la barra de la parte inferior que controla el protagonista.
Method signatures and docstrings:
- def __init__(self): Constructor para Protagonista.
- def update(self): Actualiza la posición del protagonista.
<|skeleton... | 795125ba99cf93d9be50de0fc4947748094e6624 | <|skeleton|>
class Protagonista:
"""Esta clase representa la barra de la parte inferior que controla el protagonista."""
def __init__(self):
"""Constructor para Protagonista."""
<|body_0|>
def update(self):
"""Actualiza la posición del protagonista."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Protagonista:
"""Esta clase representa la barra de la parte inferior que controla el protagonista."""
def __init__(self):
"""Constructor para Protagonista."""
super().__init__()
self.largo = 75
self.alto = 15
self.image = pygame.Surface([self.largo, self.alto])
... | the_stack_v2_python_sparse | material para juegos/destruirBloques.py | AlejoObandoGil/python-programacion-de-videojuegos | train | 1 |
6878907f9fd3b3ae273e4c58d5ecb2091a4a5da0 | [
"if not self.queue:\n return '#'\nelse:\n return self.queue[0]",
"if char in self.d.keys():\n self.d[char] += 1\nelse:\n self.d[char] = 1\n self.queue.append(char)\nwhile self.queue and self.d[self.queue[0]] > 1:\n self.queue.pop(0)"
] | <|body_start_0|>
if not self.queue:
return '#'
else:
return self.queue[0]
<|end_body_0|>
<|body_start_1|>
if char in self.d.keys():
self.d[char] += 1
else:
self.d[char] = 1
self.queue.append(char)
while self.queue and s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def firstAppearingOnce(self):
""":rtype: str"""
<|body_0|>
def insert(self, char):
""":type char: str :rtype: void"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not self.queue:
return '#'
else:
return s... | stack_v2_sparse_classes_36k_train_023025 | 777 | no_license | [
{
"docstring": ":rtype: str",
"name": "firstAppearingOnce",
"signature": "def firstAppearingOnce(self)"
},
{
"docstring": ":type char: str :rtype: void",
"name": "insert",
"signature": "def insert(self, char)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstAppearingOnce(self): :rtype: str
- def insert(self, char): :type char: str :rtype: void | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstAppearingOnce(self): :rtype: str
- def insert(self, char): :type char: str :rtype: void
<|skeleton|>
class Solution:
def firstAppearingOnce(self):
""":rtyp... | 967b0fbb40ae491b552bc3365a481e66324cb6f2 | <|skeleton|>
class Solution:
def firstAppearingOnce(self):
""":rtype: str"""
<|body_0|>
def insert(self, char):
""":type char: str :rtype: void"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def firstAppearingOnce(self):
""":rtype: str"""
if not self.queue:
return '#'
else:
return self.queue[0]
def insert(self, char):
""":type char: str :rtype: void"""
if char in self.d.keys():
self.d[char] += 1
els... | the_stack_v2_python_sparse | jianzhi_offer/43_字符流中第一个只出现一次的字符.py | ryanatgz/data_structure_and_algorithm | train | 0 | |
8d8c5828dbf530119b1122589d61d16372848947 | [
"low, high, max_val = (1, len(nums) - 1, len(nums) - 1)\nwhile low < high:\n pivot = low + (high - low) / 2\n small_count, large_count = (0, 0)\n for n in nums:\n if n < pivot:\n small_count += 1\n elif n > pivot:\n large_count += 1\n if small_count > pivot - 1:\n ... | <|body_start_0|>
low, high, max_val = (1, len(nums) - 1, len(nums) - 1)
while low < high:
pivot = low + (high - low) / 2
small_count, large_count = (0, 0)
for n in nums:
if n < pivot:
small_count += 1
elif n > pivot:... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def find_duplicate_bs(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def find_duplicate_bs_nice(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def find_duplicate_two_pointers(self, nums):
""":type nums:... | stack_v2_sparse_classes_36k_train_023026 | 2,372 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "find_duplicate_bs",
"signature": "def find_duplicate_bs(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "find_duplicate_bs_nice",
"signature": "def find_duplicate_bs_nice(self, nums)"
},
{
"d... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def find_duplicate_bs(self, nums): :type nums: List[int] :rtype: int
- def find_duplicate_bs_nice(self, nums): :type nums: List[int] :rtype: int
- def find_duplicate_two_pointers... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def find_duplicate_bs(self, nums): :type nums: List[int] :rtype: int
- def find_duplicate_bs_nice(self, nums): :type nums: List[int] :rtype: int
- def find_duplicate_two_pointers... | e41f4ac9e99b9272ed4718680f4d12fd7443db03 | <|skeleton|>
class Solution:
def find_duplicate_bs(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def find_duplicate_bs_nice(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def find_duplicate_two_pointers(self, nums):
""":type nums:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def find_duplicate_bs(self, nums):
""":type nums: List[int] :rtype: int"""
low, high, max_val = (1, len(nums) - 1, len(nums) - 1)
while low < high:
pivot = low + (high - low) / 2
small_count, large_count = (0, 0)
for n in nums:
... | the_stack_v2_python_sparse | 1-Python/Hard/find_the_duplicate_number.py | jied314/IQs | train | 0 | |
8044af0e2916530e3cb99fb423c77fd0a175a69c | [
"if num == 0:\n return ''\nelif 1 <= num <= 3:\n return lower * num\nelif num == 4:\n return lower + higher\nelif num <= 8:\n return higher + lower * (num - 5)\nelse:\n return lower + upper",
"letters = ['I', 'V', 'X', 'L', 'C', 'D', 'M', '', '']\nindex = 0\nret = ''\nwhile num != 0:\n ret = sel... | <|body_start_0|>
if num == 0:
return ''
elif 1 <= num <= 3:
return lower * num
elif num == 4:
return lower + higher
elif num <= 8:
return higher + lower * (num - 5)
else:
return lower + upper
<|end_body_0|>
<|body_start... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def get_roman_num(self, num, lower, higher, upper):
""":type num: int :type lower: str :type higher: str :type upper: str :rtype: str"""
<|body_0|>
def intToRoman(self, num):
""":type num: int :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_36k_train_023027 | 1,063 | no_license | [
{
"docstring": ":type num: int :type lower: str :type higher: str :type upper: str :rtype: str",
"name": "get_roman_num",
"signature": "def get_roman_num(self, num, lower, higher, upper)"
},
{
"docstring": ":type num: int :rtype: str",
"name": "intToRoman",
"signature": "def intToRoman(s... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_roman_num(self, num, lower, higher, upper): :type num: int :type lower: str :type higher: str :type upper: str :rtype: str
- def intToRoman(self, num): :type num: int :rt... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_roman_num(self, num, lower, higher, upper): :type num: int :type lower: str :type higher: str :type upper: str :rtype: str
- def intToRoman(self, num): :type num: int :rt... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def get_roman_num(self, num, lower, higher, upper):
""":type num: int :type lower: str :type higher: str :type upper: str :rtype: str"""
<|body_0|>
def intToRoman(self, num):
""":type num: int :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def get_roman_num(self, num, lower, higher, upper):
""":type num: int :type lower: str :type higher: str :type upper: str :rtype: str"""
if num == 0:
return ''
elif 1 <= num <= 3:
return lower * num
elif num == 4:
return lower + hig... | the_stack_v2_python_sparse | python/leetcode_bak/12_Integer_to_Roman.py | bobcaoge/my-code | train | 0 | |
6fd1dbbaca8dc84007b0cecde498aff826d53f26 | [
"if torch.cuda.is_available():\n device = torch.device('cuda')\nelse:\n device = torch.device('cpu')\ntor_zero = torch.Tensor([0.0]).to(device).double()\nalpha = ApproxNDCG_OP.DEFAULT_ALPHA\nbatch_pred_diffs = torch.unsqueeze(input, dim=2) - torch.unsqueeze(input, dim=1)\nbatch_hat_pis = tor_get_approximated_... | <|body_start_0|>
if torch.cuda.is_available():
device = torch.device('cuda')
else:
device = torch.device('cpu')
tor_zero = torch.Tensor([0.0]).to(device).double()
alpha = ApproxNDCG_OP.DEFAULT_ALPHA
batch_pred_diffs = torch.unsqueeze(input, dim=2) - torch.... | ApproxNDCG_OP | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApproxNDCG_OP:
def forward(ctx, input, batch_std_labels):
"""In the forward pass we receive a context object and a Tensor containing the input; we must return a Tensor containing the output, and we can use the context object to cache objects for use in the backward pass. Specifically, ct... | stack_v2_sparse_classes_36k_train_023028 | 12,276 | permissive | [
{
"docstring": "In the forward pass we receive a context object and a Tensor containing the input; we must return a Tensor containing the output, and we can use the context object to cache objects for use in the backward pass. Specifically, ctx is a context object that can be used to stash information for backw... | 2 | stack_v2_sparse_classes_30k_test_000399 | Implement the Python class `ApproxNDCG_OP` described below.
Class description:
Implement the ApproxNDCG_OP class.
Method signatures and docstrings:
- def forward(ctx, input, batch_std_labels): In the forward pass we receive a context object and a Tensor containing the input; we must return a Tensor containing the out... | Implement the Python class `ApproxNDCG_OP` described below.
Class description:
Implement the ApproxNDCG_OP class.
Method signatures and docstrings:
- def forward(ctx, input, batch_std_labels): In the forward pass we receive a context object and a Tensor containing the input; we must return a Tensor containing the out... | 4d56d5174c7ce4b15157d112083eb92e57288b04 | <|skeleton|>
class ApproxNDCG_OP:
def forward(ctx, input, batch_std_labels):
"""In the forward pass we receive a context object and a Tensor containing the input; we must return a Tensor containing the output, and we can use the context object to cache objects for use in the backward pass. Specifically, ct... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ApproxNDCG_OP:
def forward(ctx, input, batch_std_labels):
"""In the forward pass we receive a context object and a Tensor containing the input; we must return a Tensor containing the output, and we can use the context object to cache objects for use in the backward pass. Specifically, ctx is a context... | the_stack_v2_python_sparse | MultiDCP/models/loss_utils.py | qiaoliuhub/MultiDCP | train | 3 | |
4e3b87b09c9150017cc587666c85eb2d95700665 | [
"request_command = self.parser_invoker.remote_start_prime_command_bytes(self.sequence_id, self.product_id, 1)\nresponse_command_content = self.connectObj.send_receive_command(request_command)\nreturn response_command_content",
"request_command = self.parser_invoker.remote_start_prime_command_bytes(self.sequence_i... | <|body_start_0|>
request_command = self.parser_invoker.remote_start_prime_command_bytes(self.sequence_id, self.product_id, 1)
response_command_content = self.connectObj.send_receive_command(request_command)
return response_command_content
<|end_body_0|>
<|body_start_1|>
request_command ... | This class is used to define all related methods with priming. | Priming | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Priming:
"""This class is used to define all related methods with priming."""
def start_prime(self):
"""This method is used to start prime. :return: None"""
<|body_0|>
def stop_prime(self):
"""This method is used to stop prime. :return: None"""
<|body_1|>... | stack_v2_sparse_classes_36k_train_023029 | 1,085 | permissive | [
{
"docstring": "This method is used to start prime. :return: None",
"name": "start_prime",
"signature": "def start_prime(self)"
},
{
"docstring": "This method is used to stop prime. :return: None",
"name": "stop_prime",
"signature": "def stop_prime(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010448 | Implement the Python class `Priming` described below.
Class description:
This class is used to define all related methods with priming.
Method signatures and docstrings:
- def start_prime(self): This method is used to start prime. :return: None
- def stop_prime(self): This method is used to stop prime. :return: None | Implement the Python class `Priming` described below.
Class description:
This class is used to define all related methods with priming.
Method signatures and docstrings:
- def start_prime(self): This method is used to start prime. :return: None
- def stop_prime(self): This method is used to stop prime. :return: None
... | c2a4884a36f4c6c6552fa942143ae5d21c120b41 | <|skeleton|>
class Priming:
"""This class is used to define all related methods with priming."""
def start_prime(self):
"""This method is used to start prime. :return: None"""
<|body_0|>
def stop_prime(self):
"""This method is used to stop prime. :return: None"""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Priming:
"""This class is used to define all related methods with priming."""
def start_prime(self):
"""This method is used to start prime. :return: None"""
request_command = self.parser_invoker.remote_start_prime_command_bytes(self.sequence_id, self.product_id, 1)
response_comman... | the_stack_v2_python_sparse | Keywords/DeliveryView/priming.py | cassie01/PumpLibrary | train | 0 |
a330d62002b315707cc0ee83bc38f61aca9c6965 | [
"stack = []\nres = []\nrs = ''\nfor n in range(len(s)):\n if s[n] != ' ':\n stack.append(s[n])\n else:\n while len(stack) > 0:\n res.append(stack.pop())\n res.append(' ')\nwhile len(stack) > 0:\n res.append(stack.pop())\nreturn rs.join(res)",
"s = s.split(' ')\nfor i in ra... | <|body_start_0|>
stack = []
res = []
rs = ''
for n in range(len(s)):
if s[n] != ' ':
stack.append(s[n])
else:
while len(stack) > 0:
res.append(stack.pop())
res.append(' ')
while len(stack)... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseWords(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverseWords2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
stack = []
res = []
rs = ''
for n in range... | stack_v2_sparse_classes_36k_train_023030 | 1,177 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "reverseWords",
"signature": "def reverseWords(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "reverseWords2",
"signature": "def reverseWords2(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008766 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseWords(self, s): :type s: str :rtype: str
- def reverseWords2(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseWords(self, s): :type s: str :rtype: str
- def reverseWords2(self, s): :type s: str :rtype: str
<|skeleton|>
class Solution:
def reverseWords(self, s):
"... | 813235789ce422a3bab198317aafc46fbc61625e | <|skeleton|>
class Solution:
def reverseWords(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverseWords2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseWords(self, s):
""":type s: str :rtype: str"""
stack = []
res = []
rs = ''
for n in range(len(s)):
if s[n] != ' ':
stack.append(s[n])
else:
while len(stack) > 0:
res.append(... | the_stack_v2_python_sparse | 11. STRING MANIP/reverse_words_in_A_string_III/solution.py | kimmyoo/python_leetcode | train | 1 | |
c4c2395337eeade5d6d6fc68bab44338f03dc488 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | ////////////////////////////////////////////////////////////////////////////// ProfileAnalysis service provide entry point for profiling TPU and for serving profiled data to Tensorboard through GRPC ////////////////////////////////////////////////////////////////////////////// | ProfileAnalysisServicer | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileAnalysisServicer:
"""////////////////////////////////////////////////////////////////////////////// ProfileAnalysis service provide entry point for profiling TPU and for serving profiled data to Tensorboard through GRPC //////////////////////////////////////////////////////////////////////... | stack_v2_sparse_classes_36k_train_023031 | 5,789 | permissive | [
{
"docstring": "Starts a profiling session, blocks until it completes. TPUProfileAnalysis service delegate this to TPUProfiler service. Populate the profiled data in repository, then return status to caller.",
"name": "NewSession",
"signature": "def NewSession(self, request, context)"
},
{
"docs... | 3 | stack_v2_sparse_classes_30k_train_017263 | Implement the Python class `ProfileAnalysisServicer` described below.
Class description:
////////////////////////////////////////////////////////////////////////////// ProfileAnalysis service provide entry point for profiling TPU and for serving profiled data to Tensorboard through GRPC ///////////////////////////////... | Implement the Python class `ProfileAnalysisServicer` described below.
Class description:
////////////////////////////////////////////////////////////////////////////// ProfileAnalysis service provide entry point for profiling TPU and for serving profiled data to Tensorboard through GRPC ///////////////////////////////... | a7f3934a67900720af3d3b15389551483bee50b8 | <|skeleton|>
class ProfileAnalysisServicer:
"""////////////////////////////////////////////////////////////////////////////// ProfileAnalysis service provide entry point for profiling TPU and for serving profiled data to Tensorboard through GRPC //////////////////////////////////////////////////////////////////////... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProfileAnalysisServicer:
"""////////////////////////////////////////////////////////////////////////////// ProfileAnalysis service provide entry point for profiling TPU and for serving profiled data to Tensorboard through GRPC //////////////////////////////////////////////////////////////////////////////"""
... | the_stack_v2_python_sparse | tensorflow/python/tpu/profiler/profiler_analysis_pb2_grpc.py | tensorflow/tensorflow | train | 208,740 |
2cb8c3efc4625767b31f0375d8665c388903cd70 | [
"if id == 'current':\n id = request.user.id\nreturn api.keystone.user_get(request, id, admin=False).to_dict()",
"if id == 'current':\n return django.http.HttpResponseNotFound('current')\napi.keystone.user_delete(request, id)",
"keys = tuple(request.DATA)\nuser = api.keystone.user_get(request, id)\nif 'pas... | <|body_start_0|>
if id == 'current':
id = request.user.id
return api.keystone.user_get(request, id, admin=False).to_dict()
<|end_body_0|>
<|body_start_1|>
if id == 'current':
return django.http.HttpResponseNotFound('current')
api.keystone.user_delete(request, id)... | API for a single keystone user. | User | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class User:
"""API for a single keystone user."""
def get(self, request, id):
"""Get a specific user by id. If the id supplied is 'current' then the current logged-in user will be returned, otherwise the user specified by the id."""
<|body_0|>
def delete(self, request, id):
... | stack_v2_sparse_classes_36k_train_023032 | 22,644 | permissive | [
{
"docstring": "Get a specific user by id. If the id supplied is 'current' then the current logged-in user will be returned, otherwise the user specified by the id.",
"name": "get",
"signature": "def get(self, request, id)"
},
{
"docstring": "Delete a single user by id. This method returns HTTP ... | 3 | null | Implement the Python class `User` described below.
Class description:
API for a single keystone user.
Method signatures and docstrings:
- def get(self, request, id): Get a specific user by id. If the id supplied is 'current' then the current logged-in user will be returned, otherwise the user specified by the id.
- d... | Implement the Python class `User` described below.
Class description:
API for a single keystone user.
Method signatures and docstrings:
- def get(self, request, id): Get a specific user by id. If the id supplied is 'current' then the current logged-in user will be returned, otherwise the user specified by the id.
- d... | 7896fd8c77a6766a1156a520946efaf792b76ca5 | <|skeleton|>
class User:
"""API for a single keystone user."""
def get(self, request, id):
"""Get a specific user by id. If the id supplied is 'current' then the current logged-in user will be returned, otherwise the user specified by the id."""
<|body_0|>
def delete(self, request, id):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class User:
"""API for a single keystone user."""
def get(self, request, id):
"""Get a specific user by id. If the id supplied is 'current' then the current logged-in user will be returned, otherwise the user specified by the id."""
if id == 'current':
id = request.user.id
r... | the_stack_v2_python_sparse | openstack_dashboard/api/rest/keystone.py | openstack/horizon | train | 1,060 |
38c102ae9d0072801b1aa3fce012f8b4ce78fad2 | [
"super().__init__(script_file=script_file, work_dir=work_dir, interpreter=interpreter)\nself.nodes = nodes\nself.procs_per_node = procs_per_node\nself.reservation = reservation\nself.launcher = launcher\nself.launcher_args = launcher_args\nself.add_header_line(f'#BSUB -cwd {self.work_dir}')\nself.add_header_line(f'... | <|body_start_0|>
super().__init__(script_file=script_file, work_dir=work_dir, interpreter=interpreter)
self.nodes = nodes
self.procs_per_node = procs_per_node
self.reservation = reservation
self.launcher = launcher
self.launcher_args = launcher_args
self.add_heade... | Utility class to write LSF batch scripts. | LSFBatchScript | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LSFBatchScript:
"""Utility class to write LSF batch scripts."""
def __init__(self, script_file=None, work_dir=os.getcwd(), nodes=1, procs_per_node=1, time_limit=None, job_name=None, partition=None, account=None, reservation=None, launcher='jsrun', launcher_args=[], interpreter='/bin/bash'):
... | stack_v2_sparse_classes_36k_train_023033 | 6,308 | permissive | [
{
"docstring": "Construct LSF batch script manager. Args: script_file (str): Script file. work_dir (str, optional): Working directory (default: current working directory). nodes (int, optional): Number of compute nodes (default: 1). procs_per_node (int, optional): Parallel processes per compute node (default: 1... | 3 | stack_v2_sparse_classes_30k_train_021418 | Implement the Python class `LSFBatchScript` described below.
Class description:
Utility class to write LSF batch scripts.
Method signatures and docstrings:
- def __init__(self, script_file=None, work_dir=os.getcwd(), nodes=1, procs_per_node=1, time_limit=None, job_name=None, partition=None, account=None, reservation=... | Implement the Python class `LSFBatchScript` described below.
Class description:
Utility class to write LSF batch scripts.
Method signatures and docstrings:
- def __init__(self, script_file=None, work_dir=os.getcwd(), nodes=1, procs_per_node=1, time_limit=None, job_name=None, partition=None, account=None, reservation=... | e8cf85eed2acbd3383892bf7cb2d88b44c194f4f | <|skeleton|>
class LSFBatchScript:
"""Utility class to write LSF batch scripts."""
def __init__(self, script_file=None, work_dir=os.getcwd(), nodes=1, procs_per_node=1, time_limit=None, job_name=None, partition=None, account=None, reservation=None, launcher='jsrun', launcher_args=[], interpreter='/bin/bash'):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LSFBatchScript:
"""Utility class to write LSF batch scripts."""
def __init__(self, script_file=None, work_dir=os.getcwd(), nodes=1, procs_per_node=1, time_limit=None, job_name=None, partition=None, account=None, reservation=None, launcher='jsrun', launcher_args=[], interpreter='/bin/bash'):
"""Co... | the_stack_v2_python_sparse | python/lbann/launcher/lsf.py | LLNL/lbann | train | 225 |
a55dc8ef112a7043d5ab3843f618265a4103e14c | [
"super().__init__()\nself.factory = factory\nfor key in initial_keys if initial_keys else []:\n self.__setitem__(key, None)",
"it = super().__getitem__(key)\nif it is None:\n it = self.factory(key)\n self[key] = it\nreturn it"
] | <|body_start_0|>
super().__init__()
self.factory = factory
for key in initial_keys if initial_keys else []:
self.__setitem__(key, None)
<|end_body_0|>
<|body_start_1|>
it = super().__getitem__(key)
if it is None:
it = self.factory(key)
self[ke... | A version of dict where a user-supplied factory method can be used to provide None-marked elements. :note: Why doesn't collections.defaultdict support this... :( | LazyDict | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LazyDict:
"""A version of dict where a user-supplied factory method can be used to provide None-marked elements. :note: Why doesn't collections.defaultdict support this... :("""
def __init__(self, factory, initial_keys=None):
"""Create a new dict and register the element factory in i... | stack_v2_sparse_classes_36k_train_023034 | 1,089 | no_license | [
{
"docstring": "Create a new dict and register the element factory in it. :param initial_keys: (Optional) if a collection, set the given keys in the dict to None.",
"name": "__init__",
"signature": "def __init__(self, factory, initial_keys=None)"
},
{
"docstring": "Returns the element for the gi... | 2 | stack_v2_sparse_classes_30k_train_009590 | Implement the Python class `LazyDict` described below.
Class description:
A version of dict where a user-supplied factory method can be used to provide None-marked elements. :note: Why doesn't collections.defaultdict support this... :(
Method signatures and docstrings:
- def __init__(self, factory, initial_keys=None)... | Implement the Python class `LazyDict` described below.
Class description:
A version of dict where a user-supplied factory method can be used to provide None-marked elements. :note: Why doesn't collections.defaultdict support this... :(
Method signatures and docstrings:
- def __init__(self, factory, initial_keys=None)... | 36d617f5629134ad8cffbf99aca76ea87146a47b | <|skeleton|>
class LazyDict:
"""A version of dict where a user-supplied factory method can be used to provide None-marked elements. :note: Why doesn't collections.defaultdict support this... :("""
def __init__(self, factory, initial_keys=None):
"""Create a new dict and register the element factory in i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LazyDict:
"""A version of dict where a user-supplied factory method can be used to provide None-marked elements. :note: Why doesn't collections.defaultdict support this... :("""
def __init__(self, factory, initial_keys=None):
"""Create a new dict and register the element factory in it. :param ini... | the_stack_v2_python_sparse | dotfiles/lazy_dict.py | whisperity/dotfiles-framework | train | 2 |
037d5658e5e85f09b18e9b0cab84902de5aed6fe | [
"super().__init__()\nself.cache_prior = cache_prior\nself._cache = {}",
"B = log_p_attn.shape[0]\nbb_prior = self._generate_prior(ilens, olens)\nbb_prior = paddle.to_tensor(bb_prior, dtype=log_p_attn.dtype, place=log_p_attn.place)\nlog_p_attn = log_p_attn + bb_prior\nlog_p_attn_pd = F.pad(log_p_attn, (0, 0, 0, 0,... | <|body_start_0|>
super().__init__()
self.cache_prior = cache_prior
self._cache = {}
<|end_body_0|>
<|body_start_1|>
B = log_p_attn.shape[0]
bb_prior = self._generate_prior(ilens, olens)
bb_prior = paddle.to_tensor(bb_prior, dtype=log_p_attn.dtype, place=log_p_attn.place)... | https://openreview.net/forum?id=0NQwnnwAORi | ForwardSumLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ForwardSumLoss:
"""https://openreview.net/forum?id=0NQwnnwAORi"""
def __init__(self, cache_prior: bool=True):
"""Args: cache_prior (bool): Whether to cache beta-binomial prior"""
<|body_0|>
def forward(self, log_p_attn: paddle.Tensor, ilens: paddle.Tensor, olens: paddle.... | stack_v2_sparse_classes_36k_train_023035 | 46,210 | permissive | [
{
"docstring": "Args: cache_prior (bool): Whether to cache beta-binomial prior",
"name": "__init__",
"signature": "def __init__(self, cache_prior: bool=True)"
},
{
"docstring": "Args: log_p_attn (Tensor): Batch of log probability of attention matrix (B, T_feats, T_text). ilens (Tensor): Batch of... | 3 | stack_v2_sparse_classes_30k_train_018068 | Implement the Python class `ForwardSumLoss` described below.
Class description:
https://openreview.net/forum?id=0NQwnnwAORi
Method signatures and docstrings:
- def __init__(self, cache_prior: bool=True): Args: cache_prior (bool): Whether to cache beta-binomial prior
- def forward(self, log_p_attn: paddle.Tensor, ilen... | Implement the Python class `ForwardSumLoss` described below.
Class description:
https://openreview.net/forum?id=0NQwnnwAORi
Method signatures and docstrings:
- def __init__(self, cache_prior: bool=True): Args: cache_prior (bool): Whether to cache beta-binomial prior
- def forward(self, log_p_attn: paddle.Tensor, ilen... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class ForwardSumLoss:
"""https://openreview.net/forum?id=0NQwnnwAORi"""
def __init__(self, cache_prior: bool=True):
"""Args: cache_prior (bool): Whether to cache beta-binomial prior"""
<|body_0|>
def forward(self, log_p_attn: paddle.Tensor, ilens: paddle.Tensor, olens: paddle.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ForwardSumLoss:
"""https://openreview.net/forum?id=0NQwnnwAORi"""
def __init__(self, cache_prior: bool=True):
"""Args: cache_prior (bool): Whether to cache beta-binomial prior"""
super().__init__()
self.cache_prior = cache_prior
self._cache = {}
def forward(self, log_... | the_stack_v2_python_sparse | paddlespeech/t2s/modules/losses.py | anniyanvr/DeepSpeech-1 | train | 0 |
fb6c99e65a41e15630519bfc7f0e9c1177af1eed | [
"super(Decoder, self).__init__()\nself.attention = LuongAttention(rnn_size, attention_func)\nself.rnn_size = rnn_size\nself.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)\nself.lstm = tf.keras.layers.LSTM(rnn_size, return_sequences=True, return_state=True)\nself.wc = tf.keras.layers.Dense(rnn_size... | <|body_start_0|>
super(Decoder, self).__init__()
self.attention = LuongAttention(rnn_size, attention_func)
self.rnn_size = rnn_size
self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)
self.lstm = tf.keras.layers.LSTM(rnn_size, return_sequences=True, return_state... | Decoder of the gru with attention model. | Decoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
"""Decoder of the gru with attention model."""
def __init__(self, vocab_size, embedding_dim, rnn_size, attention_func='dot'):
"""Create the decoder."""
<|body_0|>
def call(self, x, hidden, enc_output, training):
"""Call the foward past. Note that the cal... | stack_v2_sparse_classes_36k_train_023036 | 8,912 | no_license | [
{
"docstring": "Create the decoder.",
"name": "__init__",
"signature": "def __init__(self, vocab_size, embedding_dim, rnn_size, attention_func='dot')"
},
{
"docstring": "Call the foward past. Note that the call must be for one caracter/word at a time.",
"name": "call",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_012023 | Implement the Python class `Decoder` described below.
Class description:
Decoder of the gru with attention model.
Method signatures and docstrings:
- def __init__(self, vocab_size, embedding_dim, rnn_size, attention_func='dot'): Create the decoder.
- def call(self, x, hidden, enc_output, training): Call the foward pa... | Implement the Python class `Decoder` described below.
Class description:
Decoder of the gru with attention model.
Method signatures and docstrings:
- def __init__(self, vocab_size, embedding_dim, rnn_size, attention_func='dot'): Create the decoder.
- def call(self, x, hidden, enc_output, training): Call the foward pa... | 4502d9e7461520664e72165a91bedd8e65464bae | <|skeleton|>
class Decoder:
"""Decoder of the gru with attention model."""
def __init__(self, vocab_size, embedding_dim, rnn_size, attention_func='dot'):
"""Create the decoder."""
<|body_0|>
def call(self, x, hidden, enc_output, training):
"""Call the foward past. Note that the cal... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Decoder:
"""Decoder of the gru with attention model."""
def __init__(self, vocab_size, embedding_dim, rnn_size, attention_func='dot'):
"""Create the decoder."""
super(Decoder, self).__init__()
self.attention = LuongAttention(rnn_size, attention_func)
self.rnn_size = rnn_si... | the_stack_v2_python_sparse | src/model/lstm_luong_attention.py | nathanielsimard/Low-Resource-Machine-Translation | train | 0 |
2eebf45daa150da6cc48ce2970f7cfb4eef29a26 | [
"from collections import deque\nif k == 0:\n return []\nwindow = deque()\nfor i in range(k):\n window.append(nums[i])\nmax_e = max(window)\nres = [max_e]\nfor i in range(k, len(nums)):\n cur = nums[i]\n a = window.popleft()\n window.append(cur)\n if a == max_e and max_e > cur:\n max_e = max... | <|body_start_0|>
from collections import deque
if k == 0:
return []
window = deque()
for i in range(k):
window.append(nums[i])
max_e = max(window)
res = [max_e]
for i in range(k, len(nums)):
cur = nums[i]
a = window.... | Ex239 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ex239:
def maxSlidingWindow(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def maxSlidingWindow0(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_023037 | 3,981 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: List[int]",
"name": "maxSlidingWindow",
"signature": "def maxSlidingWindow(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: List[int]",
"name": "maxSlidingWindow0",
"signature": "def maxSlidingWindow0... | 2 | null | Implement the Python class `Ex239` described below.
Class description:
Implement the Ex239 class.
Method signatures and docstrings:
- def maxSlidingWindow(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- def maxSlidingWindow0(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int] | Implement the Python class `Ex239` described below.
Class description:
Implement the Ex239 class.
Method signatures and docstrings:
- def maxSlidingWindow(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- def maxSlidingWindow0(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
... | 8f9327a1879949f61b462cc6c82e00e7c27b8b07 | <|skeleton|>
class Ex239:
def maxSlidingWindow(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def maxSlidingWindow0(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ex239:
def maxSlidingWindow(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
from collections import deque
if k == 0:
return []
window = deque()
for i in range(k):
window.append(nums[i])
max_e = max(window)
... | the_stack_v2_python_sparse | LeetCode/Ex200/Ex239.py | JasonVann/CrackingCodingInterview | train | 0 | |
873d681a92c9170d036448668ad4c34bf6cc1688 | [
"super(MultiModalDenseNet, self).__init__()\nself.modalities = modalities\nself.device = device\nself.concatenate_out_mod = concatenate_out_mod\nfor mod in self.modalities:\n setattr(self, 'densenet_' + mod, DenseNet(*args, **kwargs))",
"if mod is None:\n out = []\n if self.concatenate_out_mod:\n ... | <|body_start_0|>
super(MultiModalDenseNet, self).__init__()
self.modalities = modalities
self.device = device
self.concatenate_out_mod = concatenate_out_mod
for mod in self.modalities:
setattr(self, 'densenet_' + mod, DenseNet(*args, **kwargs))
<|end_body_0|>
<|body_... | MultiModalDenseNet | [
"LicenseRef-scancode-cecill-b-en"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiModalDenseNet:
def __init__(self, modalities: List[str], *args, device: str='cuda', concatenate_out_mod: bool=False, **kwargs):
""":param modalities: listing all the modality names. It also defines the total # modalities. :param concatenate_out_mod: bool, default False whether we co... | stack_v2_sparse_classes_36k_train_023038 | 7,777 | permissive | [
{
"docstring": ":param modalities: listing all the modality names. It also defines the total # modalities. :param concatenate_out_mod: bool, default False whether we concatenate the ouput or not :param args, kwargs: parameters to give to all DenseNet",
"name": "__init__",
"signature": "def __init__(self... | 2 | null | Implement the Python class `MultiModalDenseNet` described below.
Class description:
Implement the MultiModalDenseNet class.
Method signatures and docstrings:
- def __init__(self, modalities: List[str], *args, device: str='cuda', concatenate_out_mod: bool=False, **kwargs): :param modalities: listing all the modality n... | Implement the Python class `MultiModalDenseNet` described below.
Class description:
Implement the MultiModalDenseNet class.
Method signatures and docstrings:
- def __init__(self, modalities: List[str], *args, device: str='cuda', concatenate_out_mod: bool=False, **kwargs): :param modalities: listing all the modality n... | 7a807ed690929563ce36086eaf0998d0e8856aea | <|skeleton|>
class MultiModalDenseNet:
def __init__(self, modalities: List[str], *args, device: str='cuda', concatenate_out_mod: bool=False, **kwargs):
""":param modalities: listing all the modality names. It also defines the total # modalities. :param concatenate_out_mod: bool, default False whether we co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiModalDenseNet:
def __init__(self, modalities: List[str], *args, device: str='cuda', concatenate_out_mod: bool=False, **kwargs):
""":param modalities: listing all the modality names. It also defines the total # modalities. :param concatenate_out_mod: bool, default False whether we concatenate the ... | the_stack_v2_python_sparse | pynet/models/multimodal_densenet.py | Duplums/pynet | train | 0 | |
f0f300220b2bd977230a1bebc78964fdb4ef6279 | [
"try:\n from rdkit import Chem\n import pubchempy as pcp\nexcept ModuleNotFoundError:\n raise ImportError('This class requires PubChemPy to be installed.')\nself.get_pubchem_compounds = pcp.get_compounds",
"try:\n from rdkit import Chem\n import pubchempy as pcp\nexcept ModuleNotFoundError:\n ra... | <|body_start_0|>
try:
from rdkit import Chem
import pubchempy as pcp
except ModuleNotFoundError:
raise ImportError('This class requires PubChemPy to be installed.')
self.get_pubchem_compounds = pcp.get_compounds
<|end_body_0|>
<|body_start_1|>
try:
... | PubChem Fingerprint. The PubChem fingerprint is a 881 bit structural key, which is used by PubChem for similarity searching. Please confirm the details in [1]_. References ---------- .. [1] ftp://ftp.ncbi.nlm.nih.gov/pubchem/specifications/pubchem_fingerprints.pdf Note ----- This class requires RDKit and PubChemPy to b... | PubChemFingerprint | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PubChemFingerprint:
"""PubChem Fingerprint. The PubChem fingerprint is a 881 bit structural key, which is used by PubChem for similarity searching. Please confirm the details in [1]_. References ---------- .. [1] ftp://ftp.ncbi.nlm.nih.gov/pubchem/specifications/pubchem_fingerprints.pdf Note ----... | stack_v2_sparse_classes_36k_train_023039 | 2,258 | permissive | [
{
"docstring": "Initialize this featurizer.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Calculate PubChem fingerprint. Parameters ---------- datapoint: rdkit.Chem.rdchem.Mol RDKit Mol object Returns ------- np.ndarray 1D array of RDKit descriptors for `mol`. The le... | 2 | stack_v2_sparse_classes_30k_train_007218 | Implement the Python class `PubChemFingerprint` described below.
Class description:
PubChem Fingerprint. The PubChem fingerprint is a 881 bit structural key, which is used by PubChem for similarity searching. Please confirm the details in [1]_. References ---------- .. [1] ftp://ftp.ncbi.nlm.nih.gov/pubchem/specificat... | Implement the Python class `PubChemFingerprint` described below.
Class description:
PubChem Fingerprint. The PubChem fingerprint is a 881 bit structural key, which is used by PubChem for similarity searching. Please confirm the details in [1]_. References ---------- .. [1] ftp://ftp.ncbi.nlm.nih.gov/pubchem/specificat... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class PubChemFingerprint:
"""PubChem Fingerprint. The PubChem fingerprint is a 881 bit structural key, which is used by PubChem for similarity searching. Please confirm the details in [1]_. References ---------- .. [1] ftp://ftp.ncbi.nlm.nih.gov/pubchem/specifications/pubchem_fingerprints.pdf Note ----... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PubChemFingerprint:
"""PubChem Fingerprint. The PubChem fingerprint is a 881 bit structural key, which is used by PubChem for similarity searching. Please confirm the details in [1]_. References ---------- .. [1] ftp://ftp.ncbi.nlm.nih.gov/pubchem/specifications/pubchem_fingerprints.pdf Note ----- This class ... | the_stack_v2_python_sparse | deepchem/feat/molecule_featurizers/pubchem_fingerprint.py | deepchem/deepchem | train | 4,876 |
4f6a2c4b76cb954f623bba3b7b36ccb376e11475 | [
"super(self.__class__, self).__init__()\nself.mgmt_conf_key = 'Controller_management_address'\nself.ctl_type = 'em'",
"super_mtd = super(self.__class__, self)._analysis_shell_info\nresult_info = super_mtd(result_json, get_info_list)\nctl_info = self._analysis_controller_info(result_json, get_info_list)\nif ctl_in... | <|body_start_0|>
super(self.__class__, self).__init__()
self.mgmt_conf_key = 'Controller_management_address'
self.ctl_type = 'em'
<|end_body_0|>
<|body_start_1|>
super_mtd = super(self.__class__, self)._analysis_shell_info
result_info = super_mtd(result_json, get_info_list)
... | Analyze shell script result(ACT). | AnalysisShellResultAct | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnalysisShellResultAct:
"""Analyze shell script result(ACT)."""
def __init__(self):
"""Constructor."""
<|body_0|>
def _analysis_shell_info(self, result_json, get_info_list):
"""Analyze shell script result(core information and OS information). Explanation about pa... | stack_v2_sparse_classes_36k_train_023040 | 24,571 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Analyze shell script result(core information and OS information). Explanation about parameter: result_json:shell script result (json) get_info_list:Acquisition Target List Explanation about re... | 3 | null | Implement the Python class `AnalysisShellResultAct` described below.
Class description:
Analyze shell script result(ACT).
Method signatures and docstrings:
- def __init__(self): Constructor.
- def _analysis_shell_info(self, result_json, get_info_list): Analyze shell script result(core information and OS information).... | Implement the Python class `AnalysisShellResultAct` described below.
Class description:
Analyze shell script result(ACT).
Method signatures and docstrings:
- def __init__(self): Constructor.
- def _analysis_shell_info(self, result_json, get_info_list): Analyze shell script result(core information and OS information).... | e550d1b5ec9419f1fb3eb6e058ce46b57c92ee2f | <|skeleton|>
class AnalysisShellResultAct:
"""Analyze shell script result(ACT)."""
def __init__(self):
"""Constructor."""
<|body_0|>
def _analysis_shell_info(self, result_json, get_info_list):
"""Analyze shell script result(core information and OS information). Explanation about pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnalysisShellResultAct:
"""Analyze shell script result(ACT)."""
def __init__(self):
"""Constructor."""
super(self.__class__, self).__init__()
self.mgmt_conf_key = 'Controller_management_address'
self.ctl_type = 'em'
def _analysis_shell_info(self, result_json, get_info... | the_stack_v2_python_sparse | lib/RestScenario/EmControllerStatusGet.py | lixiaochun/element-manager | train | 0 |
2c86f661dcac18f95b7e9bc91e41e40312b586dc | [
"m = len(grid)\nn = len(grid[0])\ndp = [[0] * n, [0] * n]\ndp[0][0] = grid[0][0]\nfor j in range(1, n):\n dp[0][j] = grid[0][j] + dp[0][j - 1]\nfor i in range(1, m):\n dp[i % 2][0] = grid[i][0] + dp[(i - 1) % 2][0]\n for j in range(1, n):\n dp[i % 2][j] = grid[i][j] + min(dp[(i - 1) % 2][j], dp[i % ... | <|body_start_0|>
m = len(grid)
n = len(grid[0])
dp = [[0] * n, [0] * n]
dp[0][0] = grid[0][0]
for j in range(1, n):
dp[0][j] = grid[0][j] + dp[0][j - 1]
for i in range(1, m):
dp[i % 2][0] = grid[i][0] + dp[(i - 1) % 2][0]
for j in range... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_0|>
def minPathSum2(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m = len(grid)
n = len(grid... | stack_v2_sparse_classes_36k_train_023041 | 1,169 | no_license | [
{
"docstring": ":type grid: List[List[int]] :rtype: int",
"name": "minPathSum",
"signature": "def minPathSum(self, grid)"
},
{
"docstring": ":type grid: List[List[int]] :rtype: int",
"name": "minPathSum2",
"signature": "def minPathSum2(self, grid)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minPathSum(self, grid): :type grid: List[List[int]] :rtype: int
- def minPathSum2(self, grid): :type grid: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minPathSum(self, grid): :type grid: List[List[int]] :rtype: int
- def minPathSum2(self, grid): :type grid: List[List[int]] :rtype: int
<|skeleton|>
class Solution:
def ... | 653d8a5aee803d2b414d0135f791a8f9d83bb272 | <|skeleton|>
class Solution:
def minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_0|>
def minPathSum2(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
m = len(grid)
n = len(grid[0])
dp = [[0] * n, [0] * n]
dp[0][0] = grid[0][0]
for j in range(1, n):
dp[0][j] = grid[0][j] + dp[0][j - 1]
for i in range(1, m):
... | the_stack_v2_python_sparse | 60/64.py | huangyuzhen/let | train | 0 | |
0f3e2ff81835b7f34512b7172f91abf5f547f8df | [
"super(CharDecoder, self).__init__()\nself.target_vocab = target_vocab\nself.charDecoder = nn.LSTM(char_embedding_size, hidden_size)\nself.char_output_projection = nn.Linear(hidden_size, len(self.target_vocab.char2id))\nself.decoderCharEmb = nn.Embedding(len(self.target_vocab.char2id), char_embedding_size, padding_... | <|body_start_0|>
super(CharDecoder, self).__init__()
self.target_vocab = target_vocab
self.charDecoder = nn.LSTM(char_embedding_size, hidden_size)
self.char_output_projection = nn.Linear(hidden_size, len(self.target_vocab.char2id))
self.decoderCharEmb = nn.Embedding(len(self.targ... | CharDecoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CharDecoder:
def __init__(self, hidden_size, char_embedding_size=50, target_vocab=None):
"""Init Character Decoder. @param hidden_size (int): Hidden size of the decoder LSTM @param char_embedding_size (int): dimensionality of character embeddings @param target_vocab (VocabEntry): vocabul... | stack_v2_sparse_classes_36k_train_023042 | 5,695 | no_license | [
{
"docstring": "Init Character Decoder. @param hidden_size (int): Hidden size of the decoder LSTM @param char_embedding_size (int): dimensionality of character embeddings @param target_vocab (VocabEntry): vocabulary for the target language. See vocab.py for documentation.",
"name": "__init__",
"signatur... | 4 | stack_v2_sparse_classes_30k_train_006745 | Implement the Python class `CharDecoder` described below.
Class description:
Implement the CharDecoder class.
Method signatures and docstrings:
- def __init__(self, hidden_size, char_embedding_size=50, target_vocab=None): Init Character Decoder. @param hidden_size (int): Hidden size of the decoder LSTM @param char_em... | Implement the Python class `CharDecoder` described below.
Class description:
Implement the CharDecoder class.
Method signatures and docstrings:
- def __init__(self, hidden_size, char_embedding_size=50, target_vocab=None): Init Character Decoder. @param hidden_size (int): Hidden size of the decoder LSTM @param char_em... | 73efc2abe0b126be53f1e8a366bd7efadaa0267a | <|skeleton|>
class CharDecoder:
def __init__(self, hidden_size, char_embedding_size=50, target_vocab=None):
"""Init Character Decoder. @param hidden_size (int): Hidden size of the decoder LSTM @param char_embedding_size (int): dimensionality of character embeddings @param target_vocab (VocabEntry): vocabul... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CharDecoder:
def __init__(self, hidden_size, char_embedding_size=50, target_vocab=None):
"""Init Character Decoder. @param hidden_size (int): Hidden size of the decoder LSTM @param char_embedding_size (int): dimensionality of character embeddings @param target_vocab (VocabEntry): vocabulary for the ta... | the_stack_v2_python_sparse | CS224N_2020_Winter/a5/char_decoder.py | haroldmei/MLAI | train | 1 | |
fb58a4fe2b2c1de6e4b8d3aaef538228377031a6 | [
"super(OwnedEntityForm, self).__init__(*args, **kwargs)\nif not self.instance.id:\n self.instance.owner = self.user.owner\nself.restrict_fields()\nself.restrict_querysets()\nself.modernize_fields()",
"disallowed_fields = self.user.get_disallowed_fields_for(self.instance)\nif self.is_bound:\n for k in disall... | <|body_start_0|>
super(OwnedEntityForm, self).__init__(*args, **kwargs)
if not self.instance.id:
self.instance.owner = self.user.owner
self.restrict_fields()
self.restrict_querysets()
self.modernize_fields()
<|end_body_0|>
<|body_start_1|>
disallowed_fields =... | Base model form for OwnedEntity subclasses, providing automatic disabled fields based on permissions, filters for choice fields based on user account (owner of instances) and HTML5 widgets. IMPORTANT: Only fields belonging to the model are disabled by default, so any extra fields added to the form MUST BE handled by th... | OwnedEntityForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OwnedEntityForm:
"""Base model form for OwnedEntity subclasses, providing automatic disabled fields based on permissions, filters for choice fields based on user account (owner of instances) and HTML5 widgets. IMPORTANT: Only fields belonging to the model are disabled by default, so any extra fie... | stack_v2_sparse_classes_36k_train_023043 | 2,435 | no_license | [
{
"docstring": "Set owner to new insstance, restrict fields, querysets and modernize fields.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Disable or remove fields for data that the user is not allowed to modify.",
"name": "restrict_fields",
... | 2 | null | Implement the Python class `OwnedEntityForm` described below.
Class description:
Base model form for OwnedEntity subclasses, providing automatic disabled fields based on permissions, filters for choice fields based on user account (owner of instances) and HTML5 widgets. IMPORTANT: Only fields belonging to the model ar... | Implement the Python class `OwnedEntityForm` described below.
Class description:
Base model form for OwnedEntity subclasses, providing automatic disabled fields based on permissions, filters for choice fields based on user account (owner of instances) and HTML5 widgets. IMPORTANT: Only fields belonging to the model ar... | 4dcf0e6a37e8753ae9d69d663c0c280fcca0a26c | <|skeleton|>
class OwnedEntityForm:
"""Base model form for OwnedEntity subclasses, providing automatic disabled fields based on permissions, filters for choice fields based on user account (owner of instances) and HTML5 widgets. IMPORTANT: Only fields belonging to the model are disabled by default, so any extra fie... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OwnedEntityForm:
"""Base model form for OwnedEntity subclasses, providing automatic disabled fields based on permissions, filters for choice fields based on user account (owner of instances) and HTML5 widgets. IMPORTANT: Only fields belonging to the model are disabled by default, so any extra fields added to ... | the_stack_v2_python_sparse | apps/common/forms/base.py | ESCL/pjtracker | train | 1 |
0cb010fec95294db88560c917b9bb2ec7568225b | [
"form.instance.profile = Profile.objects.get(pk=self.kwargs['id'])\nform.instance.type = 'PF'\nreturn super().form_valid(form)",
"context = super().get_context_data(**kwargs)\ncontext['name'] = Profile.objects.get(pk=self.kwargs['id']).name\nreturn context"
] | <|body_start_0|>
form.instance.profile = Profile.objects.get(pk=self.kwargs['id'])
form.instance.type = 'PF'
return super().form_valid(form)
<|end_body_0|>
<|body_start_1|>
context = super().get_context_data(**kwargs)
context['name'] = Profile.objects.get(pk=self.kwargs['id']).n... | Class based view for reporting profile | ProfileReportForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileReportForm:
"""Class based view for reporting profile"""
def form_valid(self, form):
"""Ensures hidden form values are filled"""
<|body_0|>
def get_context_data(self, **kwargs):
"""Passes item name to template"""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_023044 | 10,733 | permissive | [
{
"docstring": "Ensures hidden form values are filled",
"name": "form_valid",
"signature": "def form_valid(self, form)"
},
{
"docstring": "Passes item name to template",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008198 | Implement the Python class `ProfileReportForm` described below.
Class description:
Class based view for reporting profile
Method signatures and docstrings:
- def form_valid(self, form): Ensures hidden form values are filled
- def get_context_data(self, **kwargs): Passes item name to template | Implement the Python class `ProfileReportForm` described below.
Class description:
Class based view for reporting profile
Method signatures and docstrings:
- def form_valid(self, form): Ensures hidden form values are filled
- def get_context_data(self, **kwargs): Passes item name to template
<|skeleton|>
class Profi... | 6bf8e75a1f279ac584daa4ee19927ffccaa67551 | <|skeleton|>
class ProfileReportForm:
"""Class based view for reporting profile"""
def form_valid(self, form):
"""Ensures hidden form values are filled"""
<|body_0|>
def get_context_data(self, **kwargs):
"""Passes item name to template"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProfileReportForm:
"""Class based view for reporting profile"""
def form_valid(self, form):
"""Ensures hidden form values are filled"""
form.instance.profile = Profile.objects.get(pk=self.kwargs['id'])
form.instance.type = 'PF'
return super().form_valid(form)
def get_... | the_stack_v2_python_sparse | rameniaapp/views/report.py | awlane/ramenia | train | 0 |
6b0ff9a4091934d885040c699ff42a0910d7708e | [
"self.ordered_courses = []\nself.couse_table = [[] for _ in range(numCourses)]\nself.course_state = [Solution.UNKNOWN] * numCourses\nfor course1, course2 in prerequisites:\n self.couse_table[course2].append(course1)\nfor course in range(numCourses):\n if self.dfs(course):\n return []\nreturn self.order... | <|body_start_0|>
self.ordered_courses = []
self.couse_table = [[] for _ in range(numCourses)]
self.course_state = [Solution.UNKNOWN] * numCourses
for course1, course2 in prerequisites:
self.couse_table[course2].append(course1)
for course in range(numCourses):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List:
"""DFS解法,是标准和简洁的做法"""
<|body_0|>
def dfs(self, course) -> bool:
"""判断是否有环, 并做拓扑排序"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.ordered_courses = []
... | stack_v2_sparse_classes_36k_train_023045 | 1,468 | no_license | [
{
"docstring": "DFS解法,是标准和简洁的做法",
"name": "findOrder",
"signature": "def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List"
},
{
"docstring": "判断是否有环, 并做拓扑排序",
"name": "dfs",
"signature": "def dfs(self, course) -> bool"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List: DFS解法,是标准和简洁的做法
- def dfs(self, course) -> bool: 判断是否有环, 并做拓扑排序 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List: DFS解法,是标准和简洁的做法
- def dfs(self, course) -> bool: 判断是否有环, 并做拓扑排序
<|skeleton|>
class Solution:
d... | 91ca9cd0df3c88fc7ef3c829dacd4d13f6b71ab1 | <|skeleton|>
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List:
"""DFS解法,是标准和简洁的做法"""
<|body_0|>
def dfs(self, course) -> bool:
"""判断是否有环, 并做拓扑排序"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List:
"""DFS解法,是标准和简洁的做法"""
self.ordered_courses = []
self.couse_table = [[] for _ in range(numCourses)]
self.course_state = [Solution.UNKNOWN] * numCourses
for course1, course2 in prerequ... | the_stack_v2_python_sparse | leetcode_projects/leetcode_210/solution.py | miniyk2012/leetcode | train | 1 | |
f9baafe5a1a83b9e04a5b3b64a78729a345e5ed8 | [
"self.name = name\nself.space = space\nself.input_ = input_\nself.output_ = output_\nself.commands = commands",
"print('-----------------------------------------------------------')\nprint(' Current Command List ')\nprint('------------------------------------------------------... | <|body_start_0|>
self.name = name
self.space = space
self.input_ = input_
self.output_ = output_
self.commands = commands
<|end_body_0|>
<|body_start_1|>
print('-----------------------------------------------------------')
print(' Current Comma... | Class for creating a measurement pattern. This class represents the measurement pattern in the MBQC model. Please refer to [The measurement calculus, arXiv: 0704.1263] for technical details. Attributes: name (str): pattern name space (list): space vertices input_ (list): input vertices output_ (list): output vertices c... | Pattern | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pattern:
"""Class for creating a measurement pattern. This class represents the measurement pattern in the MBQC model. Please refer to [The measurement calculus, arXiv: 0704.1263] for technical details. Attributes: name (str): pattern name space (list): space vertices input_ (list): input vertice... | stack_v2_sparse_classes_36k_train_023046 | 7,995 | permissive | [
{
"docstring": "Constructor for Pattern class. Args: name (str): pattern name space (list): space vertices input_ (list): input vertices output_ (list): output vertices commands (list): command list",
"name": "__init__",
"signature": "def __init__(self, name: str, space: list, input_: list, output_: lis... | 2 | stack_v2_sparse_classes_30k_train_002516 | Implement the Python class `Pattern` described below.
Class description:
Class for creating a measurement pattern. This class represents the measurement pattern in the MBQC model. Please refer to [The measurement calculus, arXiv: 0704.1263] for technical details. Attributes: name (str): pattern name space (list): spac... | Implement the Python class `Pattern` described below.
Class description:
Class for creating a measurement pattern. This class represents the measurement pattern in the MBQC model. Please refer to [The measurement calculus, arXiv: 0704.1263] for technical details. Attributes: name (str): pattern name space (list): spac... | 8bc3c7238b5b6825eb63ded8d65afb08b389941f | <|skeleton|>
class Pattern:
"""Class for creating a measurement pattern. This class represents the measurement pattern in the MBQC model. Please refer to [The measurement calculus, arXiv: 0704.1263] for technical details. Attributes: name (str): pattern name space (list): space vertices input_ (list): input vertice... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pattern:
"""Class for creating a measurement pattern. This class represents the measurement pattern in the MBQC model. Please refer to [The measurement calculus, arXiv: 0704.1263] for technical details. Attributes: name (str): pattern name space (list): space vertices input_ (list): input vertices output_ (li... | the_stack_v2_python_sparse | Extensions/QuantumNetwork/qcompute_qnet/quantum/pattern.py | baidu/QCompute | train | 86 |
461be6a05b2e8ceb3a69aa0b7b5295af2f031de5 | [
"currArgs = [binResObjs, oxyIndices, hyIndices, distFilterIndices, distFilterRanges]\ncurrKwargs = {'nDonorFilterRanges': nDonorFilterRanges, 'nAcceptorFilterRanges': nAcceptorFilterRanges, 'nTotalFilterRanges': nTotalFilterRanges, 'maxOOHBond': maxOOHBond, 'maxAngleHBond': maxAngleHBond, 'checkInputConsistent': ch... | <|body_start_0|>
currArgs = [binResObjs, oxyIndices, hyIndices, distFilterIndices, distFilterRanges]
currKwargs = {'nDonorFilterRanges': nDonorFilterRanges, 'nAcceptorFilterRanges': nAcceptorFilterRanges, 'nTotalFilterRanges': nTotalFilterRanges, 'maxOOHBond': maxOOHBond, 'maxAngleHBond': maxAngleHBond,... | This is an options object specifically for finding certain types of adsorbed water; based on the horizontal distances betwee the atoms which they are adsorbed on. Its actually mostly inherited from WaterCountTypesMinDistAndHBondSimpleOpts though | WaterAdsorbedClassifier_usingMinHozDistsBetweenAdsorptionSitesOptsObj | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WaterAdsorbedClassifier_usingMinHozDistsBetweenAdsorptionSitesOptsObj:
"""This is an options object specifically for finding certain types of adsorbed water; based on the horizontal distances betwee the atoms which they are adsorbed on. Its actually mostly inherited from WaterCountTypesMinDistAnd... | stack_v2_sparse_classes_36k_train_023047 | 28,130 | no_license | [
{
"docstring": "Initializer Args: binResObjs: (iter of BinnedResultsStandard objects) One bin for each type of water you want to count (determined by the \"Ranges\" parameters) oxyIndices: (iter of ints) The oxygen indices for each water molecule hyIndices: (iter of len-2 ints) Same length as oxyIndices, but ea... | 2 | null | Implement the Python class `WaterAdsorbedClassifier_usingMinHozDistsBetweenAdsorptionSitesOptsObj` described below.
Class description:
This is an options object specifically for finding certain types of adsorbed water; based on the horizontal distances betwee the atoms which they are adsorbed on. Its actually mostly i... | Implement the Python class `WaterAdsorbedClassifier_usingMinHozDistsBetweenAdsorptionSitesOptsObj` described below.
Class description:
This is an options object specifically for finding certain types of adsorbed water; based on the horizontal distances betwee the atoms which they are adsorbed on. Its actually mostly i... | 8469a51c1580b923ca35a56811e92c065b424d68 | <|skeleton|>
class WaterAdsorbedClassifier_usingMinHozDistsBetweenAdsorptionSitesOptsObj:
"""This is an options object specifically for finding certain types of adsorbed water; based on the horizontal distances betwee the atoms which they are adsorbed on. Its actually mostly inherited from WaterCountTypesMinDistAnd... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WaterAdsorbedClassifier_usingMinHozDistsBetweenAdsorptionSitesOptsObj:
"""This is an options object specifically for finding certain types of adsorbed water; based on the horizontal distances betwee the atoms which they are adsorbed on. Its actually mostly inherited from WaterCountTypesMinDistAndHBondSimpleOp... | the_stack_v2_python_sparse | gen_basis_helpers/analyse_md/classification_distr_opt_objs.py | RFogarty1/plato_gen_basis_helpers | train | 3 |
4bf7aebc5baaa5224d030607aa79889a5b515035 | [
"directory_path = Path(directory_path)\noutput_path = Path(output_path)\narchive_path = output_path / f'{directory_path.stem}.zip'\nwith zipfile.ZipFile(archive_path, 'w') as zip_file:\n for path in directory_path.rglob('*'):\n zip_file.write(filename=path, arcname=path.relative_to(directory_path))\nretur... | <|body_start_0|>
directory_path = Path(directory_path)
output_path = Path(output_path)
archive_path = output_path / f'{directory_path.stem}.zip'
with zipfile.ZipFile(archive_path, 'w') as zip_file:
for path in directory_path.rglob('*'):
zip_file.write(filename... | A static class for managing zip archives. | _ZipArchiver | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _ZipArchiver:
"""A static class for managing zip archives."""
def create_archive(cls, directory_path: str, output_path: str) -> str:
"""Create an archive of all the contents in the given directory and save it to an archive file named as the directory in the provided output path. :par... | stack_v2_sparse_classes_36k_train_023048 | 7,567 | permissive | [
{
"docstring": "Create an archive of all the contents in the given directory and save it to an archive file named as the directory in the provided output path. :param directory_path: The directory with the files to archive. :param output_path: The output path to store the created archive file. :return: The crea... | 2 | stack_v2_sparse_classes_30k_train_004010 | Implement the Python class `_ZipArchiver` described below.
Class description:
A static class for managing zip archives.
Method signatures and docstrings:
- def create_archive(cls, directory_path: str, output_path: str) -> str: Create an archive of all the contents in the given directory and save it to an archive file... | Implement the Python class `_ZipArchiver` described below.
Class description:
A static class for managing zip archives.
Method signatures and docstrings:
- def create_archive(cls, directory_path: str, output_path: str) -> str: Create an archive of all the contents in the given directory and save it to an archive file... | b5fe0c05ae7f5818a4a5a5a40245c851ff9b2c77 | <|skeleton|>
class _ZipArchiver:
"""A static class for managing zip archives."""
def create_archive(cls, directory_path: str, output_path: str) -> str:
"""Create an archive of all the contents in the given directory and save it to an archive file named as the directory in the provided output path. :par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _ZipArchiver:
"""A static class for managing zip archives."""
def create_archive(cls, directory_path: str, output_path: str) -> str:
"""Create an archive of all the contents in the given directory and save it to an archive file named as the directory in the provided output path. :param directory_... | the_stack_v2_python_sparse | mlrun/package/utils/_archiver.py | mlrun/mlrun | train | 1,093 |
3f3794a85c646ce307fe2df1911e99f937058d35 | [
"n = len(nums)\nmemo = [float('inf')] * n\nmemo[-1] = 0\nfor i in reversed(range(n - 1)):\n max_jump = nums[i]\n if max_jump >= n - 1 - i:\n memo[i] = 1\n else:\n sub_problems = (memo[i + jump] for jump in range(1, max_jump + 1))\n memo[i] = 1 + min(sub_problems, default=float('inf'))\... | <|body_start_0|>
n = len(nums)
memo = [float('inf')] * n
memo[-1] = 0
for i in reversed(range(n - 1)):
max_jump = nums[i]
if max_jump >= n - 1 - i:
memo[i] = 1
else:
sub_problems = (memo[i + jump] for jump in range(1, ma... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def jump_1(self, nums: List[int]) -> int:
"""Solution 1: Simply try every possibility ! You have to memoize the sub-problems for there will be overlaps - Number of sub-problems: O(N) - Complexity of recursion: at the very most O(N) => O(N**2) time complexity and O(N) space comp... | stack_v2_sparse_classes_36k_train_023049 | 3,586 | no_license | [
{
"docstring": "Solution 1: Simply try every possibility ! You have to memoize the sub-problems for there will be overlaps - Number of sub-problems: O(N) - Complexity of recursion: at the very most O(N) => O(N**2) time complexity and O(N) space complexity Timeouts on inputs such as [N, N-1, N-2, ...] and N = 25... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def jump_1(self, nums: List[int]) -> int: Solution 1: Simply try every possibility ! You have to memoize the sub-problems for there will be overlaps - Number of sub-problems: O(N... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def jump_1(self, nums: List[int]) -> int: Solution 1: Simply try every possibility ! You have to memoize the sub-problems for there will be overlaps - Number of sub-problems: O(N... | 3ffcfee5cedf421d5de6d0dec4ba53b0eecbbff8 | <|skeleton|>
class Solution:
def jump_1(self, nums: List[int]) -> int:
"""Solution 1: Simply try every possibility ! You have to memoize the sub-problems for there will be overlaps - Number of sub-problems: O(N) - Complexity of recursion: at the very most O(N) => O(N**2) time complexity and O(N) space comp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def jump_1(self, nums: List[int]) -> int:
"""Solution 1: Simply try every possibility ! You have to memoize the sub-problems for there will be overlaps - Number of sub-problems: O(N) - Complexity of recursion: at the very most O(N) => O(N**2) time complexity and O(N) space complexity Timeout... | the_stack_v2_python_sparse | arrays/JumpGame2_Hard.py | QuentinDuval/PythonExperiments | train | 3 | |
050a876c19ae89300de35f8cc89fdfda8b72d872 | [
"skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge_plugins.craft_plugins.bottom.html', self)\nself.fileNameInput = settings.FileNameInput().getFromFileName(fabmetheus_interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Bottom', self, '')\nself.activateBottom = settings.... | <|body_start_0|>
skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge_plugins.craft_plugins.bottom.html', self)
self.fileNameInput = settings.FileNameInput().getFromFileName(fabmetheus_interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Bottom', self, '')
... | A class to handle the bottom settings. | BottomRepository | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BottomRepository:
"""A class to handle the bottom settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
<|body_0|>
def execute(self):
"""Bottom button has been clicked."""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_023050 | 6,865 | no_license | [
{
"docstring": "Set the default settings, execute title & settings fileName.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Bottom button has been clicked.",
"name": "execute",
"signature": "def execute(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015686 | Implement the Python class `BottomRepository` described below.
Class description:
A class to handle the bottom settings.
Method signatures and docstrings:
- def __init__(self): Set the default settings, execute title & settings fileName.
- def execute(self): Bottom button has been clicked. | Implement the Python class `BottomRepository` described below.
Class description:
A class to handle the bottom settings.
Method signatures and docstrings:
- def __init__(self): Set the default settings, execute title & settings fileName.
- def execute(self): Bottom button has been clicked.
<|skeleton|>
class BottomR... | c1b00a76f1550df2cbb457248205159e51fd4308 | <|skeleton|>
class BottomRepository:
"""A class to handle the bottom settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
<|body_0|>
def execute(self):
"""Bottom button has been clicked."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BottomRepository:
"""A class to handle the bottom settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge_plugins.craft_plugins.bottom.html', self)
self.... | the_stack_v2_python_sparse | skeinforge_application/skeinforge_plugins/craft_plugins/bottom.py | amsler/skeinforge | train | 10 |
0e691ac7febb18c3510ed79ef05ee2592ef4e926 | [
"super(FFN, self).__init__()\nself.w_1 = Conv(num_hidden, num_hidden * 4, kernel_size=1, w_init='relu')\nself.w_2 = Conv(num_hidden * 4, num_hidden, kernel_size=1)\nself.dropout = nn.Dropout(p=0.1)\nself.layer_norm = nn.LayerNorm(num_hidden)",
"x = input_.transpose(1, 2)\nx = self.w_2(t.relu(self.w_1(x)))\nx = x.... | <|body_start_0|>
super(FFN, self).__init__()
self.w_1 = Conv(num_hidden, num_hidden * 4, kernel_size=1, w_init='relu')
self.w_2 = Conv(num_hidden * 4, num_hidden, kernel_size=1)
self.dropout = nn.Dropout(p=0.1)
self.layer_norm = nn.LayerNorm(num_hidden)
<|end_body_0|>
<|body_sta... | Positionwise Feed-Forward Network. | FFN | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FFN:
"""Positionwise Feed-Forward Network."""
def __init__(self, num_hidden):
""":param num_hidden: dimension of hidden."""
<|body_0|>
def forward(self, input_):
"""forward."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(FFN, self).__init... | stack_v2_sparse_classes_36k_train_023051 | 17,934 | permissive | [
{
"docstring": ":param num_hidden: dimension of hidden.",
"name": "__init__",
"signature": "def __init__(self, num_hidden)"
},
{
"docstring": "forward.",
"name": "forward",
"signature": "def forward(self, input_)"
}
] | 2 | null | Implement the Python class `FFN` described below.
Class description:
Positionwise Feed-Forward Network.
Method signatures and docstrings:
- def __init__(self, num_hidden): :param num_hidden: dimension of hidden.
- def forward(self, input_): forward. | Implement the Python class `FFN` described below.
Class description:
Positionwise Feed-Forward Network.
Method signatures and docstrings:
- def __init__(self, num_hidden): :param num_hidden: dimension of hidden.
- def forward(self, input_): forward.
<|skeleton|>
class FFN:
"""Positionwise Feed-Forward Network.""... | 31d50b1ea1dea92f4182c5b2b6fe9fe4c981ae39 | <|skeleton|>
class FFN:
"""Positionwise Feed-Forward Network."""
def __init__(self, num_hidden):
""":param num_hidden: dimension of hidden."""
<|body_0|>
def forward(self, input_):
"""forward."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FFN:
"""Positionwise Feed-Forward Network."""
def __init__(self, num_hidden):
""":param num_hidden: dimension of hidden."""
super(FFN, self).__init__()
self.w_1 = Conv(num_hidden, num_hidden * 4, kernel_size=1, w_init='relu')
self.w_2 = Conv(num_hidden * 4, num_hidden, ker... | the_stack_v2_python_sparse | SVS/model/layers/pretrain_module.py | SJTMusicTeam/SVS_system | train | 85 |
428be28ff53840f2bc709728a82cecb1b6a2fa1d | [
"with torch.no_grad():\n self.range_max = range_max\n log_indices = torch.arange(1.0, range_max + 2.0, 1.0).log_()\n self.dist = (log_indices[1:] - log_indices[:-1]) / log_indices[-1]\n self.log_q = (-(-self.dist.double().log1p_() * 2 * n_sample).expm1_()).log_().float()\nself.n_sample = n_sample",
"n... | <|body_start_0|>
with torch.no_grad():
self.range_max = range_max
log_indices = torch.arange(1.0, range_max + 2.0, 1.0).log_()
self.dist = (log_indices[1:] - log_indices[:-1]) / log_indices[-1]
self.log_q = (-(-self.dist.double().log1p_() * 2 * n_sample).expm1_())... | LogUniformSampler | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"BSD-2-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogUniformSampler:
def __init__(self, range_max, n_sample):
"""Reference : https://github.com/tensorflow/tensorflow/blob/r1.10/tensorflow/python/ops/candidate_sampling_ops.py `P(class) = (log(class + 2) - log(class + 1)) / log(range_max + 1)` expected count can be approximated by 1 - (1 ... | stack_v2_sparse_classes_36k_train_023052 | 7,028 | permissive | [
{
"docstring": "Reference : https://github.com/tensorflow/tensorflow/blob/r1.10/tensorflow/python/ops/candidate_sampling_ops.py `P(class) = (log(class + 2) - log(class + 1)) / log(range_max + 1)` expected count can be approximated by 1 - (1 - p)^n and we use a numerically stable version -expm1(num_tries * log1p... | 2 | null | Implement the Python class `LogUniformSampler` described below.
Class description:
Implement the LogUniformSampler class.
Method signatures and docstrings:
- def __init__(self, range_max, n_sample): Reference : https://github.com/tensorflow/tensorflow/blob/r1.10/tensorflow/python/ops/candidate_sampling_ops.py `P(clas... | Implement the Python class `LogUniformSampler` described below.
Class description:
Implement the LogUniformSampler class.
Method signatures and docstrings:
- def __init__(self, range_max, n_sample): Reference : https://github.com/tensorflow/tensorflow/blob/r1.10/tensorflow/python/ops/candidate_sampling_ops.py `P(clas... | 92acc188d3a0f634de58463b6676e70df83ef808 | <|skeleton|>
class LogUniformSampler:
def __init__(self, range_max, n_sample):
"""Reference : https://github.com/tensorflow/tensorflow/blob/r1.10/tensorflow/python/ops/candidate_sampling_ops.py `P(class) = (log(class + 2) - log(class + 1)) / log(range_max + 1)` expected count can be approximated by 1 - (1 ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogUniformSampler:
def __init__(self, range_max, n_sample):
"""Reference : https://github.com/tensorflow/tensorflow/blob/r1.10/tensorflow/python/ops/candidate_sampling_ops.py `P(class) = (log(class + 2) - log(class + 1)) / log(range_max + 1)` expected count can be approximated by 1 - (1 - p)^n and we ... | the_stack_v2_python_sparse | PyTorch/dev/cv/image_classification/TransformerXL_ID0699_for_PyTorch/pytorch/utils/log_uniform_sampler.py | Ascend/ModelZoo-PyTorch | train | 23 | |
1003b24f302c47e93747ee595008d4e12d354789 | [
"if len(nums) < 2:\n return 0\nmin_v = min(nums)\nmax_v = max(nums)\nbucket_number = len(nums) + 1\nbucket_size = (max_v - min_v) / (bucket_number - 1)\nif bucket_size == 0:\n return 0\nbucket_list = []\nfor i in range(bucket_number):\n bucket_list.append(Bucket(i))\nfor num in nums:\n bucket_list[int((... | <|body_start_0|>
if len(nums) < 2:
return 0
min_v = min(nums)
max_v = max(nums)
bucket_number = len(nums) + 1
bucket_size = (max_v - min_v) / (bucket_number - 1)
if bucket_size == 0:
return 0
bucket_list = []
for i in range(bucket_n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maximumGap(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maximumGap1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(nums) < 2:
return 0
... | stack_v2_sparse_classes_36k_train_023053 | 2,796 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maximumGap",
"signature": "def maximumGap(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maximumGap1",
"signature": "def maximumGap1(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximumGap(self, nums): :type nums: List[int] :rtype: int
- def maximumGap1(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 maximumGap(self, nums): :type nums: List[int] :rtype: int
- def maximumGap1(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def maximumGap(s... | 2c47abbf020f44c97e7e439735e4b0d49f3b843f | <|skeleton|>
class Solution:
def maximumGap(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maximumGap1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maximumGap(self, nums):
""":type nums: List[int] :rtype: int"""
if len(nums) < 2:
return 0
min_v = min(nums)
max_v = max(nums)
bucket_number = len(nums) + 1
bucket_size = (max_v - min_v) / (bucket_number - 1)
if bucket_size == 0... | the_stack_v2_python_sparse | LeetCode/LeetCode164maximum-gap.py | weiguangjiayou/LeetCode | train | 0 | |
e8ffa64829feab3d947afcbd0fffedc3034aefe6 | [
"assert scene in sms_constant.SMS_NOTICE_SCENE_MAP, scene\nif self.filter(scene=scene, instid=instid).exists():\n logger.warning(f'sms_send__msg_remind__exists {scene} {instid}')\n return (False, f'提醒短信已存在: {scene} {instid}')\ntemplate = sms_constant.SMS_NOTICE_SCENE_MAP[scene]\nsign = sms_constant.SMS_SIGN\n... | <|body_start_0|>
assert scene in sms_constant.SMS_NOTICE_SCENE_MAP, scene
if self.filter(scene=scene, instid=instid).exists():
logger.warning(f'sms_send__msg_remind__exists {scene} {instid}')
return (False, f'提醒短信已存在: {scene} {instid}')
template = sms_constant.SMS_NOTICE_... | SmsRecordManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SmsRecordManager:
def sms_send__msg_remind(self, scene, number, params, usrid, touchid, instid):
"""发送 消息短信提醒消息"""
<|body_0|>
def sms_notice_report_receipt(self, dic):
"""通知短信,发送回执MNS订阅"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
assert scene in... | stack_v2_sparse_classes_36k_train_023054 | 6,280 | no_license | [
{
"docstring": "发送 消息短信提醒消息",
"name": "sms_send__msg_remind",
"signature": "def sms_send__msg_remind(self, scene, number, params, usrid, touchid, instid)"
},
{
"docstring": "通知短信,发送回执MNS订阅",
"name": "sms_notice_report_receipt",
"signature": "def sms_notice_report_receipt(self, dic)"
}
... | 2 | null | Implement the Python class `SmsRecordManager` described below.
Class description:
Implement the SmsRecordManager class.
Method signatures and docstrings:
- def sms_send__msg_remind(self, scene, number, params, usrid, touchid, instid): 发送 消息短信提醒消息
- def sms_notice_report_receipt(self, dic): 通知短信,发送回执MNS订阅 | Implement the Python class `SmsRecordManager` described below.
Class description:
Implement the SmsRecordManager class.
Method signatures and docstrings:
- def sms_send__msg_remind(self, scene, number, params, usrid, touchid, instid): 发送 消息短信提醒消息
- def sms_notice_report_receipt(self, dic): 通知短信,发送回执MNS订阅
<|skeleton|... | b7ed6588e13d2916a4162d56509d2794742a1eb1 | <|skeleton|>
class SmsRecordManager:
def sms_send__msg_remind(self, scene, number, params, usrid, touchid, instid):
"""发送 消息短信提醒消息"""
<|body_0|>
def sms_notice_report_receipt(self, dic):
"""通知短信,发送回执MNS订阅"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SmsRecordManager:
def sms_send__msg_remind(self, scene, number, params, usrid, touchid, instid):
"""发送 消息短信提醒消息"""
assert scene in sms_constant.SMS_NOTICE_SCENE_MAP, scene
if self.filter(scene=scene, instid=instid).exists():
logger.warning(f'sms_send__msg_remind__exists {sc... | the_stack_v2_python_sparse | server/applibs/outside/models/ali_dysms.py | fanshuai/kubrick | train | 0 | |
53f36807f85cb5c6de0e623b2795c303145f83d3 | [
"super(InteractionBlock, self).__init__()\nmlp = Sequential(Linear(num_gaussians, num_filters), ShiftedSoftplus(), Linear(num_filters, num_filters))\nself.conv = CFConv(hidden_channels, hidden_channels, num_filters, mlp, cutoff, smooth)\nself.act = ShiftedSoftplus()\nself.lin = Linear(hidden_channels, hidden_channe... | <|body_start_0|>
super(InteractionBlock, self).__init__()
mlp = Sequential(Linear(num_gaussians, num_filters), ShiftedSoftplus(), Linear(num_filters, num_filters))
self.conv = CFConv(hidden_channels, hidden_channels, num_filters, mlp, cutoff, smooth)
self.act = ShiftedSoftplus()
... | Interaction block. | InteractionBlock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InteractionBlock:
"""Interaction block."""
def __init__(self, hidden_channels: int, num_gaussians: int, num_filters: int, cutoff: float, smooth: bool) -> None:
"""Construct an interaction block. Args: hidden_channels: number of hidden channels. num_gaussians: number of gaussians. num... | stack_v2_sparse_classes_36k_train_023055 | 15,380 | permissive | [
{
"docstring": "Construct an interaction block. Args: hidden_channels: number of hidden channels. num_gaussians: number of gaussians. num_filters: number of filters. cutoff: cutoff distance. smooth: whether to use smooth cutoff.",
"name": "__init__",
"signature": "def __init__(self, hidden_channels: int... | 2 | stack_v2_sparse_classes_30k_train_008003 | Implement the Python class `InteractionBlock` described below.
Class description:
Interaction block.
Method signatures and docstrings:
- def __init__(self, hidden_channels: int, num_gaussians: int, num_filters: int, cutoff: float, smooth: bool) -> None: Construct an interaction block. Args: hidden_channels: number of... | Implement the Python class `InteractionBlock` described below.
Class description:
Interaction block.
Method signatures and docstrings:
- def __init__(self, hidden_channels: int, num_gaussians: int, num_filters: int, cutoff: float, smooth: bool) -> None: Construct an interaction block. Args: hidden_channels: number of... | 0b69b7d5b261f2f9af3984793c1295b9b80cd01a | <|skeleton|>
class InteractionBlock:
"""Interaction block."""
def __init__(self, hidden_channels: int, num_gaussians: int, num_filters: int, cutoff: float, smooth: bool) -> None:
"""Construct an interaction block. Args: hidden_channels: number of hidden channels. num_gaussians: number of gaussians. num... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InteractionBlock:
"""Interaction block."""
def __init__(self, hidden_channels: int, num_gaussians: int, num_filters: int, cutoff: float, smooth: bool) -> None:
"""Construct an interaction block. Args: hidden_channels: number of hidden channels. num_gaussians: number of gaussians. num_filters: num... | the_stack_v2_python_sparse | src/gt4sd/algorithms/generation/diffusion/geodiff/model/layers.py | GT4SD/gt4sd-core | train | 239 |
9c260e7b1cd639ea8444901e53e07223c6d685aa | [
"if context is None:\n context = {}\nreturn context.get('type', False)",
"if 'number' not in vals or vals.get('number') == '/':\n seq = self.pool.get('ir.sequence').get(cr, user, 'account.budget.niss')\n vals['number'] = seq and seq or '/'\n if not seq:\n raise osv.except_osv(_('Warning'), _(\"... | <|body_start_0|>
if context is None:
context = {}
return context.get('type', False)
<|end_body_0|>
<|body_start_1|>
if 'number' not in vals or vals.get('number') == '/':
seq = self.pool.get('ir.sequence').get(cr, user, 'account.budget.niss')
vals['number'] = ... | account_budget_niss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class account_budget_niss:
def _get_type(self, cr, uid, context=None):
"""Get type of Budget @return : type or False"""
<|body_0|>
def create(self, cr, user, vals, context=None):
"""Override to add constrain of sequance @param vals: Dictionary of values @return: super of e... | stack_v2_sparse_classes_36k_train_023056 | 4,517 | no_license | [
{
"docstring": "Get type of Budget @return : type or False",
"name": "_get_type",
"signature": "def _get_type(self, cr, uid, context=None)"
},
{
"docstring": "Override to add constrain of sequance @param vals: Dictionary of values @return: super of exchange_order",
"name": "create",
"sig... | 3 | stack_v2_sparse_classes_30k_train_021469 | Implement the Python class `account_budget_niss` described below.
Class description:
Implement the account_budget_niss class.
Method signatures and docstrings:
- def _get_type(self, cr, uid, context=None): Get type of Budget @return : type or False
- def create(self, cr, user, vals, context=None): Override to add con... | Implement the Python class `account_budget_niss` described below.
Class description:
Implement the account_budget_niss class.
Method signatures and docstrings:
- def _get_type(self, cr, uid, context=None): Get type of Budget @return : type or False
- def create(self, cr, user, vals, context=None): Override to add con... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class account_budget_niss:
def _get_type(self, cr, uid, context=None):
"""Get type of Budget @return : type or False"""
<|body_0|>
def create(self, cr, user, vals, context=None):
"""Override to add constrain of sequance @param vals: Dictionary of values @return: super of e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class account_budget_niss:
def _get_type(self, cr, uid, context=None):
"""Get type of Budget @return : type or False"""
if context is None:
context = {}
return context.get('type', False)
def create(self, cr, user, vals, context=None):
"""Override to add constrain of ... | the_stack_v2_python_sparse | v_7/NISS/shamil_v3/account_budget_niss/account_budget_niss.py | musabahmed/baba | train | 0 | |
96ccc203a077db894bd1edbef92c98c78a5494bc | [
"if isinstance(self.conn, BytesIO):\n buff = b''\n have = 0\n while have < size:\n chunk = self.conn.read(size - have)\n have += len(chunk)\n buff += chunk\n return buff\nelse:\n buff = b''\n have = 0\n while have < size:\n chunk = self.conn.recv(size - have)\n ... | <|body_start_0|>
if isinstance(self.conn, BytesIO):
buff = b''
have = 0
while have < size:
chunk = self.conn.read(size - have)
have += len(chunk)
buff += chunk
return buff
else:
buff = b''
... | float divide(1: int num1, 2: int num2=1) | DivideProtocol | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DivideProtocol:
"""float divide(1: int num1, 2: int num2=1)"""
def _read_all(self, size):
"""读取指定长度的字节 :param size: 长度 :return: 读取出的二进制数据"""
<|body_0|>
def args_encode(self, num1, num2=1):
"""对调用参数进行编码 :param num1: int :param num2: int :return: 编码后的二进制数据"""
... | stack_v2_sparse_classes_36k_train_023057 | 9,675 | no_license | [
{
"docstring": "读取指定长度的字节 :param size: 长度 :return: 读取出的二进制数据",
"name": "_read_all",
"signature": "def _read_all(self, size)"
},
{
"docstring": "对调用参数进行编码 :param num1: int :param num2: int :return: 编码后的二进制数据",
"name": "args_encode",
"signature": "def args_encode(self, num1, num2=1)"
},
... | 5 | stack_v2_sparse_classes_30k_train_019739 | Implement the Python class `DivideProtocol` described below.
Class description:
float divide(1: int num1, 2: int num2=1)
Method signatures and docstrings:
- def _read_all(self, size): 读取指定长度的字节 :param size: 长度 :return: 读取出的二进制数据
- def args_encode(self, num1, num2=1): 对调用参数进行编码 :param num1: int :param num2: int :retur... | Implement the Python class `DivideProtocol` described below.
Class description:
float divide(1: int num1, 2: int num2=1)
Method signatures and docstrings:
- def _read_all(self, size): 读取指定长度的字节 :param size: 长度 :return: 读取出的二进制数据
- def args_encode(self, num1, num2=1): 对调用参数进行编码 :param num1: int :param num2: int :retur... | faae36526a4202282d180ebe50031999531374d4 | <|skeleton|>
class DivideProtocol:
"""float divide(1: int num1, 2: int num2=1)"""
def _read_all(self, size):
"""读取指定长度的字节 :param size: 长度 :return: 读取出的二进制数据"""
<|body_0|>
def args_encode(self, num1, num2=1):
"""对调用参数进行编码 :param num1: int :param num2: int :return: 编码后的二进制数据"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DivideProtocol:
"""float divide(1: int num1, 2: int num2=1)"""
def _read_all(self, size):
"""读取指定长度的字节 :param size: 长度 :return: 读取出的二进制数据"""
if isinstance(self.conn, BytesIO):
buff = b''
have = 0
while have < size:
chunk = self.conn.read... | the_stack_v2_python_sparse | RPC/demo005.py | JY-Justin/pydailynotes | train | 0 |
4695784a3f157e9a6d3e17212f1f079d42b282fc | [
"assert isinstance(response, scrapy.http.response.html.HtmlResponse)\nBOARDS = ['Shore Fishing']\nURLS = ['http://www.nesa.co.uk/forums/shore-fishing/']\nPAGES = [501]\nassert len(BOARDS) == len(URLS) == len(PAGES), 'Setup list lengths DO NOT match'\nfor i, root_url in enumerate(URLS):\n curboard = BOARDS[i]\n ... | <|body_start_0|>
assert isinstance(response, scrapy.http.response.html.HtmlResponse)
BOARDS = ['Shore Fishing']
URLS = ['http://www.nesa.co.uk/forums/shore-fishing/']
PAGES = [501]
assert len(BOARDS) == len(URLS) == len(PAGES), 'Setup list lengths DO NOT match'
for i, roo... | scrape reports from angling addicts forum | NESASpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NESASpider:
"""scrape reports from angling addicts forum"""
def parse(self, response):
"""generate links to pages in a board"""
<|body_0|>
def crawl_board_threads(self, response):
"""crawl"""
<|body_1|>
def parse_thread(self, response):
"""op... | stack_v2_sparse_classes_36k_train_023058 | 13,051 | no_license | [
{
"docstring": "generate links to pages in a board",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "crawl",
"name": "crawl_board_threads",
"signature": "def crawl_board_threads(self, response)"
},
{
"docstring": "open a report thread and parse first ... | 3 | null | Implement the Python class `NESASpider` 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
- def crawl_board_threads(self, response): crawl
- def parse_thread(self, response): open a report thr... | Implement the Python class `NESASpider` 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
- def crawl_board_threads(self, response): crawl
- def parse_thread(self, response): open a report thr... | 9123aa6baf538b662143b9098d963d55165e8409 | <|skeleton|>
class NESASpider:
"""scrape reports from angling addicts forum"""
def parse(self, response):
"""generate links to pages in a board"""
<|body_0|>
def crawl_board_threads(self, response):
"""crawl"""
<|body_1|>
def parse_thread(self, response):
"""op... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NESASpider:
"""scrape reports from angling addicts forum"""
def parse(self, response):
"""generate links to pages in a board"""
assert isinstance(response, scrapy.http.response.html.HtmlResponse)
BOARDS = ['Shore Fishing']
URLS = ['http://www.nesa.co.uk/forums/shore-fishin... | the_stack_v2_python_sparse | imgscrape/spiders/nesa.py | gmonkman/python | train | 0 |
ac12766ab40db82d403104e19ffe82c6060f678e | [
"if isinstance(data_particle, DataParticle):\n sample_dict = data_particle.generate_dict()\nelif isinstance(data_particle, basestring):\n sample_dict = json.loads(data_particle)\nelif isinstance(data_particle, dict):\n sample_dict = data_particle\nelse:\n raise IDKException('invalid data particle type: ... | <|body_start_0|>
if isinstance(data_particle, DataParticle):
sample_dict = data_particle.generate_dict()
elif isinstance(data_particle, basestring):
sample_dict = json.loads(data_particle)
elif isinstance(data_particle, dict):
sample_dict = data_particle
... | A class with some methods to test data particles. Intended to be mixed into test classes so that particles can be tested in different areas of the MI code base. | ParticleTestMixin | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParticleTestMixin:
"""A class with some methods to test data particles. Intended to be mixed into test classes so that particles can be tested in different areas of the MI code base."""
def convert_data_particle_to_dict(self, data_particle):
"""Convert a data particle object to a dic... | stack_v2_sparse_classes_36k_train_023059 | 5,556 | permissive | [
{
"docstring": "Convert a data particle object to a dict. This will work for data particles as DataParticle object, dictionaries or a string @param data_particle data particle @return dictionary representation of a data particle",
"name": "convert_data_particle_to_dict",
"signature": "def convert_data_p... | 4 | stack_v2_sparse_classes_30k_train_010293 | Implement the Python class `ParticleTestMixin` described below.
Class description:
A class with some methods to test data particles. Intended to be mixed into test classes so that particles can be tested in different areas of the MI code base.
Method signatures and docstrings:
- def convert_data_particle_to_dict(self... | Implement the Python class `ParticleTestMixin` described below.
Class description:
A class with some methods to test data particles. Intended to be mixed into test classes so that particles can be tested in different areas of the MI code base.
Method signatures and docstrings:
- def convert_data_particle_to_dict(self... | bdbf01f5614e7188ce19596704794466e5683b30 | <|skeleton|>
class ParticleTestMixin:
"""A class with some methods to test data particles. Intended to be mixed into test classes so that particles can be tested in different areas of the MI code base."""
def convert_data_particle_to_dict(self, data_particle):
"""Convert a data particle object to a dic... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParticleTestMixin:
"""A class with some methods to test data particles. Intended to be mixed into test classes so that particles can be tested in different areas of the MI code base."""
def convert_data_particle_to_dict(self, data_particle):
"""Convert a data particle object to a dict. This will ... | the_stack_v2_python_sparse | mi/core/unit_test.py | oceanobservatories/mi-instrument | train | 1 |
b2781102d1c6e741b1c33733f8942a53906d7173 | [
"super(DeepTCRTorch, self).__init__()\nself.use_vdj = params['use_vdj']\nself.use_embedding_matrix = params['use_embedding_matrix']\nself.alpha_encoder = CNNEncoder(seq_model_hyperparams, None, num_seq_labels, use_output_layer=False, use_embedding_matrix=params['use_embedding_matrix'])\nself.beta_encoder = CNNEncod... | <|body_start_0|>
super(DeepTCRTorch, self).__init__()
self.use_vdj = params['use_vdj']
self.use_embedding_matrix = params['use_embedding_matrix']
self.alpha_encoder = CNNEncoder(seq_model_hyperparams, None, num_seq_labels, use_output_layer=False, use_embedding_matrix=params['use_embeddin... | DeepTCRTorch | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeepTCRTorch:
def __init__(self, num_v_alpha, num_j_alpha, num_v_beta, num_d_beta, num_j_beta, num_seq_labels, params, seq_model_hyperparams):
"""If use_embedding_matrix = True, then vdj gets one-hot-encoded and multiplied with embedding matrix The Decoder will then use the transposed em... | stack_v2_sparse_classes_36k_train_023060 | 31,590 | permissive | [
{
"docstring": "If use_embedding_matrix = True, then vdj gets one-hot-encoded and multiplied with embedding matrix The Decoder will then use the transposed embedding matrix to get back the predicted vdj This is the original implementation of DeepTCR",
"name": "__init__",
"signature": "def __init__(self,... | 3 | stack_v2_sparse_classes_30k_train_001432 | Implement the Python class `DeepTCRTorch` described below.
Class description:
Implement the DeepTCRTorch class.
Method signatures and docstrings:
- def __init__(self, num_v_alpha, num_j_alpha, num_v_beta, num_d_beta, num_j_beta, num_seq_labels, params, seq_model_hyperparams): If use_embedding_matrix = True, then vdj ... | Implement the Python class `DeepTCRTorch` described below.
Class description:
Implement the DeepTCRTorch class.
Method signatures and docstrings:
- def __init__(self, num_v_alpha, num_j_alpha, num_v_beta, num_d_beta, num_j_beta, num_seq_labels, params, seq_model_hyperparams): If use_embedding_matrix = True, then vdj ... | dba217393a3a9b1a8700d2927dbac81d360aec4a | <|skeleton|>
class DeepTCRTorch:
def __init__(self, num_v_alpha, num_j_alpha, num_v_beta, num_d_beta, num_j_beta, num_seq_labels, params, seq_model_hyperparams):
"""If use_embedding_matrix = True, then vdj gets one-hot-encoded and multiplied with embedding matrix The Decoder will then use the transposed em... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeepTCRTorch:
def __init__(self, num_v_alpha, num_j_alpha, num_v_beta, num_d_beta, num_j_beta, num_seq_labels, params, seq_model_hyperparams):
"""If use_embedding_matrix = True, then vdj gets one-hot-encoded and multiplied with embedding matrix The Decoder will then use the transposed embedding matrix... | the_stack_v2_python_sparse | tcr_embedding/models/deep_tcr.py | lizwood/mvTCR | train | 0 | |
573f0f6640abeddeb336cbd27c6cc2b30f540d27 | [
"result = dict(vars(config))\nfor arg in self._ignore_config:\n if arg in result:\n del result[arg]\nreturn result",
"for check_arg, check_value in check_config.items():\n if check_arg not in pickled_config:\n return False\n pickled_value = pickled_config[check_arg]\n if isinstance(check... | <|body_start_0|>
result = dict(vars(config))
for arg in self._ignore_config:
if arg in result:
del result[arg]
return result
<|end_body_0|>
<|body_start_1|>
for check_arg, check_value in check_config.items():
if check_arg not in pickled_config:
... | Class for managing collections of results tied to configuration. | MultiPickle | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiPickle:
"""Class for managing collections of results tied to configuration."""
def _get_pickle_config(self, config):
"""Return configuration ready to pickle or compare to pickled. Args: config: See same name argument to `check_for_pickled()` Returns: dict: Dictionary of the conf... | stack_v2_sparse_classes_36k_train_023061 | 8,159 | permissive | [
{
"docstring": "Return configuration ready to pickle or compare to pickled. Args: config: See same name argument to `check_for_pickled()` Returns: dict: Dictionary of the configuration to be pickled or compared to what is pickled.",
"name": "_get_pickle_config",
"signature": "def _get_pickle_config(self... | 6 | stack_v2_sparse_classes_30k_train_009260 | Implement the Python class `MultiPickle` described below.
Class description:
Class for managing collections of results tied to configuration.
Method signatures and docstrings:
- def _get_pickle_config(self, config): Return configuration ready to pickle or compare to pickled. Args: config: See same name argument to `c... | Implement the Python class `MultiPickle` described below.
Class description:
Class for managing collections of results tied to configuration.
Method signatures and docstrings:
- def _get_pickle_config(self, config): Return configuration ready to pickle or compare to pickled. Args: config: See same name argument to `c... | 18f5f35239d3c9ce3ebfd072f5dbc72f5f1532e9 | <|skeleton|>
class MultiPickle:
"""Class for managing collections of results tied to configuration."""
def _get_pickle_config(self, config):
"""Return configuration ready to pickle or compare to pickled. Args: config: See same name argument to `check_for_pickled()` Returns: dict: Dictionary of the conf... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiPickle:
"""Class for managing collections of results tied to configuration."""
def _get_pickle_config(self, config):
"""Return configuration ready to pickle or compare to pickled. Args: config: See same name argument to `check_for_pickled()` Returns: dict: Dictionary of the configuration to ... | the_stack_v2_python_sparse | multi_pickle.py | kpenev/general_purpose_python_modules | train | 0 |
2061194404c40d47ff3ad902b784e6df77e60d7f | [
"if not root:\n return 'x'\nreturn ','.join([str(root.val), self.serialize(root.left), self.serialize(root.right)])",
"self.data = input_data\nif self.data[0] == 'x':\n return None\nnode = TreeNode(self.data[:self.data.find(',')], None, None)\nnode.left = self.deserialize(self.data[self.data.find(',') + 1:]... | <|body_start_0|>
if not root:
return 'x'
return ','.join([str(root.val), self.serialize(root.left), self.serialize(root.right)])
<|end_body_0|>
<|body_start_1|>
self.data = input_data
if self.data[0] == 'x':
return None
node = TreeNode(self.data[:self.dat... | 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, input_data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_023062 | 4,141 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, input_data): Decodes your encoded data to tree. :type data: str :... | 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, input_data): Decodes your encoded data to tree. :type data: str :... | c875ff69ed2b5dfaa5b2d7f37354456542f1ceea | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, input_data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return 'x'
return ','.join([str(root.val), self.serialize(root.left), self.serialize(root.right)])
def deserialize(self, input_data):
"""Dec... | the_stack_v2_python_sparse | DailyChallenge/LC_297.py | linxixu-1/Leetcode | train | 0 | |
6c9ebf1040fd6dc5d277ff49afaba6c080d7106a | [
"expressed_article = self.get_article(slug)\nresponse, status_ = dislikeReaction.mofidy_reaction(expressed_article, request.user, self.reaction, 'article')\nreturn Response(response, status=status_)",
"try:\n article = Article.objects.get(slug=art)\nexcept Exception as ex:\n print(ex)\n raise exceptions.... | <|body_start_0|>
expressed_article = self.get_article(slug)
response, status_ = dislikeReaction.mofidy_reaction(expressed_article, request.user, self.reaction, 'article')
return Response(response, status=status_)
<|end_body_0|>
<|body_start_1|>
try:
article = Article.objects... | Allows user to post reactions to an article | UserReactionView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserReactionView:
"""Allows user to post reactions to an article"""
def post(self, request, slug):
"""Posts a like or dislike to an article from an autheticated user."""
<|body_0|>
def get_article(self, art):
"""Fetches and returns an article instance given its s... | stack_v2_sparse_classes_36k_train_023063 | 2,525 | permissive | [
{
"docstring": "Posts a like or dislike to an article from an autheticated user.",
"name": "post",
"signature": "def post(self, request, slug)"
},
{
"docstring": "Fetches and returns an article instance given its slug field",
"name": "get_article",
"signature": "def get_article(self, art... | 2 | stack_v2_sparse_classes_30k_train_014370 | Implement the Python class `UserReactionView` described below.
Class description:
Allows user to post reactions to an article
Method signatures and docstrings:
- def post(self, request, slug): Posts a like or dislike to an article from an autheticated user.
- def get_article(self, art): Fetches and returns an article... | Implement the Python class `UserReactionView` described below.
Class description:
Allows user to post reactions to an article
Method signatures and docstrings:
- def post(self, request, slug): Posts a like or dislike to an article from an autheticated user.
- def get_article(self, art): Fetches and returns an article... | b80ad485339dbb02b74d9b2093543bf8173d51de | <|skeleton|>
class UserReactionView:
"""Allows user to post reactions to an article"""
def post(self, request, slug):
"""Posts a like or dislike to an article from an autheticated user."""
<|body_0|>
def get_article(self, art):
"""Fetches and returns an article instance given its s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserReactionView:
"""Allows user to post reactions to an article"""
def post(self, request, slug):
"""Posts a like or dislike to an article from an autheticated user."""
expressed_article = self.get_article(slug)
response, status_ = dislikeReaction.mofidy_reaction(expressed_articl... | the_stack_v2_python_sparse | authors/apps/reactions/views.py | deferral/ah-django | train | 1 |
bac4db69a0f7a82e0e142a7c49319c49344a5886 | [
"me = request.me\ndata = {'title': request.data.get('title') or '', 'content': request.data.get('content') or '', 'thumbnail': request.data.get('thumbnail') or None, 'is_draft': request.data.get('is_draft') or None}\nif 'labels' not in request.data:\n return self.error(errorcode.MSG_INVALID_DATA, errorcode.INVAL... | <|body_start_0|>
me = request.me
data = {'title': request.data.get('title') or '', 'content': request.data.get('content') or '', 'thumbnail': request.data.get('thumbnail') or None, 'is_draft': request.data.get('is_draft') or None}
if 'labels' not in request.data:
return self.error(er... | ArticleView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArticleView:
def post(self, request):
"""写文章,可以是草稿"""
<|body_0|>
def get(self, request):
"""查看一批文章,可分页"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
me = request.me
data = {'title': request.data.get('title') or '', 'content': request.data.... | stack_v2_sparse_classes_36k_train_023064 | 8,733 | no_license | [
{
"docstring": "写文章,可以是草稿",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "查看一批文章,可分页",
"name": "get",
"signature": "def get(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004152 | Implement the Python class `ArticleView` described below.
Class description:
Implement the ArticleView class.
Method signatures and docstrings:
- def post(self, request): 写文章,可以是草稿
- def get(self, request): 查看一批文章,可分页 | Implement the Python class `ArticleView` described below.
Class description:
Implement the ArticleView class.
Method signatures and docstrings:
- def post(self, request): 写文章,可以是草稿
- def get(self, request): 查看一批文章,可分页
<|skeleton|>
class ArticleView:
def post(self, request):
"""写文章,可以是草稿"""
<|bod... | 6a68fb207f43e5ed65299cc08535b35d5e934ead | <|skeleton|>
class ArticleView:
def post(self, request):
"""写文章,可以是草稿"""
<|body_0|>
def get(self, request):
"""查看一批文章,可分页"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArticleView:
def post(self, request):
"""写文章,可以是草稿"""
me = request.me
data = {'title': request.data.get('title') or '', 'content': request.data.get('content') or '', 'thumbnail': request.data.get('thumbnail') or None, 'is_draft': request.data.get('is_draft') or None}
if 'labels... | the_stack_v2_python_sparse | apps/articles_v2/views.py | Slowhalfframe/fanyijiang-API | train | 0 | |
3129433c1ee56338d3e7aecd45e77590651e34b2 | [
"m, n = (len(nums1), len(nums2))\nif m == 0:\n if n & 1 == 0:\n return (nums2[n // 2] + nums2[n // 2 - 1]) / 2\n return nums2[n // 2]\nif n == 0:\n if m & 1 == 0:\n return (nums1[m // 2] + nums1[m // 2 - 1]) / 2\n return nums1[m // 2]\ntotal = m + n\nif total & 1 == 1:\n return self.fin... | <|body_start_0|>
m, n = (len(nums1), len(nums2))
if m == 0:
if n & 1 == 0:
return (nums2[n // 2] + nums2[n // 2 - 1]) / 2
return nums2[n // 2]
if n == 0:
if m & 1 == 0:
return (nums1[m // 2] + nums1[m // 2 - 1]) / 2
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
"""两个有序数组求中位数,问题一般化为,求两个有序数组的第k个数,当k = (m+n)/2时为原问题的解。 怎么求第k个数?分别求出第一个和第二个数组的第 k / 2个数 a 和 b,然后比较 a 和 b,当a < b , 说明第 k 个数位于 a数组的第 k / 2个数后半段,或者b数组的 第 k / 2 个数前半段,问题规模缩小了一半, 然后递归处理就行。 时间复杂度是 O(log(m+n... | stack_v2_sparse_classes_36k_train_023065 | 3,908 | no_license | [
{
"docstring": "两个有序数组求中位数,问题一般化为,求两个有序数组的第k个数,当k = (m+n)/2时为原问题的解。 怎么求第k个数?分别求出第一个和第二个数组的第 k / 2个数 a 和 b,然后比较 a 和 b,当a < b , 说明第 k 个数位于 a数组的第 k / 2个数后半段,或者b数组的 第 k / 2 个数前半段,问题规模缩小了一半, 然后递归处理就行。 时间复杂度是 O(log(m+n)) :param nums1: :param nums2: :return:",
"name": "findMedianSortedArrays",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_test_000268 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: 两个有序数组求中位数,问题一般化为,求两个有序数组的第k个数,当k = (m+n)/2时为原问题的解。 怎么求第k个数?分别求出第一个和第二个数组的第 k / 2个数 a 和 b,然后比较 a 和 ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: 两个有序数组求中位数,问题一般化为,求两个有序数组的第k个数,当k = (m+n)/2时为原问题的解。 怎么求第k个数?分别求出第一个和第二个数组的第 k / 2个数 a 和 b,然后比较 a 和 ... | 971cc2f674d53cf33a621a3a608f32a53603438a | <|skeleton|>
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
"""两个有序数组求中位数,问题一般化为,求两个有序数组的第k个数,当k = (m+n)/2时为原问题的解。 怎么求第k个数?分别求出第一个和第二个数组的第 k / 2个数 a 和 b,然后比较 a 和 b,当a < b , 说明第 k 个数位于 a数组的第 k / 2个数后半段,或者b数组的 第 k / 2 个数前半段,问题规模缩小了一半, 然后递归处理就行。 时间复杂度是 O(log(m+n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
"""两个有序数组求中位数,问题一般化为,求两个有序数组的第k个数,当k = (m+n)/2时为原问题的解。 怎么求第k个数?分别求出第一个和第二个数组的第 k / 2个数 a 和 b,然后比较 a 和 b,当a < b , 说明第 k 个数位于 a数组的第 k / 2个数后半段,或者b数组的 第 k / 2 个数前半段,问题规模缩小了一半, 然后递归处理就行。 时间复杂度是 O(log(m+n)) :param nums... | the_stack_v2_python_sparse | LeetCode/困难/4寻找两个有序数组的中位数.py | xiyangxitian1/learn_days | train | 0 | |
93353e6ef5ef35255e4db3df24b7ce401b5b8e4b | [
"for profile in orm.Profile.objects.filter(school_staff=True).filter(code__isnull=True).select_related('user'):\n profile.code = generate_code(profile.user.username)\n profile.save()",
"for profile in orm.Profile.objects.filter(school_staff=True).filter(code__isnull=False):\n profile.code = None\n pro... | <|body_start_0|>
for profile in orm.Profile.objects.filter(school_staff=True).filter(code__isnull=True).select_related('user'):
profile.code = generate_code(profile.user.username)
profile.save()
<|end_body_0|>
<|body_start_1|>
for profile in orm.Profile.objects.filter(school_sta... | Migration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Write your forwards methods here."""
<|body_0|>
def backwards(self, orm):
"""Write your backwards methods here."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for profile in orm.Profile.objects.filter(school_s... | stack_v2_sparse_classes_36k_train_023066 | 5,844 | no_license | [
{
"docstring": "Write your forwards methods here.",
"name": "forwards",
"signature": "def forwards(self, orm)"
},
{
"docstring": "Write your backwards methods here.",
"name": "backwards",
"signature": "def backwards(self, orm)"
}
] | 2 | null | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Write your forwards methods here.
- def backwards(self, orm): Write your backwards methods here. | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Write your forwards methods here.
- def backwards(self, orm): Write your backwards methods here.
<|skeleton|>
class Migration:
def forwards(self,... | ffa893d47aa8065c0f5809fe765fcde5772e31f6 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Write your forwards methods here."""
<|body_0|>
def backwards(self, orm):
"""Write your backwards methods here."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Migration:
def forwards(self, orm):
"""Write your forwards methods here."""
for profile in orm.Profile.objects.filter(school_staff=True).filter(code__isnull=True).select_related('user'):
profile.code = generate_code(profile.user.username)
profile.save()
def backwar... | the_stack_v2_python_sparse | portfoliyo/model/users/migrations/0007_populate_codes.py | denis-sukhoverkhov/portfoliyo | train | 0 | |
2061bf770860ab3b5849c1af36f665bfa1ef600c | [
"super().__init__()\nif mu < 0.0:\n raise ValueError('mu should be no less than 0.0')\nself.mu = mu",
"prox_loss: torch.Tensor = 0.0\nfor param, ref in zip(input.named_parameters(), target.named_parameters()):\n prox_loss += self.mu / 2 * torch.sum((param[1] - ref[1]) ** 2)\nreturn prox_loss"
] | <|body_start_0|>
super().__init__()
if mu < 0.0:
raise ValueError('mu should be no less than 0.0')
self.mu = mu
<|end_body_0|>
<|body_start_1|>
prox_loss: torch.Tensor = 0.0
for param, ref in zip(input.named_parameters(), target.named_parameters()):
prox_... | PTFedProxLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PTFedProxLoss:
def __init__(self, mu: float=0.01) -> None:
"""Compute FedProx loss: a loss penalizing the deviation from global model. Args: mu: weighting parameter"""
<|body_0|>
def forward(self, input, target) -> torch.Tensor:
"""Forward pass in training. Args: inp... | stack_v2_sparse_classes_36k_train_023067 | 1,634 | permissive | [
{
"docstring": "Compute FedProx loss: a loss penalizing the deviation from global model. Args: mu: weighting parameter",
"name": "__init__",
"signature": "def __init__(self, mu: float=0.01) -> None"
},
{
"docstring": "Forward pass in training. Args: input (nn.Module): the local pytorch model tar... | 2 | null | Implement the Python class `PTFedProxLoss` described below.
Class description:
Implement the PTFedProxLoss class.
Method signatures and docstrings:
- def __init__(self, mu: float=0.01) -> None: Compute FedProx loss: a loss penalizing the deviation from global model. Args: mu: weighting parameter
- def forward(self, i... | Implement the Python class `PTFedProxLoss` described below.
Class description:
Implement the PTFedProxLoss class.
Method signatures and docstrings:
- def __init__(self, mu: float=0.01) -> None: Compute FedProx loss: a loss penalizing the deviation from global model. Args: mu: weighting parameter
- def forward(self, i... | 1433290c203bd23f34c29e11795ce592bc067888 | <|skeleton|>
class PTFedProxLoss:
def __init__(self, mu: float=0.01) -> None:
"""Compute FedProx loss: a loss penalizing the deviation from global model. Args: mu: weighting parameter"""
<|body_0|>
def forward(self, input, target) -> torch.Tensor:
"""Forward pass in training. Args: inp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PTFedProxLoss:
def __init__(self, mu: float=0.01) -> None:
"""Compute FedProx loss: a loss penalizing the deviation from global model. Args: mu: weighting parameter"""
super().__init__()
if mu < 0.0:
raise ValueError('mu should be no less than 0.0')
self.mu = mu
... | the_stack_v2_python_sparse | nvflare/app_opt/pt/fedproxloss.py | NVIDIA/NVFlare | train | 442 | |
183370fde921c6500c31865d9ff4823138b107f8 | [
"args = dict(is_add=True, is_src_dst=True, vni=int(vni), deid=LispEid.create_eid(deid, deid_prefix if not is_mac else None), seid=LispEid.create_eid(seid, seid_prefix if not is_mac else None), rloc_num=1, rlocs=LispRemoteLocator.create_rloc(rloc))\ncmd = u'lisp_add_del_remote_mapping'\nerr_msg = f\"Failed to add re... | <|body_start_0|>
args = dict(is_add=True, is_src_dst=True, vni=int(vni), deid=LispEid.create_eid(deid, deid_prefix if not is_mac else None), seid=LispEid.create_eid(seid, seid_prefix if not is_mac else None), rloc_num=1, rlocs=LispRemoteLocator.create_rloc(rloc))
cmd = u'lisp_add_del_remote_mapping'
... | Class for lisp remote mapping API. | LispRemoteMapping | [
"GPL-1.0-or-later",
"CC-BY-4.0",
"Apache-2.0",
"LicenseRef-scancode-dco-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LispRemoteMapping:
"""Class for lisp remote mapping API."""
def vpp_add_lisp_remote_mapping(node, vni, deid, deid_prefix, seid, seid_prefix, rloc, is_mac=False):
"""Add lisp remote mapping on the VPP node in topology. :param node: VPP node. :param vni: Vni. :param deid: Destination e... | stack_v2_sparse_classes_36k_train_023068 | 14,690 | permissive | [
{
"docstring": "Add lisp remote mapping on the VPP node in topology. :param node: VPP node. :param vni: Vni. :param deid: Destination eid address. :param deid_prefix: Destination eid address prefix_len. :param seid: Source eid address. :param seid_prefix: Source eid address prefix_len. :param rloc: Receiver loc... | 2 | stack_v2_sparse_classes_30k_train_008189 | Implement the Python class `LispRemoteMapping` described below.
Class description:
Class for lisp remote mapping API.
Method signatures and docstrings:
- def vpp_add_lisp_remote_mapping(node, vni, deid, deid_prefix, seid, seid_prefix, rloc, is_mac=False): Add lisp remote mapping on the VPP node in topology. :param no... | Implement the Python class `LispRemoteMapping` described below.
Class description:
Class for lisp remote mapping API.
Method signatures and docstrings:
- def vpp_add_lisp_remote_mapping(node, vni, deid, deid_prefix, seid, seid_prefix, rloc, is_mac=False): Add lisp remote mapping on the VPP node in topology. :param no... | 947057d7310cd1602119258c6b82fbb25fe1b79d | <|skeleton|>
class LispRemoteMapping:
"""Class for lisp remote mapping API."""
def vpp_add_lisp_remote_mapping(node, vni, deid, deid_prefix, seid, seid_prefix, rloc, is_mac=False):
"""Add lisp remote mapping on the VPP node in topology. :param node: VPP node. :param vni: Vni. :param deid: Destination e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LispRemoteMapping:
"""Class for lisp remote mapping API."""
def vpp_add_lisp_remote_mapping(node, vni, deid, deid_prefix, seid, seid_prefix, rloc, is_mac=False):
"""Add lisp remote mapping on the VPP node in topology. :param node: VPP node. :param vni: Vni. :param deid: Destination eid address. :... | the_stack_v2_python_sparse | resources/libraries/python/LispSetup.py | FDio/csit | train | 28 |
dcb11edc9e03f13fda81fe94797d01a9ee70926c | [
"if name in ['comb', 'sync', 'specials', 'submodules', 'clock_domains']:\n if not isinstance(value, _ModuleProxy):\n raise AttributeError('Attempted to assign special Module property - use += instead')\nelif isinstance(value, Module) and (name, value) not in m._submodules and (not isinstance(value, _CSRBa... | <|body_start_0|>
if name in ['comb', 'sync', 'specials', 'submodules', 'clock_domains']:
if not isinstance(value, _ModuleProxy):
raise AttributeError('Attempted to assign special Module property - use += instead')
elif isinstance(value, Module) and (name, value) not in m._sub... | LiteXModule is an enhancement of the Migen Module, offering additional features and simplifications for users to handle submodules, specials, and clock domains. It is integrated with AutoCSR and AutoDoc for CSR and documentation automation, respectively. | LiteXModule | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LiteXModule:
"""LiteXModule is an enhancement of the Migen Module, offering additional features and simplifications for users to handle submodules, specials, and clock domains. It is integrated with AutoCSR and AutoDoc for CSR and documentation automation, respectively."""
def __setattr__(m,... | stack_v2_sparse_classes_36k_train_023069 | 3,991 | permissive | [
{
"docstring": "Overrides the default behavior of attribute assignment in Python. This method simplifies the process of adding submodules, specials, and clock domains in LiteX compared to Migen.",
"name": "__setattr__",
"signature": "def __setattr__(m, name, value)"
},
{
"docstring": "Overrides ... | 4 | stack_v2_sparse_classes_30k_train_000488 | Implement the Python class `LiteXModule` described below.
Class description:
LiteXModule is an enhancement of the Migen Module, offering additional features and simplifications for users to handle submodules, specials, and clock domains. It is integrated with AutoCSR and AutoDoc for CSR and documentation automation, r... | Implement the Python class `LiteXModule` described below.
Class description:
LiteXModule is an enhancement of the Migen Module, offering additional features and simplifications for users to handle submodules, specials, and clock domains. It is integrated with AutoCSR and AutoDoc for CSR and documentation automation, r... | 405296b7fd99764af21fffd94afa5075c22affa8 | <|skeleton|>
class LiteXModule:
"""LiteXModule is an enhancement of the Migen Module, offering additional features and simplifications for users to handle submodules, specials, and clock domains. It is integrated with AutoCSR and AutoDoc for CSR and documentation automation, respectively."""
def __setattr__(m,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LiteXModule:
"""LiteXModule is an enhancement of the Migen Module, offering additional features and simplifications for users to handle submodules, specials, and clock domains. It is integrated with AutoCSR and AutoDoc for CSR and documentation automation, respectively."""
def __setattr__(m, name, value)... | the_stack_v2_python_sparse | litex/gen/fhdl/module.py | enjoy-digital/litex | train | 2,351 |
b56369e7730a5e7f222cbc1d845e8315d37a07e1 | [
"if not nums:\n return None\nlen_nums = len(nums)\nif len_nums == 1:\n return nums[0]\nresult = nums[0]\naccum = 0\nfor num in nums:\n if accum < 0:\n accum = num\n else:\n accum += num\n if accum > result:\n result = accum\nreturn result",
"len_nums = len(nums)\nresult = nums[... | <|body_start_0|>
if not nums:
return None
len_nums = len(nums)
if len_nums == 1:
return nums[0]
result = nums[0]
accum = 0
for num in nums:
if accum < 0:
accum = num
else:
accum += num
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maxSubArray_DP(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return None
... | stack_v2_sparse_classes_36k_train_023070 | 1,186 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maxSubArray",
"signature": "def maxSubArray(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maxSubArray_DP",
"signature": "def maxSubArray_DP(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray(self, nums): :type nums: List[int] :rtype: int
- def maxSubArray_DP(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 maxSubArray(self, nums): :type nums: List[int] :rtype: int
- def maxSubArray_DP(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxSubAr... | dbdb227e12f329e4ca064b338f1fbdca42f3a848 | <|skeleton|>
class Solution:
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maxSubArray_DP(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
if not nums:
return None
len_nums = len(nums)
if len_nums == 1:
return nums[0]
result = nums[0]
accum = 0
for num in nums:
if accum < 0:
... | the_stack_v2_python_sparse | LC53.py | Qiao-Liang/LeetCode | train | 0 | |
91097cf3aa24574bcd34b139a7db3ca7b8861025 | [
"super().__init__(coordinator, thermostat, unique_id=f'{thermostat.thermostat_id}_{sensor_call}')\nself._call = sensor_call\nself._modifier = modifier\nself._attr_device_class = sensor_class\nself._attr_native_unit_of_measurement = sensor_unit\nself._attr_state_class = state_class\nif translation_key is not None:\n... | <|body_start_0|>
super().__init__(coordinator, thermostat, unique_id=f'{thermostat.thermostat_id}_{sensor_call}')
self._call = sensor_call
self._modifier = modifier
self._attr_device_class = sensor_class
self._attr_native_unit_of_measurement = sensor_unit
self._attr_state... | Provides Nexia thermostat sensor support. | NexiaThermostatSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NexiaThermostatSensor:
"""Provides Nexia thermostat sensor support."""
def __init__(self, coordinator, thermostat, sensor_call, translation_key, sensor_class, sensor_unit, state_class, modifier=None):
"""Initialize the sensor."""
<|body_0|>
def native_value(self):
... | stack_v2_sparse_classes_36k_train_023071 | 7,364 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, coordinator, thermostat, sensor_call, translation_key, sensor_class, sensor_unit, state_class, modifier=None)"
},
{
"docstring": "Return the state of the sensor.",
"name": "native_value",
"signa... | 2 | null | Implement the Python class `NexiaThermostatSensor` described below.
Class description:
Provides Nexia thermostat sensor support.
Method signatures and docstrings:
- def __init__(self, coordinator, thermostat, sensor_call, translation_key, sensor_class, sensor_unit, state_class, modifier=None): Initialize the sensor.
... | Implement the Python class `NexiaThermostatSensor` described below.
Class description:
Provides Nexia thermostat sensor support.
Method signatures and docstrings:
- def __init__(self, coordinator, thermostat, sensor_call, translation_key, sensor_class, sensor_unit, state_class, modifier=None): Initialize the sensor.
... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class NexiaThermostatSensor:
"""Provides Nexia thermostat sensor support."""
def __init__(self, coordinator, thermostat, sensor_call, translation_key, sensor_class, sensor_unit, state_class, modifier=None):
"""Initialize the sensor."""
<|body_0|>
def native_value(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NexiaThermostatSensor:
"""Provides Nexia thermostat sensor support."""
def __init__(self, coordinator, thermostat, sensor_call, translation_key, sensor_class, sensor_unit, state_class, modifier=None):
"""Initialize the sensor."""
super().__init__(coordinator, thermostat, unique_id=f'{ther... | the_stack_v2_python_sparse | homeassistant/components/nexia/sensor.py | home-assistant/core | train | 35,501 |
914473cd8ef728d71f1026c2d9a659d6c2c0ee09 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn EducationRubric()",
"from .education_assignment_grade_type import EducationAssignmentGradeType\nfrom .education_item_body import EducationItemBody\nfrom .entity import Entity\nfrom .identity_set import IdentitySet\nfrom .rubric_level i... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return EducationRubric()
<|end_body_0|>
<|body_start_1|>
from .education_assignment_grade_type import EducationAssignmentGradeType
from .education_item_body import EducationItemBody
fro... | EducationRubric | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EducationRubric:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationRubric:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Ret... | stack_v2_sparse_classes_36k_train_023072 | 5,145 | 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: EducationRubric",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_val... | 3 | null | Implement the Python class `EducationRubric` described below.
Class description:
Implement the EducationRubric class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationRubric: Creates a new instance of the appropriate class based on discriminator... | Implement the Python class `EducationRubric` described below.
Class description:
Implement the EducationRubric class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationRubric: Creates a new instance of the appropriate class based on discriminator... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class EducationRubric:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationRubric:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EducationRubric:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationRubric:
"""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: Educatio... | the_stack_v2_python_sparse | msgraph/generated/models/education_rubric.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
7ff70d0cd8252aaf45b8bc81e38a7b559ede77e1 | [
"set_seed(1)\nds.config.set_seed(1)\nrandom.seed(1)\nif device == 'CPU':\n context.set_context(mode=context.PYNATIVE_MODE, device_target=device)\nelse:\n print('initialize, rank %d / %d, device_id: %d' % (get_rank_id() + 1, get_device_num(), device_id))\n device_num = get_device_num()\n context.set_cont... | <|body_start_0|>
set_seed(1)
ds.config.set_seed(1)
random.seed(1)
if device == 'CPU':
context.set_context(mode=context.PYNATIVE_MODE, device_target=device)
else:
print('initialize, rank %d / %d, device_id: %d' % (get_rank_id() + 1, get_device_num(), device... | utils for initialize and prepare dataloader | MSUtils | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MSUtils:
"""utils for initialize and prepare dataloader"""
def initialize(device='CPU', device_id=0):
""":param device: support GPU/CPU/Ascend"""
<|body_0|>
def prepare_dataloader(dataset, column_names, batch_size=None, num_workers=1, is_shuffle=False):
"""prepar... | stack_v2_sparse_classes_36k_train_023073 | 3,836 | permissive | [
{
"docstring": ":param device: support GPU/CPU/Ascend",
"name": "initialize",
"signature": "def initialize(device='CPU', device_id=0)"
},
{
"docstring": "prepare dataloader :param dataset: dataset :param column_names: column_names :param batch_size: batch_size :param num_workers: worker numbers ... | 2 | stack_v2_sparse_classes_30k_train_013535 | Implement the Python class `MSUtils` described below.
Class description:
utils for initialize and prepare dataloader
Method signatures and docstrings:
- def initialize(device='CPU', device_id=0): :param device: support GPU/CPU/Ascend
- def prepare_dataloader(dataset, column_names, batch_size=None, num_workers=1, is_s... | Implement the Python class `MSUtils` described below.
Class description:
utils for initialize and prepare dataloader
Method signatures and docstrings:
- def initialize(device='CPU', device_id=0): :param device: support GPU/CPU/Ascend
- def prepare_dataloader(dataset, column_names, batch_size=None, num_workers=1, is_s... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class MSUtils:
"""utils for initialize and prepare dataloader"""
def initialize(device='CPU', device_id=0):
""":param device: support GPU/CPU/Ascend"""
<|body_0|>
def prepare_dataloader(dataset, column_names, batch_size=None, num_workers=1, is_shuffle=False):
"""prepar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MSUtils:
"""utils for initialize and prepare dataloader"""
def initialize(device='CPU', device_id=0):
""":param device: support GPU/CPU/Ascend"""
set_seed(1)
ds.config.set_seed(1)
random.seed(1)
if device == 'CPU':
context.set_context(mode=context.PYNAT... | the_stack_v2_python_sparse | research/cv/rcnn/src/common/mindspore_utils.py | mindspore-ai/models | train | 301 |
0a784cb11b5c59e7e863115663fc92a655801083 | [
"def dfs(path):\n if len(path) == len(s):\n res = ''.join(path)\n if res not in ans:\n ans.append(res)\n return\n for j in range(len(s)):\n if visited[j]:\n continue\n visited[j] = 1\n path.append(s[j])\n dfs(path)\n visited[j] = 0\... | <|body_start_0|>
def dfs(path):
if len(path) == len(s):
res = ''.join(path)
if res not in ans:
ans.append(res)
return
for j in range(len(s)):
if visited[j]:
continue
vi... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def permutation(self, s: str) -> List[str]:
"""思路:dfs回溯,超时"""
<|body_0|>
def permutation1(self, s: str) -> List[str]:
"""思路:dfs回溯,剪枝:1,排序去重i vs i-1,2,每位对应一个set"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def dfs(path):
if l... | stack_v2_sparse_classes_36k_train_023074 | 2,768 | permissive | [
{
"docstring": "思路:dfs回溯,超时",
"name": "permutation",
"signature": "def permutation(self, s: str) -> List[str]"
},
{
"docstring": "思路:dfs回溯,剪枝:1,排序去重i vs i-1,2,每位对应一个set",
"name": "permutation1",
"signature": "def permutation1(self, s: str) -> List[str]"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def permutation(self, s: str) -> List[str]: 思路:dfs回溯,超时
- def permutation1(self, s: str) -> List[str]: 思路:dfs回溯,剪枝:1,排序去重i vs i-1,2,每位对应一个set | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def permutation(self, s: str) -> List[str]: 思路:dfs回溯,超时
- def permutation1(self, s: str) -> List[str]: 思路:dfs回溯,剪枝:1,排序去重i vs i-1,2,每位对应一个set
<|skeleton|>
class Solution:
d... | e8a1c6cae6547cbcb6e8494be6df685f3e7c837c | <|skeleton|>
class Solution:
def permutation(self, s: str) -> List[str]:
"""思路:dfs回溯,超时"""
<|body_0|>
def permutation1(self, s: str) -> List[str]:
"""思路:dfs回溯,剪枝:1,排序去重i vs i-1,2,每位对应一个set"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def permutation(self, s: str) -> List[str]:
"""思路:dfs回溯,超时"""
def dfs(path):
if len(path) == len(s):
res = ''.join(path)
if res not in ans:
ans.append(res)
return
for j in range(len(s)):
... | the_stack_v2_python_sparse | lcof/38-zi-fu-chuan-de-pai-lie-lcof.py | yuenliou/leetcode | train | 0 | |
d06d1f73e290d05221b70593a3bb9e1801a49564 | [
"time_zone_offset = self._GetValueFromStructure(structure, 'time_zone_offset')\ntry:\n time_zone_offset_hours = int(time_zone_offset[1:3], 10)\n time_zone_offset_minutes = int(time_zone_offset[3:5], 10)\nexcept (IndexError, TypeError, ValueError) as exception:\n raise ValueError('unable to parse time zone ... | <|body_start_0|>
time_zone_offset = self._GetValueFromStructure(structure, 'time_zone_offset')
try:
time_zone_offset_hours = int(time_zone_offset[1:3], 10)
time_zone_offset_minutes = int(time_zone_offset[3:5], 10)
except (IndexError, TypeError, ValueError) as exception:
... | Parses events from Google Drive Sync log files. | GoogleDriveSyncLogParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoogleDriveSyncLogParser:
"""Parses events from Google Drive Sync log files."""
def _GetISO8601String(self, structure):
"""Retrieves an ISO 8601 date time string from the structure. The date and time values in Google Drive Sync log files are formatted as: "2018-01-24 18:25:08,454 -08... | stack_v2_sparse_classes_36k_train_023075 | 8,303 | permissive | [
{
"docstring": "Retrieves an ISO 8601 date time string from the structure. The date and time values in Google Drive Sync log files are formatted as: \"2018-01-24 18:25:08,454 -0800\". Args: structure (pyparsing.ParseResults): structure of tokens derived from a line of a text file, that contains the time element... | 4 | null | Implement the Python class `GoogleDriveSyncLogParser` described below.
Class description:
Parses events from Google Drive Sync log files.
Method signatures and docstrings:
- def _GetISO8601String(self, structure): Retrieves an ISO 8601 date time string from the structure. The date and time values in Google Drive Sync... | Implement the Python class `GoogleDriveSyncLogParser` described below.
Class description:
Parses events from Google Drive Sync log files.
Method signatures and docstrings:
- def _GetISO8601String(self, structure): Retrieves an ISO 8601 date time string from the structure. The date and time values in Google Drive Sync... | c69b2952b608cfce47ff8fd0d1409d856be35cb1 | <|skeleton|>
class GoogleDriveSyncLogParser:
"""Parses events from Google Drive Sync log files."""
def _GetISO8601String(self, structure):
"""Retrieves an ISO 8601 date time string from the structure. The date and time values in Google Drive Sync log files are formatted as: "2018-01-24 18:25:08,454 -08... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GoogleDriveSyncLogParser:
"""Parses events from Google Drive Sync log files."""
def _GetISO8601String(self, structure):
"""Retrieves an ISO 8601 date time string from the structure. The date and time values in Google Drive Sync log files are formatted as: "2018-01-24 18:25:08,454 -0800". Args: st... | the_stack_v2_python_sparse | plaso/parsers/gdrive_synclog.py | cyb3rfox/plaso | train | 3 |
7328b07eaa3c2cc5d17279e58805e6692ec46465 | [
"self.dest_guid = dest_guid\nself.object_flags = object_flags\nself.property_status_vec = property_status_vec\nself.source_guid = source_guid\nself.status = status\nself.timetaken_ms = timetaken_ms",
"if dictionary is None:\n return None\ndest_guid = dictionary.get('destGuid')\nobject_flags = dictionary.get('o... | <|body_start_0|>
self.dest_guid = dest_guid
self.object_flags = object_flags
self.property_status_vec = property_status_vec
self.source_guid = source_guid
self.status = status
self.timetaken_ms = timetaken_ms
<|end_body_0|>
<|body_start_1|>
if dictionary is None:... | Implementation of the 'ADObjectRestoreStatus' model. TODO: type description here. Attributes: dest_guid (string): Destination guid string of the AD object that is newly created on production AD corresponding to 'source_guid'. If the object was restored from production AD recycle Bin, this value can be empty or set to s... | ADObjectRestoreStatus | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ADObjectRestoreStatus:
"""Implementation of the 'ADObjectRestoreStatus' model. TODO: type description here. Attributes: dest_guid (string): Destination guid string of the AD object that is newly created on production AD corresponding to 'source_guid'. If the object was restored from production AD... | stack_v2_sparse_classes_36k_train_023076 | 4,444 | permissive | [
{
"docstring": "Constructor for the ADObjectRestoreStatus class",
"name": "__init__",
"signature": "def __init__(self, dest_guid=None, object_flags=None, property_status_vec=None, source_guid=None, status=None, timetaken_ms=None)"
},
{
"docstring": "Creates an instance of this model from a dicti... | 2 | stack_v2_sparse_classes_30k_train_019287 | Implement the Python class `ADObjectRestoreStatus` described below.
Class description:
Implementation of the 'ADObjectRestoreStatus' model. TODO: type description here. Attributes: dest_guid (string): Destination guid string of the AD object that is newly created on production AD corresponding to 'source_guid'. If the... | Implement the Python class `ADObjectRestoreStatus` described below.
Class description:
Implementation of the 'ADObjectRestoreStatus' model. TODO: type description here. Attributes: dest_guid (string): Destination guid string of the AD object that is newly created on production AD corresponding to 'source_guid'. If the... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ADObjectRestoreStatus:
"""Implementation of the 'ADObjectRestoreStatus' model. TODO: type description here. Attributes: dest_guid (string): Destination guid string of the AD object that is newly created on production AD corresponding to 'source_guid'. If the object was restored from production AD... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ADObjectRestoreStatus:
"""Implementation of the 'ADObjectRestoreStatus' model. TODO: type description here. Attributes: dest_guid (string): Destination guid string of the AD object that is newly created on production AD corresponding to 'source_guid'. If the object was restored from production AD recycle Bin,... | the_stack_v2_python_sparse | cohesity_management_sdk/models/ad_object_restore_status.py | cohesity/management-sdk-python | train | 24 |
e48765a96366f7dc03be40cc294177f215eb3ff4 | [
"VDriveCommand.__init__(self, controller, command_args)\nself.check_command_arguments(self.SupportedArgs)\nreturn",
"input_args = self._commandArgsDict.keys()\nfor arg_key in input_args:\n if arg_key not in RunsInfoQuery.SupportedArgs:\n raise KeyError('INFO argument {} is not recognized. Supported arg... | <|body_start_0|>
VDriveCommand.__init__(self, controller, command_args)
self.check_command_arguments(self.SupportedArgs)
return
<|end_body_0|>
<|body_start_1|>
input_args = self._commandArgsDict.keys()
for arg_key in input_args:
if arg_key not in RunsInfoQuery.Suppor... | Process command MERGE | RunsInfoQuery | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunsInfoQuery:
"""Process command MERGE"""
def __init__(self, controller, command_args):
"""Initialization"""
<|body_0|>
def exec_cmd(self):
"""Execute input command"""
<|body_1|>
def format_list_to_str(info_dict_list, keys):
"""format the ru... | stack_v2_sparse_classes_36k_train_023077 | 5,215 | no_license | [
{
"docstring": "Initialization",
"name": "__init__",
"signature": "def __init__(self, controller, command_args)"
},
{
"docstring": "Execute input command",
"name": "exec_cmd",
"signature": "def exec_cmd(self)"
},
{
"docstring": "format the run information dictionary list into nic... | 4 | null | Implement the Python class `RunsInfoQuery` described below.
Class description:
Process command MERGE
Method signatures and docstrings:
- def __init__(self, controller, command_args): Initialization
- def exec_cmd(self): Execute input command
- def format_list_to_str(info_dict_list, keys): format the run information d... | Implement the Python class `RunsInfoQuery` described below.
Class description:
Process command MERGE
Method signatures and docstrings:
- def __init__(self, controller, command_args): Initialization
- def exec_cmd(self): Execute input command
- def format_list_to_str(info_dict_list, keys): format the run information d... | 875a5b99a7a6f51129844bf8052fc6f231497d71 | <|skeleton|>
class RunsInfoQuery:
"""Process command MERGE"""
def __init__(self, controller, command_args):
"""Initialization"""
<|body_0|>
def exec_cmd(self):
"""Execute input command"""
<|body_1|>
def format_list_to_str(info_dict_list, keys):
"""format the ru... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RunsInfoQuery:
"""Process command MERGE"""
def __init__(self, controller, command_args):
"""Initialization"""
VDriveCommand.__init__(self, controller, command_args)
self.check_command_arguments(self.SupportedArgs)
return
def exec_cmd(self):
"""Execute input co... | the_stack_v2_python_sparse | pyvdrive/interface/vdrive_commands/show_info.py | neutrons/PyVDrive | train | 2 |
fc172eb3354166984cc3c6c08ee8c531dfccc707 | [
"project = kwargs.pop('project', None)\nsuper(self.__class__, self).__init__(*args, **kwargs)\nself.fields['parent'].queryset = Task.objects.filter(project=project)\nself.fields['type'].queryset = Type.objects.filter(is_project_type=True)\nself.fields['owner'].queryset = User.objects.filter(is_active=True, is_staff... | <|body_start_0|>
project = kwargs.pop('project', None)
super(self.__class__, self).__init__(*args, **kwargs)
self.fields['parent'].queryset = Task.objects.filter(project=project)
self.fields['type'].queryset = Type.objects.filter(is_project_type=True)
self.fields['owner'].queryse... | Form representing task model | TaskForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaskForm:
"""Form representing task model"""
def __init__(self, *args, **kwargs):
"""Overriden init method to have add project related data to fields"""
<|body_0|>
def save(self, user, project, commit=True):
"""Overriden save method to save virtual field which ar... | stack_v2_sparse_classes_36k_train_023078 | 5,361 | no_license | [
{
"docstring": "Overriden init method to have add project related data to fields",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Overriden save method to save virtual field which are not displayed to user",
"name": "save",
"signature": "def sav... | 2 | stack_v2_sparse_classes_30k_train_007603 | Implement the Python class `TaskForm` described below.
Class description:
Form representing task model
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Overriden init method to have add project related data to fields
- def save(self, user, project, commit=True): Overriden save method to save v... | Implement the Python class `TaskForm` described below.
Class description:
Form representing task model
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Overriden init method to have add project related data to fields
- def save(self, user, project, commit=True): Overriden save method to save v... | 7a337e0e3a20180b9564de68ab22620dc9aa1a36 | <|skeleton|>
class TaskForm:
"""Form representing task model"""
def __init__(self, *args, **kwargs):
"""Overriden init method to have add project related data to fields"""
<|body_0|>
def save(self, user, project, commit=True):
"""Overriden save method to save virtual field which ar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TaskForm:
"""Form representing task model"""
def __init__(self, *args, **kwargs):
"""Overriden init method to have add project related data to fields"""
project = kwargs.pop('project', None)
super(self.__class__, self).__init__(*args, **kwargs)
self.fields['parent'].querys... | the_stack_v2_python_sparse | project_management/tasks/forms.py | raveena17/ILASM | train | 0 |
5d6b06fa7182a7cd1cd649edace36c9b8cb5d12b | [
"while True:\n table = self._get_nodes_table(timeout)\n try:\n return table\n except StaleElementReferenceException:\n self.progress('retrying after stale element')\n time.sleep(1)\n continue\n except NoSuchElementException:\n self.progress('retrying after no such elem... | <|body_start_0|>
while True:
table = self._get_nodes_table(timeout)
try:
return table
except StaleElementReferenceException:
self.progress('retrying after stale element')
time.sleep(1)
continue
except... | Class for Nodes page | NodesPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NodesPage:
"""Class for Nodes page"""
def cluster_get_nodes_table(self, timeout=20):
"""extract the table of coordinators / dbservers from the 'nodes' page"""
<|body_0|>
def _get_nodes_table(self, timeout):
"""repeatable inner func"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_023079 | 3,337 | no_license | [
{
"docstring": "extract the table of coordinators / dbservers from the 'nodes' page",
"name": "cluster_get_nodes_table",
"signature": "def cluster_get_nodes_table(self, timeout=20)"
},
{
"docstring": "repeatable inner func",
"name": "_get_nodes_table",
"signature": "def _get_nodes_table(... | 2 | null | Implement the Python class `NodesPage` described below.
Class description:
Class for Nodes page
Method signatures and docstrings:
- def cluster_get_nodes_table(self, timeout=20): extract the table of coordinators / dbservers from the 'nodes' page
- def _get_nodes_table(self, timeout): repeatable inner func | Implement the Python class `NodesPage` described below.
Class description:
Class for Nodes page
Method signatures and docstrings:
- def cluster_get_nodes_table(self, timeout=20): extract the table of coordinators / dbservers from the 'nodes' page
- def _get_nodes_table(self, timeout): repeatable inner func
<|skeleto... | 4d4a0b049eb83625df41d86f2066ddb0c6c9c85b | <|skeleton|>
class NodesPage:
"""Class for Nodes page"""
def cluster_get_nodes_table(self, timeout=20):
"""extract the table of coordinators / dbservers from the 'nodes' page"""
<|body_0|>
def _get_nodes_table(self, timeout):
"""repeatable inner func"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NodesPage:
"""Class for Nodes page"""
def cluster_get_nodes_table(self, timeout=20):
"""extract the table of coordinators / dbservers from the 'nodes' page"""
while True:
table = self._get_nodes_table(timeout)
try:
return table
except St... | the_stack_v2_python_sparse | release_tester/selenium_ui_test/pages/nodes_page.py | arangodb/release-test-automation | train | 14 |
8de04dfd1d12abade9dd0d0afd7c2cba678cd986 | [
"if p.val < root.val and q.val < root.val:\n return self.lowestCommonAncestor(root.left, p, q)\nelif p.val > root.val and q.val > root.val:\n return self.lowestCommonAncestor(root.right, p, q)\nelse:\n return root",
"p_val = p.val\nq_val = q.val\nwhile root:\n root_val = root.val\n if p_val < root_... | <|body_start_0|>
if p.val < root.val and q.val < root.val:
return self.lowestCommonAncestor(root.left, p, q)
elif p.val > root.val and q.val > root.val:
return self.lowestCommonAncestor(root.right, p, q)
else:
return root
<|end_body_0|>
<|body_start_1|>
... | Solution | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root, p, q):
"""76ms"""
<|body_0|>
def lowestCommonAncestor2(self, root, p, q):
"""64ms"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if p.val < root.val and q.val < root.val:
return self.lowest... | stack_v2_sparse_classes_36k_train_023080 | 1,776 | permissive | [
{
"docstring": "76ms",
"name": "lowestCommonAncestor",
"signature": "def lowestCommonAncestor(self, root, p, q)"
},
{
"docstring": "64ms",
"name": "lowestCommonAncestor2",
"signature": "def lowestCommonAncestor2(self, root, p, q)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001898 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root, p, q): 76ms
- def lowestCommonAncestor2(self, root, p, q): 64ms | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root, p, q): 76ms
- def lowestCommonAncestor2(self, root, p, q): 64ms
<|skeleton|>
class Solution:
def lowestCommonAncestor(self, root, p, q)... | 49a0b03c55d8a702785888d473ef96539265ce9c | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root, p, q):
"""76ms"""
<|body_0|>
def lowestCommonAncestor2(self, root, p, q):
"""64ms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lowestCommonAncestor(self, root, p, q):
"""76ms"""
if p.val < root.val and q.val < root.val:
return self.lowestCommonAncestor(root.left, p, q)
elif p.val > root.val and q.val > root.val:
return self.lowestCommonAncestor(root.right, p, q)
el... | the_stack_v2_python_sparse | leetcode/0235_lowest_common_ancestor_of_a_binary_search_tree.py | chaosWsF/Python-Practice | train | 1 | |
34b2947b5a6582162f22386d47bdcc65582a72a0 | [
"self.sn_str = str_val\ntmp = str_val.split(':')\nif len(tmp) != 3:\n raise ValueError('Unknown format for snapshot')\nself.xmin = int(tmp[0])\nself.xmax = int(tmp[1])\nself.txid_list = []\nif tmp[2] != '':\n for s in tmp[2].split(','):\n self.txid_list.append(int(s))",
"txid = int(txid)\nif txid < s... | <|body_start_0|>
self.sn_str = str_val
tmp = str_val.split(':')
if len(tmp) != 3:
raise ValueError('Unknown format for snapshot')
self.xmin = int(tmp[0])
self.xmax = int(tmp[1])
self.txid_list = []
if tmp[2] != '':
for s in tmp[2].split(','... | Represents a PostgreSQL snapshot. | Snapshot | [
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Snapshot:
"""Represents a PostgreSQL snapshot."""
def __init__(self, str_val: str):
"""Create snapshot from string."""
<|body_0|>
def contains(self, txid: int) -> bool:
"""Is txid visible in snapshot."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_023081 | 20,712 | permissive | [
{
"docstring": "Create snapshot from string.",
"name": "__init__",
"signature": "def __init__(self, str_val: str)"
},
{
"docstring": "Is txid visible in snapshot.",
"name": "contains",
"signature": "def contains(self, txid: int) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_train_014304 | Implement the Python class `Snapshot` described below.
Class description:
Represents a PostgreSQL snapshot.
Method signatures and docstrings:
- def __init__(self, str_val: str): Create snapshot from string.
- def contains(self, txid: int) -> bool: Is txid visible in snapshot. | Implement the Python class `Snapshot` described below.
Class description:
Represents a PostgreSQL snapshot.
Method signatures and docstrings:
- def __init__(self, str_val: str): Create snapshot from string.
- def contains(self, txid: int) -> bool: Is txid visible in snapshot.
<|skeleton|>
class Snapshot:
"""Repr... | 0b846b65de4090228355a8494a3c731480f6dfbe | <|skeleton|>
class Snapshot:
"""Represents a PostgreSQL snapshot."""
def __init__(self, str_val: str):
"""Create snapshot from string."""
<|body_0|>
def contains(self, txid: int) -> bool:
"""Is txid visible in snapshot."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Snapshot:
"""Represents a PostgreSQL snapshot."""
def __init__(self, str_val: str):
"""Create snapshot from string."""
self.sn_str = str_val
tmp = str_val.split(':')
if len(tmp) != 3:
raise ValueError('Unknown format for snapshot')
self.xmin = int(tmp[0... | the_stack_v2_python_sparse | skytools/sqltools.py | pgq/python-skytools | train | 8 |
e47bfa7c393f7986728d05fc668c133b54a675c6 | [
"if option_dict is None:\n return None\noption_dict.update(kwargs)\nlogger.info(f'create {cls.__name__} from dict')\nreturn cls(**option_dict)",
"if option_file is None:\n return None\noption_dict = load_yaml(option_file)\noption_dict.update(kwargs)\nlogger.info(f'create {cls.__name__} from file {option_fil... | <|body_start_0|>
if option_dict is None:
return None
option_dict.update(kwargs)
logger.info(f'create {cls.__name__} from dict')
return cls(**option_dict)
<|end_body_0|>
<|body_start_1|>
if option_file is None:
return None
option_dict = load_yaml(o... | _Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Base:
def from_dict(cls: Type[T], option_dict: dict, **kwargs) -> T:
"""Build option from a dict of arguments :param option_dict: Dict of arguments :param kwargs: extra keyword arguments :return: T instance"""
<|body_0|>
def from_file(cls: Type[T], option_file: str, **kwarg... | stack_v2_sparse_classes_36k_train_023082 | 2,323 | no_license | [
{
"docstring": "Build option from a dict of arguments :param option_dict: Dict of arguments :param kwargs: extra keyword arguments :return: T instance",
"name": "from_dict",
"signature": "def from_dict(cls: Type[T], option_dict: dict, **kwargs) -> T"
},
{
"docstring": "Build option from a yaml f... | 2 | stack_v2_sparse_classes_30k_train_011243 | Implement the Python class `_Base` described below.
Class description:
Implement the _Base class.
Method signatures and docstrings:
- def from_dict(cls: Type[T], option_dict: dict, **kwargs) -> T: Build option from a dict of arguments :param option_dict: Dict of arguments :param kwargs: extra keyword arguments :retur... | Implement the Python class `_Base` described below.
Class description:
Implement the _Base class.
Method signatures and docstrings:
- def from_dict(cls: Type[T], option_dict: dict, **kwargs) -> T: Build option from a dict of arguments :param option_dict: Dict of arguments :param kwargs: extra keyword arguments :retur... | c9c2e32b484687ef5b110af3dd39f86ecfcb5337 | <|skeleton|>
class _Base:
def from_dict(cls: Type[T], option_dict: dict, **kwargs) -> T:
"""Build option from a dict of arguments :param option_dict: Dict of arguments :param kwargs: extra keyword arguments :return: T instance"""
<|body_0|>
def from_file(cls: Type[T], option_file: str, **kwarg... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _Base:
def from_dict(cls: Type[T], option_dict: dict, **kwargs) -> T:
"""Build option from a dict of arguments :param option_dict: Dict of arguments :param kwargs: extra keyword arguments :return: T instance"""
if option_dict is None:
return None
option_dict.update(kwargs)
... | the_stack_v2_python_sparse | src/pytorch_helper/settings/options/base.py | Aaronswei/BEVNet | train | 0 | |
370bec17897baa180ef122d226e278ddd2260ba1 | [
"if not isinstance(style, TMBStyle):\n msg = \"'style' argument must be of class 'TMBStyle', not '{0}'\"\n raise TypeError(msg.format(style.__class__.__name__))\nplanes.gui.Container.__init__(self, name, padding)\nself.style = style\nself.background = None\nself.rect.width = self.style.top_img.get_width()\nre... | <|body_start_0|>
if not isinstance(style, TMBStyle):
msg = "'style' argument must be of class 'TMBStyle', not '{0}'"
raise TypeError(msg.format(style.__class__.__name__))
planes.gui.Container.__init__(self, name, padding)
self.style = style
self.background = None
... | A planes.gui.Container with fixed width and TMB background. Additional attributes: TMBContainer.style An instance of TMBStyle. TMBContainer.background A Pygame Surface, holding the rendered background. Initially None, repainted in TMBContainer.sub(). | TMBContainer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TMBContainer:
"""A planes.gui.Container with fixed width and TMB background. Additional attributes: TMBContainer.style An instance of TMBStyle. TMBContainer.background A Pygame Surface, holding the rendered background. Initially None, repainted in TMBContainer.sub()."""
def __init__(self, na... | stack_v2_sparse_classes_36k_train_023083 | 13,968 | no_license | [
{
"docstring": "Initialise. style is an instance of TMBStyle.",
"name": "__init__",
"signature": "def __init__(self, name, style, padding=0)"
},
{
"docstring": "Resize the container, update the position of plane and add it as a subplane. This will also repaint TMBContainer.background.",
"nam... | 4 | stack_v2_sparse_classes_30k_train_006345 | Implement the Python class `TMBContainer` described below.
Class description:
A planes.gui.Container with fixed width and TMB background. Additional attributes: TMBContainer.style An instance of TMBStyle. TMBContainer.background A Pygame Surface, holding the rendered background. Initially None, repainted in TMBContain... | Implement the Python class `TMBContainer` described below.
Class description:
A planes.gui.Container with fixed width and TMB background. Additional attributes: TMBContainer.style An instance of TMBStyle. TMBContainer.background A Pygame Surface, holding the rendered background. Initially None, repainted in TMBContain... | c0fd400a84d722bae10c68ff1615c82a649ff6e6 | <|skeleton|>
class TMBContainer:
"""A planes.gui.Container with fixed width and TMB background. Additional attributes: TMBContainer.style An instance of TMBStyle. TMBContainer.background A Pygame Surface, holding the rendered background. Initially None, repainted in TMBContainer.sub()."""
def __init__(self, na... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TMBContainer:
"""A planes.gui.Container with fixed width and TMB background. Additional attributes: TMBContainer.style An instance of TMBStyle. TMBContainer.background A Pygame Surface, holding the rendered background. Initially None, repainted in TMBContainer.sub()."""
def __init__(self, name, style, pa... | the_stack_v2_python_sparse | planes/gui/tmb.py | aloverso/FrisbE | train | 1 |
59b53af55bab5cc560fcb2243f77a5802002be72 | [
"preorder, inorder = ([], [])\n\ndef helper(root):\n if not root:\n return\n preorder.append(root.val)\n helper(root.left)\n inorder.append(root.val)\n helper(root.right)\nhelper(root)\nreturn ':'.join(map(str, preorder)) + ':' + ':'.join(map(str, inorder))",
"l = data.split(':')\nif l == ['... | <|body_start_0|>
preorder, inorder = ([], [])
def helper(root):
if not root:
return
preorder.append(root.val)
helper(root.left)
inorder.append(root.val)
helper(root.right)
helper(root)
return ':'.join(map(str, p... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_023084 | 1,568 | 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_011527 | 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:... | 4ef763841632f2ba0a616b13c70e8650ada4ae16 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
preorder, inorder = ([], [])
def helper(root):
if not root:
return
preorder.append(root.val)
helper(root.left)
in... | the_stack_v2_python_sparse | leetcode449.py | kduan005/Leetcode | train | 0 | |
6f4cb55a74da7b43fc3207dbc5a2f8ed41a29270 | [
"super(LinearKernelSteinTest, self).__init__(p, alpha)\nself.k = k\nself.seed = seed",
"with util.ContextTimer() as t:\n alpha = self.alpha\n X = dat.data()\n n = X.shape[0]\n _, H = self.compute_stat(dat, return_pointwise_stats=True)\n test_stat = np.sqrt(old_div(n, 2)) * np.mean(H)\n stat_var ... | <|body_start_0|>
super(LinearKernelSteinTest, self).__init__(p, alpha)
self.k = k
self.seed = seed
<|end_body_0|>
<|body_start_1|>
with util.ContextTimer() as t:
alpha = self.alpha
X = dat.data()
n = X.shape[0]
_, H = self.compute_stat(dat... | Goodness-of-fit test using the linear-version of kernelized Stein discrepancy test of Liu et al., 2016 in ICML 2016. Described in Liu et al., 2016. - This test runs in O(n d^2) time. - test stat = sqrt(n_half)*linear-time Stein discrepancy - Asymptotically normal under both H0 and H1. H0: the sample follows p H1: the s... | LinearKernelSteinTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearKernelSteinTest:
"""Goodness-of-fit test using the linear-version of kernelized Stein discrepancy test of Liu et al., 2016 in ICML 2016. Described in Liu et al., 2016. - This test runs in O(n d^2) time. - test stat = sqrt(n_half)*linear-time Stein discrepancy - Asymptotically normal under b... | stack_v2_sparse_classes_36k_train_023085 | 41,550 | permissive | [
{
"docstring": "p: an instance of UnnormalizedDensity k: a LinearKSTKernel object alpha: significance level n_simulate: The number of times to simulate from the null distribution by bootstrapping. Must be a positive integer.",
"name": "__init__",
"signature": "def __init__(self, p, k, alpha=0.01, seed=1... | 3 | stack_v2_sparse_classes_30k_train_012049 | Implement the Python class `LinearKernelSteinTest` described below.
Class description:
Goodness-of-fit test using the linear-version of kernelized Stein discrepancy test of Liu et al., 2016 in ICML 2016. Described in Liu et al., 2016. - This test runs in O(n d^2) time. - test stat = sqrt(n_half)*linear-time Stein disc... | Implement the Python class `LinearKernelSteinTest` described below.
Class description:
Goodness-of-fit test using the linear-version of kernelized Stein discrepancy test of Liu et al., 2016 in ICML 2016. Described in Liu et al., 2016. - This test runs in O(n d^2) time. - test stat = sqrt(n_half)*linear-time Stein disc... | 039a95ed9d8062e283da6bd051b7161a190b4876 | <|skeleton|>
class LinearKernelSteinTest:
"""Goodness-of-fit test using the linear-version of kernelized Stein discrepancy test of Liu et al., 2016 in ICML 2016. Described in Liu et al., 2016. - This test runs in O(n d^2) time. - test stat = sqrt(n_half)*linear-time Stein discrepancy - Asymptotically normal under b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinearKernelSteinTest:
"""Goodness-of-fit test using the linear-version of kernelized Stein discrepancy test of Liu et al., 2016 in ICML 2016. Described in Liu et al., 2016. - This test runs in O(n d^2) time. - test stat = sqrt(n_half)*linear-time Stein discrepancy - Asymptotically normal under both H0 and H1... | the_stack_v2_python_sparse | kgof/goftest.py | wittawatj/kernel-gof | train | 69 |
f7a24c81d67e7e6682af76914e62540c1849ff1b | [
"Va = angle(V)\nVm = abs(V)\nF = self._evaluate_function(Ybus, V, Sbus, pv, pq)\nconverged = self._check_convergence(F)\ni = 0\nwhile not converged and i < self.iter_max:\n V, Vm, Va = self._one_iteration(F, Ybus, V, Vm, Va, pv, pq, pvpq)\n F = self._evaluate_function(Ybus, V, Sbus, pv, pq)\n converged = s... | <|body_start_0|>
Va = angle(V)
Vm = abs(V)
F = self._evaluate_function(Ybus, V, Sbus, pv, pq)
converged = self._check_convergence(F)
i = 0
while not converged and i < self.iter_max:
V, Vm, Va = self._one_iteration(F, Ybus, V, Vm, Va, pv, pq, pvpq)
... | Solves the power flow using full Newton's method. Based on newtonpf.m from MATPOWER by Ray Zimmerman, developed at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more info. | NewtonPF | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewtonPF:
"""Solves the power flow using full Newton's method. Based on newtonpf.m from MATPOWER by Ray Zimmerman, developed at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more info."""
def _run_power_flow(self, Ybus, Sbus, V, pv, pq, pvpq, **kw_args):
"""Solves ... | stack_v2_sparse_classes_36k_train_023086 | 16,710 | permissive | [
{
"docstring": "Solves the power flow using a full Newton's method.",
"name": "_run_power_flow",
"signature": "def _run_power_flow(self, Ybus, Sbus, V, pv, pq, pvpq, **kw_args)"
},
{
"docstring": "Performs one Newton iteration.",
"name": "_one_iteration",
"signature": "def _one_iteration... | 5 | stack_v2_sparse_classes_30k_train_020173 | Implement the Python class `NewtonPF` described below.
Class description:
Solves the power flow using full Newton's method. Based on newtonpf.m from MATPOWER by Ray Zimmerman, developed at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more info.
Method signatures and docstrings:
- def _run_power_fl... | Implement the Python class `NewtonPF` described below.
Class description:
Solves the power flow using full Newton's method. Based on newtonpf.m from MATPOWER by Ray Zimmerman, developed at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more info.
Method signatures and docstrings:
- def _run_power_fl... | 916514255db1ae1661406f0283df756baf960d14 | <|skeleton|>
class NewtonPF:
"""Solves the power flow using full Newton's method. Based on newtonpf.m from MATPOWER by Ray Zimmerman, developed at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more info."""
def _run_power_flow(self, Ybus, Sbus, V, pv, pq, pvpq, **kw_args):
"""Solves ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NewtonPF:
"""Solves the power flow using full Newton's method. Based on newtonpf.m from MATPOWER by Ray Zimmerman, developed at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more info."""
def _run_power_flow(self, Ybus, Sbus, V, pv, pq, pvpq, **kw_args):
"""Solves the power flo... | the_stack_v2_python_sparse | pylon/ac_pf.py | rwl/pylon | train | 15 |
0212a9501aa8b01ee2901c1721dfd0fe2ba89960 | [
"backup_count = 0\nsuper(CompressedFileHandler, self).__init__(filename, mode=mode, maxBytes=max_bytes, backupCount=backup_count, encoding=encoding, delay=delay)\nself.suffix = '%Y%m%d-%H%M%S'\nself.extMatch = '^\\\\d{4}\\\\d{2}\\\\d{2}-\\\\d{2}\\\\d{2}\\\\d{2}$'\nself.extMatch = re.compile(self.extMatch)",
"if s... | <|body_start_0|>
backup_count = 0
super(CompressedFileHandler, self).__init__(filename, mode=mode, maxBytes=max_bytes, backupCount=backup_count, encoding=encoding, delay=delay)
self.suffix = '%Y%m%d-%H%M%S'
self.extMatch = '^\\d{4}\\d{2}\\d{2}-\\d{2}\\d{2}\\d{2}$'
self.extMatch =... | A custom log handler to compress files. | CompressedFileHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompressedFileHandler:
"""A custom log handler to compress files."""
def __init__(self, filename, mode='a', max_bytes=0, encoding=None, delay=0):
"""Note: We don't want to delete any log files for backupCount is automatically set to 0. If you really want to delete log files set backu... | stack_v2_sparse_classes_36k_train_023087 | 6,555 | permissive | [
{
"docstring": "Note: We don't want to delete any log files for backupCount is automatically set to 0. If you really want to delete log files set backupCount to > 0 example: handler = CompressedFileHandler('logfile.txt') handler.backupCount = 5 Args: filename (str): Path of logfile. mode (str): Mode to open log... | 3 | stack_v2_sparse_classes_30k_train_003866 | Implement the Python class `CompressedFileHandler` described below.
Class description:
A custom log handler to compress files.
Method signatures and docstrings:
- def __init__(self, filename, mode='a', max_bytes=0, encoding=None, delay=0): Note: We don't want to delete any log files for backupCount is automatically s... | Implement the Python class `CompressedFileHandler` described below.
Class description:
A custom log handler to compress files.
Method signatures and docstrings:
- def __init__(self, filename, mode='a', max_bytes=0, encoding=None, delay=0): Note: We don't want to delete any log files for backupCount is automatically s... | 6fb2ca9d7e85826b300d3d7780c30cb09da433c7 | <|skeleton|>
class CompressedFileHandler:
"""A custom log handler to compress files."""
def __init__(self, filename, mode='a', max_bytes=0, encoding=None, delay=0):
"""Note: We don't want to delete any log files for backupCount is automatically set to 0. If you really want to delete log files set backu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CompressedFileHandler:
"""A custom log handler to compress files."""
def __init__(self, filename, mode='a', max_bytes=0, encoding=None, delay=0):
"""Note: We don't want to delete any log files for backupCount is automatically set to 0. If you really want to delete log files set backupCount to > 0... | the_stack_v2_python_sparse | qalib/qabase/log.py | Datera/datera-automation-toolkit | train | 0 |
e932213877e11870036b0aeda1d2e19c63bbfdf0 | [
"res = 0\n\ndef dfs(node, sumVal):\n nonlocal res\n if not node:\n return\n sumVal = sumVal * 10 + node.val\n if not node.left and (not node.right):\n res += sumVal\n dfs(node.left, sumVal)\n dfs(node.right, sumVal)\ndfs(root, 0)\nreturn res",
"if not root:\n return False\n\ndef... | <|body_start_0|>
res = 0
def dfs(node, sumVal):
nonlocal res
if not node:
return
sumVal = sumVal * 10 + node.val
if not node.left and (not node.right):
res += sumVal
dfs(node.left, sumVal)
dfs(node.r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sumNumbers(self, root):
"""https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/ :type root: TreeNode :rtype: int"""
<|body_0|>
def hasPathSum(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: bool"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k_train_023088 | 1,662 | no_license | [
{
"docstring": "https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/ :type root: TreeNode :rtype: int",
"name": "sumNumbers",
"signature": "def sumNumbers(self, root)"
},
{
"docstring": ":type root: TreeNode :type sum: int :rtype: bool",
"name": "hasPathSum",
"signature": "def hasP... | 2 | stack_v2_sparse_classes_30k_train_014350 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumNumbers(self, root): https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/ :type root: TreeNode :rtype: int
- def hasPathSum(self, root, sum): :type root: TreeNode :t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumNumbers(self, root): https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/ :type root: TreeNode :rtype: int
- def hasPathSum(self, root, sum): :type root: TreeNode :t... | 63ac5a0921835b1e9d65f71e1346bbb7d66dad9b | <|skeleton|>
class Solution:
def sumNumbers(self, root):
"""https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/ :type root: TreeNode :rtype: int"""
<|body_0|>
def hasPathSum(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: bool"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sumNumbers(self, root):
"""https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/ :type root: TreeNode :rtype: int"""
res = 0
def dfs(node, sumVal):
nonlocal res
if not node:
return
sumVal = sumVal * 10 + node.val
... | the_stack_v2_python_sparse | LeetCode/中等/树/129. 求根到叶子节点数字之和.py | homezzm/leetcode | train | 1 | |
97cf5fe2bc9be4a1732cb159b55adadf649d4fb4 | [
"\"\"\"Initialization\"\"\"\nself.img_shape = img_shape\nself.chunk_size = chunk_size\nself.attr_vals = load_attr_vals_txts()\nself.attr_cnt = len(self.attr_vals)\nself.train_ids, self.validation_ids, self.test_ids, self.attr_map = load_config_wiki()\nprint('-- Generator Wiki initialized.')",
"images = []\nerrs =... | <|body_start_0|>
"""Initialization"""
self.img_shape = img_shape
self.chunk_size = chunk_size
self.attr_vals = load_attr_vals_txts()
self.attr_cnt = len(self.attr_vals)
self.train_ids, self.validation_ids, self.test_ids, self.attr_map = load_config_wiki()
print('-... | DataGeneratorWiki | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataGeneratorWiki:
def __init__(self, img_shape=(100, 100), chunk_size=1024):
""":param img_shape: resolution of final image :param chunk_size: size of super batch :param rot_int: interval for image rotation"""
<|body_0|>
def get_images_online(self, img_names):
"""Re... | stack_v2_sparse_classes_36k_train_023089 | 3,756 | no_license | [
{
"docstring": ":param img_shape: resolution of final image :param chunk_size: size of super batch :param rot_int: interval for image rotation",
"name": "__init__",
"signature": "def __init__(self, img_shape=(100, 100), chunk_size=1024)"
},
{
"docstring": "Reads list of images from specidied fol... | 4 | stack_v2_sparse_classes_30k_train_003787 | Implement the Python class `DataGeneratorWiki` described below.
Class description:
Implement the DataGeneratorWiki class.
Method signatures and docstrings:
- def __init__(self, img_shape=(100, 100), chunk_size=1024): :param img_shape: resolution of final image :param chunk_size: size of super batch :param rot_int: in... | Implement the Python class `DataGeneratorWiki` described below.
Class description:
Implement the DataGeneratorWiki class.
Method signatures and docstrings:
- def __init__(self, img_shape=(100, 100), chunk_size=1024): :param img_shape: resolution of final image :param chunk_size: size of super batch :param rot_int: in... | acd540fe845d0496c9cf2560f59623de3b93898c | <|skeleton|>
class DataGeneratorWiki:
def __init__(self, img_shape=(100, 100), chunk_size=1024):
""":param img_shape: resolution of final image :param chunk_size: size of super batch :param rot_int: interval for image rotation"""
<|body_0|>
def get_images_online(self, img_names):
"""Re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataGeneratorWiki:
def __init__(self, img_shape=(100, 100), chunk_size=1024):
""":param img_shape: resolution of final image :param chunk_size: size of super batch :param rot_int: interval for image rotation"""
"""Initialization"""
self.img_shape = img_shape
self.chunk_size = c... | the_stack_v2_python_sparse | data_proc/DataGeneratorWiki.py | MarcisinMatej/CNN | train | 0 | |
19d68d6a12838d0255433be2809f1fc4a182032b | [
"QtGui.QGroupBox.__init__(self, parent)\nUi_FrameHarddiskModule.__init__(self)\nself.setupUi(self)\ndeviceFile = self.__check_invalid_values(deviceFile)\nfilesystem = self.__check_invalid_values(filesystem)\nmountingPoint = self.__check_invalid_values(mountingPoint)\nfreeSize = self.__check_invalid_values(freeSize)... | <|body_start_0|>
QtGui.QGroupBox.__init__(self, parent)
Ui_FrameHarddiskModule.__init__(self)
self.setupUi(self)
deviceFile = self.__check_invalid_values(deviceFile)
filesystem = self.__check_invalid_values(filesystem)
mountingPoint = self.__check_invalid_values(mountingP... | Estende de 'QtGui.QGroupBox' e 'Ui_FrameHarddiskModule' Classe que define um GroupBox para a exibição das informações das partições. | GUIHarddiskModule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GUIHarddiskModule:
"""Estende de 'QtGui.QGroupBox' e 'Ui_FrameHarddiskModule' Classe que define um GroupBox para a exibição das informações das partições."""
def __init__(self, parent, deviceFile, filesystem, mountingPoint, size, freeSize):
"""Construtor Parâmetros: parent -- Frame p... | stack_v2_sparse_classes_36k_train_023090 | 2,230 | no_license | [
{
"docstring": "Construtor Parâmetros: parent -- Frame pai deviceFile -- string com o device file filesystem -- string com o tipo de sistema de arquivo mountingPoint -- string com o ponto de montagem da partição size -- int que indica o tamanho da partição freeSize -- int que indica o tamanho livre da partição"... | 2 | stack_v2_sparse_classes_30k_test_000992 | Implement the Python class `GUIHarddiskModule` described below.
Class description:
Estende de 'QtGui.QGroupBox' e 'Ui_FrameHarddiskModule' Classe que define um GroupBox para a exibição das informações das partições.
Method signatures and docstrings:
- def __init__(self, parent, deviceFile, filesystem, mountingPoint, ... | Implement the Python class `GUIHarddiskModule` described below.
Class description:
Estende de 'QtGui.QGroupBox' e 'Ui_FrameHarddiskModule' Classe que define um GroupBox para a exibição das informações das partições.
Method signatures and docstrings:
- def __init__(self, parent, deviceFile, filesystem, mountingPoint, ... | bda0c2c8977dd1246339f1f0f4718d29e8795f21 | <|skeleton|>
class GUIHarddiskModule:
"""Estende de 'QtGui.QGroupBox' e 'Ui_FrameHarddiskModule' Classe que define um GroupBox para a exibição das informações das partições."""
def __init__(self, parent, deviceFile, filesystem, mountingPoint, size, freeSize):
"""Construtor Parâmetros: parent -- Frame p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GUIHarddiskModule:
"""Estende de 'QtGui.QGroupBox' e 'Ui_FrameHarddiskModule' Classe que define um GroupBox para a exibição das informações das partições."""
def __init__(self, parent, deviceFile, filesystem, mountingPoint, size, freeSize):
"""Construtor Parâmetros: parent -- Frame pai deviceFile... | the_stack_v2_python_sparse | src/libs/harddisk/gui_harddisk_module.py | adrianomelo/ldc-desktop | train | 1 |
b8c38b60f69da355289aedf8171a20a4dfe8f089 | [
"super(LearningHandler, self).__init__()\nself.lr = lr\nself.drop = drop\nself.lr_tensor = lr_tensor\nself.patience = patience\nself.tau = tau\nself.tau_tensor = tau_tensor\nself.min_tem = min_tem\nself.gumble = gumble",
"self.assign_op = tf.no_op()\nself.scheduler_stage = 0\nself.best_loss = np.inf\nself.wait = ... | <|body_start_0|>
super(LearningHandler, self).__init__()
self.lr = lr
self.drop = drop
self.lr_tensor = lr_tensor
self.patience = patience
self.tau = tau
self.tau_tensor = tau_tensor
self.min_tem = min_tem
self.gumble = gumble
<|end_body_0|>
<|bod... | Class for managing the learning rate scheduling and early stopping criteria. Learning rate scheduling is implemented by multiplying the learning rate by 'drop' everytime the validation loss does not see any improvement for 'patience' training steps | LearningHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LearningHandler:
"""Class for managing the learning rate scheduling and early stopping criteria. Learning rate scheduling is implemented by multiplying the learning rate by 'drop' everytime the validation loss does not see any improvement for 'patience' training steps"""
def __init__(self, l... | stack_v2_sparse_classes_36k_train_023091 | 10,329 | permissive | [
{
"docstring": "initializer. Args: lr: initial learning rate drop: factor by which learning rate is reduced lr_tensor: tensorflow (or keras) tensor for the learning rate patience: patience of the learning rate scheduler tau_tensor: tensor to kepp the changed temperature tau: temperature min_tem: minimum tempera... | 3 | stack_v2_sparse_classes_30k_train_018007 | Implement the Python class `LearningHandler` described below.
Class description:
Class for managing the learning rate scheduling and early stopping criteria. Learning rate scheduling is implemented by multiplying the learning rate by 'drop' everytime the validation loss does not see any improvement for 'patience' trai... | Implement the Python class `LearningHandler` described below.
Class description:
Class for managing the learning rate scheduling and early stopping criteria. Learning rate scheduling is implemented by multiplying the learning rate by 'drop' everytime the validation loss does not see any improvement for 'patience' trai... | dea327aa9e7ef7f7bca5a6c225dbdca1077a06e9 | <|skeleton|>
class LearningHandler:
"""Class for managing the learning rate scheduling and early stopping criteria. Learning rate scheduling is implemented by multiplying the learning rate by 'drop' everytime the validation loss does not see any improvement for 'patience' training steps"""
def __init__(self, l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LearningHandler:
"""Class for managing the learning rate scheduling and early stopping criteria. Learning rate scheduling is implemented by multiplying the learning rate by 'drop' everytime the validation loss does not see any improvement for 'patience' training steps"""
def __init__(self, lr, drop, lr_t... | the_stack_v2_python_sparse | clustering_normalized_cuts/util.py | Tarkiyah/googleResearch | train | 11 |
e7da7ceb7c675cd9db50cf75759f20e1931e0e29 | [
"ul_tag = response.xpath('//ul[@id=\"pins\"]/li')\nfor li_tag in ul_tag:\n url = li_tag.xpath('./span[1]/a/@href').get()\n title = li_tag.xpath('./span[1]/a/text()').get()\n time = li_tag.xpath('./span[@class=\"time\"]/text()').get()\n self.info['title'] = time + '_' + title\n self.info['url'] = url\... | <|body_start_0|>
ul_tag = response.xpath('//ul[@id="pins"]/li')
for li_tag in ul_tag:
url = li_tag.xpath('./span[1]/a/@href').get()
title = li_tag.xpath('./span[1]/a/text()').get()
time = li_tag.xpath('./span[@class="time"]/text()').get()
self.info['title'... | MztSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MztSpider:
def parse(self, response):
"""在主要页拿到每篇图的url"""
<|body_0|>
def get_link(self, response):
"""在详情页拿到每张图的link"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ul_tag = response.xpath('//ul[@id="pins"]/li')
for li_tag in ul_tag:
... | stack_v2_sparse_classes_36k_train_023092 | 1,864 | no_license | [
{
"docstring": "在主要页拿到每篇图的url",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "在详情页拿到每张图的link",
"name": "get_link",
"signature": "def get_link(self, response)"
}
] | 2 | null | Implement the Python class `MztSpider` described below.
Class description:
Implement the MztSpider class.
Method signatures and docstrings:
- def parse(self, response): 在主要页拿到每篇图的url
- def get_link(self, response): 在详情页拿到每张图的link | Implement the Python class `MztSpider` described below.
Class description:
Implement the MztSpider class.
Method signatures and docstrings:
- def parse(self, response): 在主要页拿到每篇图的url
- def get_link(self, response): 在详情页拿到每张图的link
<|skeleton|>
class MztSpider:
def parse(self, response):
"""在主要页拿到每篇图的url"... | a7eb93ddcde88075bb2217fc285c19ca349af8d7 | <|skeleton|>
class MztSpider:
def parse(self, response):
"""在主要页拿到每篇图的url"""
<|body_0|>
def get_link(self, response):
"""在详情页拿到每张图的link"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MztSpider:
def parse(self, response):
"""在主要页拿到每篇图的url"""
ul_tag = response.xpath('//ul[@id="pins"]/li')
for li_tag in ul_tag:
url = li_tag.xpath('./span[1]/a/@href').get()
title = li_tag.xpath('./span[1]/a/text()').get()
time = li_tag.xpath('./span[... | the_stack_v2_python_sparse | 爬虫基础/Scrapy学习/meizitu/meizitu/spiders/mzt.py | HimriZngz/Code | train | 0 | |
79c613270671d83bc8586a16b460a8548c69ce63 | [
"super().__init__()\nself.api_key = api_key\nself.top_k = top_k\nself.allowed_domains = allowed_domains\nself.kwargs = search_engine_kwargs if search_engine_kwargs else {}",
"kwargs = {**self.kwargs, **kwargs}\ntop_k = kwargs.pop('top_k', self.top_k)\nurl = 'https://api.bing.microsoft.com/v7.0/search'\nallowed_do... | <|body_start_0|>
super().__init__()
self.api_key = api_key
self.top_k = top_k
self.allowed_domains = allowed_domains
self.kwargs = search_engine_kwargs if search_engine_kwargs else {}
<|end_body_0|>
<|body_start_1|>
kwargs = {**self.kwargs, **kwargs}
top_k = kwar... | Search engine using the Bing API. See [Bing Web Search API](https://learn.microsoft.com/en-us/bing/search-apis/bing-web-search/overview) for more details. | BingAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BingAPI:
"""Search engine using the Bing API. See [Bing Web Search API](https://learn.microsoft.com/en-us/bing/search-apis/bing-web-search/overview) for more details."""
def __init__(self, api_key: str, top_k: Optional[int]=10, allowed_domains: Optional[List[str]]=None, search_engine_kwargs:... | stack_v2_sparse_classes_36k_train_023093 | 17,323 | permissive | [
{
"docstring": ":param api_key: API key for the Bing API. :param top_k: Number of documents to return. :param allowed_domains: List of domains to limit the search to. :param search_engine_kwargs: Additional parameters passed to the Bing. As an example, you can pass the market parameter to specify the market to ... | 2 | null | Implement the Python class `BingAPI` described below.
Class description:
Search engine using the Bing API. See [Bing Web Search API](https://learn.microsoft.com/en-us/bing/search-apis/bing-web-search/overview) for more details.
Method signatures and docstrings:
- def __init__(self, api_key: str, top_k: Optional[int]=... | Implement the Python class `BingAPI` described below.
Class description:
Search engine using the Bing API. See [Bing Web Search API](https://learn.microsoft.com/en-us/bing/search-apis/bing-web-search/overview) for more details.
Method signatures and docstrings:
- def __init__(self, api_key: str, top_k: Optional[int]=... | 5f1256ac7e5734c2ea481e72cb7e02c34baf8c43 | <|skeleton|>
class BingAPI:
"""Search engine using the Bing API. See [Bing Web Search API](https://learn.microsoft.com/en-us/bing/search-apis/bing-web-search/overview) for more details."""
def __init__(self, api_key: str, top_k: Optional[int]=10, allowed_domains: Optional[List[str]]=None, search_engine_kwargs:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BingAPI:
"""Search engine using the Bing API. See [Bing Web Search API](https://learn.microsoft.com/en-us/bing/search-apis/bing-web-search/overview) for more details."""
def __init__(self, api_key: str, top_k: Optional[int]=10, allowed_domains: Optional[List[str]]=None, search_engine_kwargs: Optional[Dic... | the_stack_v2_python_sparse | haystack/nodes/search_engine/providers.py | deepset-ai/haystack | train | 10,599 |
f2c70ea3c69e92565fe49480482c165d1334135d | [
"self.k = k\nself.h_train = None\nself.r_train = None\nself.bsk_label_train = None\nself.clf = None\nself.step = None",
"assert self.k is not None, 'k cannot be none before train'\nself.h_train = h_train.sign()\nself.r_train = r_train\nif isinstance(bsk_label_train, pd.DataFrame):\n bsk_label_train = bsk_label... | <|body_start_0|>
self.k = k
self.h_train = None
self.r_train = None
self.bsk_label_train = None
self.clf = None
self.step = None
<|end_body_0|>
<|body_start_1|>
assert self.k is not None, 'k cannot be none before train'
self.h_train = h_train.sign()
... | A knn prediction class | knn_Predictor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class knn_Predictor:
"""A knn prediction class"""
def __init__(self, k=None):
"""The constructor of the baseline predictor :param method: only Jaccard method is supported :param type: one of the two options ('Unnormalized', 'Normalized')"""
<|body_0|>
def fit(self, h_train, bs... | stack_v2_sparse_classes_36k_train_023094 | 5,928 | no_license | [
{
"docstring": "The constructor of the baseline predictor :param method: only Jaccard method is supported :param type: one of the two options ('Unnormalized', 'Normalized')",
"name": "__init__",
"signature": "def __init__(self, k=None)"
},
{
"docstring": "The train method of class :param h_train... | 4 | stack_v2_sparse_classes_30k_train_014081 | Implement the Python class `knn_Predictor` described below.
Class description:
A knn prediction class
Method signatures and docstrings:
- def __init__(self, k=None): The constructor of the baseline predictor :param method: only Jaccard method is supported :param type: one of the two options ('Unnormalized', 'Normaliz... | Implement the Python class `knn_Predictor` described below.
Class description:
A knn prediction class
Method signatures and docstrings:
- def __init__(self, k=None): The constructor of the baseline predictor :param method: only Jaccard method is supported :param type: one of the two options ('Unnormalized', 'Normaliz... | 7f9ef25bb9c50f996534ff9067da0d95ac3fdbd5 | <|skeleton|>
class knn_Predictor:
"""A knn prediction class"""
def __init__(self, k=None):
"""The constructor of the baseline predictor :param method: only Jaccard method is supported :param type: one of the two options ('Unnormalized', 'Normalized')"""
<|body_0|>
def fit(self, h_train, bs... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class knn_Predictor:
"""A knn prediction class"""
def __init__(self, k=None):
"""The constructor of the baseline predictor :param method: only Jaccard method is supported :param type: one of the two options ('Unnormalized', 'Normalized')"""
self.k = k
self.h_train = None
self.r_... | the_stack_v2_python_sparse | src/knn_prediction_2_step_cls.py | bigdatamatta/HyperGo | train | 0 |
95c7ff892616a98f8db001ca02f9a81d1d8c2b1f | [
"stack = set()\ndicts = {}\nstart = -1\nans = 0\nfor i, t in enumerate(tree):\n if len(dicts) < 2:\n if t not in dicts:\n stack.add(t)\n elif t not in dicts:\n min_key = [-1, float('inf')]\n for key in stack:\n if dicts[key] < min_key[1]:\n min_key = [... | <|body_start_0|>
stack = set()
dicts = {}
start = -1
ans = 0
for i, t in enumerate(tree):
if len(dicts) < 2:
if t not in dicts:
stack.add(t)
elif t not in dicts:
min_key = [-1, float('inf')]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def totalFruit(self, tree):
""":type tree: List[int] :rtype: int 296 ms"""
<|body_0|>
def totalFruit_1(self, tree):
"""180ms :param tree: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
stack = set()
dicts = {}
sta... | stack_v2_sparse_classes_36k_train_023095 | 2,829 | no_license | [
{
"docstring": ":type tree: List[int] :rtype: int 296 ms",
"name": "totalFruit",
"signature": "def totalFruit(self, tree)"
},
{
"docstring": "180ms :param tree: :return:",
"name": "totalFruit_1",
"signature": "def totalFruit_1(self, tree)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def totalFruit(self, tree): :type tree: List[int] :rtype: int 296 ms
- def totalFruit_1(self, tree): 180ms :param tree: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def totalFruit(self, tree): :type tree: List[int] :rtype: int 296 ms
- def totalFruit_1(self, tree): 180ms :param tree: :return:
<|skeleton|>
class Solution:
def totalFruit... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def totalFruit(self, tree):
""":type tree: List[int] :rtype: int 296 ms"""
<|body_0|>
def totalFruit_1(self, tree):
"""180ms :param tree: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def totalFruit(self, tree):
""":type tree: List[int] :rtype: int 296 ms"""
stack = set()
dicts = {}
start = -1
ans = 0
for i, t in enumerate(tree):
if len(dicts) < 2:
if t not in dicts:
stack.add(t)
... | the_stack_v2_python_sparse | FruitIntoBaskets_MID_904.py | 953250587/leetcode-python | train | 2 | |
ad0d27e392f0368fbf41bf4a4c80c9d7d7917a9c | [
"if not nums:\n return 0\nsums = [0] * len(nums)\nsums[0] = nums[0]\nres = sums[0]\nfor i in range(1, len(nums)):\n sums[i] = sums[i - 1] + nums[i] if sums[i - 1] > 0 else nums[i]\n res = max(sums[i], res)\nreturn res",
"localMaxSum, globalMaxSum = (nums[0], nums[0])\nfor i in range(1, len(nums)):\n l... | <|body_start_0|>
if not nums:
return 0
sums = [0] * len(nums)
sums[0] = nums[0]
res = sums[0]
for i in range(1, len(nums)):
sums[i] = sums[i - 1] + nums[i] if sums[i - 1] > 0 else nums[i]
res = max(sums[i], res)
return res
<|end_body_0|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maxSubArray2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return 0
su... | stack_v2_sparse_classes_36k_train_023096 | 1,509 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maxSubArray",
"signature": "def maxSubArray(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maxSubArray2",
"signature": "def maxSubArray2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_val_001099 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray(self, nums): :type nums: List[int] :rtype: int
- def maxSubArray2(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 maxSubArray(self, nums): :type nums: List[int] :rtype: int
- def maxSubArray2(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxSubArra... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maxSubArray2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
if not nums:
return 0
sums = [0] * len(nums)
sums[0] = nums[0]
res = sums[0]
for i in range(1, len(nums)):
sums[i] = sums[i - 1] + nums[i] if sums[i - 1] > 0 e... | the_stack_v2_python_sparse | M/MaximumSubarray.py | bssrdf/pyleet | train | 2 | |
975497e9f7e196eeb45d58a4bd67de43a61b831a | [
"window = sublime.active_window()\nif window.active_panel() == OutputPanelHandler.PANEL_NAME:\n window.run_command('hide_panel', {'panel': OutputPanelHandler.PANEL_NAME})",
"window = sublime.active_window()\nwindow.destroy_output_panel(OutputPanelHandler.PANEL_TAG)\npanel_view = window.create_output_panel(Outp... | <|body_start_0|>
window = sublime.active_window()
if window.active_panel() == OutputPanelHandler.PANEL_NAME:
window.run_command('hide_panel', {'panel': OutputPanelHandler.PANEL_NAME})
<|end_body_0|>
<|body_start_1|>
window = sublime.active_window()
window.destroy_output_pane... | Handle the output panel. | OutputPanelHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OutputPanelHandler:
"""Handle the output panel."""
def hide_panel():
"""Hide the output panel."""
<|body_0|>
def show(text):
"""Show the panel with text."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
window = sublime.active_window()
if... | stack_v2_sparse_classes_36k_train_023097 | 1,328 | permissive | [
{
"docstring": "Hide the output panel.",
"name": "hide_panel",
"signature": "def hide_panel()"
},
{
"docstring": "Show the panel with text.",
"name": "show",
"signature": "def show(text)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012361 | Implement the Python class `OutputPanelHandler` described below.
Class description:
Handle the output panel.
Method signatures and docstrings:
- def hide_panel(): Hide the output panel.
- def show(text): Show the panel with text. | Implement the Python class `OutputPanelHandler` described below.
Class description:
Handle the output panel.
Method signatures and docstrings:
- def hide_panel(): Hide the output panel.
- def show(text): Show the panel with text.
<|skeleton|>
class OutputPanelHandler:
"""Handle the output panel."""
def hide... | c2e8913052f4c9f11433f0a421fbbc4b78699fd6 | <|skeleton|>
class OutputPanelHandler:
"""Handle the output panel."""
def hide_panel():
"""Hide the output panel."""
<|body_0|>
def show(text):
"""Show the panel with text."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OutputPanelHandler:
"""Handle the output panel."""
def hide_panel():
"""Hide the output panel."""
window = sublime.active_window()
if window.active_panel() == OutputPanelHandler.PANEL_NAME:
window.run_command('hide_panel', {'panel': OutputPanelHandler.PANEL_NAME})
... | the_stack_v2_python_sparse | plugin/utils/output_panel_handler.py | niosus/EasyClangComplete | train | 677 |
bba310e00c1afdffef382cfdc4ce467497ec007c | [
"assert isinstance(X0, numpy.ndarray), 'X0 must be numpy array'\nassert X0.shape == (1, 3), 'X0 must be numpy (3,) array'\nsuper(CirclingParkController, self).__init__(self._circle, self._circle_accel, L, is_ned)\nself._X0 = X0\nself._R = R\nself._direction = numpy.sign(direction)",
"if self._is_ned:\n dx = se... | <|body_start_0|>
assert isinstance(X0, numpy.ndarray), 'X0 must be numpy array'
assert X0.shape == (1, 3), 'X0 must be numpy (3,) array'
super(CirclingParkController, self).__init__(self._circle, self._circle_accel, L, is_ned)
self._X0 = X0
self._R = R
self._direction = n... | A parameterized path controller that is pre-built to do circles | CirclingParkController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CirclingParkController:
"""A parameterized path controller that is pre-built to do circles"""
def __init__(self, X0, R, L, direction=1, is_ned=True):
"""Constructor Arguments: X0: the circle center point numpy (1,3) array (lla or ned depending on the argument is_ned) R: the circle ra... | stack_v2_sparse_classes_36k_train_023098 | 19,298 | permissive | [
{
"docstring": "Constructor Arguments: X0: the circle center point numpy (1,3) array (lla or ned depending on the argument is_ned) R: the circle radius (m) L: the lookahead distance on the path. (m) direction: optional, turn direction, sign of the yaw rate. defaults to positive turn rate is_ned: optional flag i... | 3 | stack_v2_sparse_classes_30k_train_012685 | Implement the Python class `CirclingParkController` described below.
Class description:
A parameterized path controller that is pre-built to do circles
Method signatures and docstrings:
- def __init__(self, X0, R, L, direction=1, is_ned=True): Constructor Arguments: X0: the circle center point numpy (1,3) array (lla ... | Implement the Python class `CirclingParkController` described below.
Class description:
A parameterized path controller that is pre-built to do circles
Method signatures and docstrings:
- def __init__(self, X0, R, L, direction=1, is_ned=True): Constructor Arguments: X0: the circle center point numpy (1,3) array (lla ... | 6827886916e36432ce1d806f0a78edef6c9270d9 | <|skeleton|>
class CirclingParkController:
"""A parameterized path controller that is pre-built to do circles"""
def __init__(self, X0, R, L, direction=1, is_ned=True):
"""Constructor Arguments: X0: the circle center point numpy (1,3) array (lla or ned depending on the argument is_ned) R: the circle ra... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CirclingParkController:
"""A parameterized path controller that is pre-built to do circles"""
def __init__(self, X0, R, L, direction=1, is_ned=True):
"""Constructor Arguments: X0: the circle center point numpy (1,3) array (lla or ned depending on the argument is_ned) R: the circle radius (m) L: t... | the_stack_v2_python_sparse | pybots/src/robot_control/path_following.py | aivian/robots | train | 0 |
417ee5ce1baff2951ff326296fd3ca72b746f0cd | [
"if len(signs) != 2:\n raise ValueError('Argument `signs` should be a tuple of two floats reflecting the sign for each channel.')\nfor sign in signs:\n if abs(sign) != 1:\n raise ValueError('Each sign should be either -1 or 1.')\nself.trap_calibration = trap_calibration\nself._signs = signs",
"if dow... | <|body_start_0|>
if len(signs) != 2:
raise ValueError('Argument `signs` should be a tuple of two floats reflecting the sign for each channel.')
for sign in signs:
if abs(sign) != 1:
raise ValueError('Each sign should be either -1 or 1.')
self.trap_calibrat... | Class to handle piezo tracking calibration Allows calculating piezo distance from trap position and correlated force data | PiezoTrackingCalibration | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PiezoTrackingCalibration:
"""Class to handle piezo tracking calibration Allows calculating piezo distance from trap position and correlated force data"""
def __init__(self, trap_calibration, signs=(1, -1)):
"""Set up piezo tracking calibration trap_calibration : DistanceCalibration C... | stack_v2_sparse_classes_36k_train_023099 | 8,607 | permissive | [
{
"docstring": "Set up piezo tracking calibration trap_calibration : DistanceCalibration Calibration from trap position to trap to trap distance. signs : tuple(float, float) Sign convention for forces (e.g. (1, -1) indicates that force2 is negative).",
"name": "__init__",
"signature": "def __init__(self... | 2 | null | Implement the Python class `PiezoTrackingCalibration` described below.
Class description:
Class to handle piezo tracking calibration Allows calculating piezo distance from trap position and correlated force data
Method signatures and docstrings:
- def __init__(self, trap_calibration, signs=(1, -1)): Set up piezo trac... | Implement the Python class `PiezoTrackingCalibration` described below.
Class description:
Class to handle piezo tracking calibration Allows calculating piezo distance from trap position and correlated force data
Method signatures and docstrings:
- def __init__(self, trap_calibration, signs=(1, -1)): Set up piezo trac... | 5b7331f23f261b968b9dada3ddea2378cb07ac4c | <|skeleton|>
class PiezoTrackingCalibration:
"""Class to handle piezo tracking calibration Allows calculating piezo distance from trap position and correlated force data"""
def __init__(self, trap_calibration, signs=(1, -1)):
"""Set up piezo tracking calibration trap_calibration : DistanceCalibration C... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PiezoTrackingCalibration:
"""Class to handle piezo tracking calibration Allows calculating piezo distance from trap position and correlated force data"""
def __init__(self, trap_calibration, signs=(1, -1)):
"""Set up piezo tracking calibration trap_calibration : DistanceCalibration Calibration fr... | the_stack_v2_python_sparse | lumicks/pylake/piezo_tracking/piezo_tracking.py | lumicks/pylake | train | 16 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.