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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4ab6acb45ce6e5de8d7016edb9fb88ff1de0e390 | [
"context = {'ir.ui.menu.full_list': True}\nmenus = self.with_context(context).search([])\ngroups = self.env.user.groups_id\nmenus = menus.filtered(lambda menu: not menu.groups_id or menu.groups_id & groups)\nfavorite_parent = menus.filtered(lambda r: r.name == 'Favorite')\nfavorite_conf = menus.filtered(lambda r: r... | <|body_start_0|>
context = {'ir.ui.menu.full_list': True}
menus = self.with_context(context).search([])
groups = self.env.user.groups_id
menus = menus.filtered(lambda menu: not menu.groups_id or menu.groups_id & groups)
favorite_parent = menus.filtered(lambda r: r.name == 'Favori... | ir_ui_menu | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ir_ui_menu:
def _visible_menu_ids(self, debug=False):
"""Return the ids of the menu items visible to the user."""
<|body_0|>
def load_menus(self, cr, uid, debug, context=None):
"""Loads all menu items (all applications and their sub-menus). :return: the menu root :rt... | stack_v2_sparse_classes_36k_train_005500 | 5,056 | no_license | [
{
"docstring": "Return the ids of the menu items visible to the user.",
"name": "_visible_menu_ids",
"signature": "def _visible_menu_ids(self, debug=False)"
},
{
"docstring": "Loads all menu items (all applications and their sub-menus). :return: the menu root :rtype: dict('children': menu_nodes)... | 2 | null | Implement the Python class `ir_ui_menu` described below.
Class description:
Implement the ir_ui_menu class.
Method signatures and docstrings:
- def _visible_menu_ids(self, debug=False): Return the ids of the menu items visible to the user.
- def load_menus(self, cr, uid, debug, context=None): Loads all menu items (al... | Implement the Python class `ir_ui_menu` described below.
Class description:
Implement the ir_ui_menu class.
Method signatures and docstrings:
- def _visible_menu_ids(self, debug=False): Return the ids of the menu items visible to the user.
- def load_menus(self, cr, uid, debug, context=None): Loads all menu items (al... | eb394e1f79ba1995da2dcd81adfdd511c22caff9 | <|skeleton|>
class ir_ui_menu:
def _visible_menu_ids(self, debug=False):
"""Return the ids of the menu items visible to the user."""
<|body_0|>
def load_menus(self, cr, uid, debug, context=None):
"""Loads all menu items (all applications and their sub-menus). :return: the menu root :rt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ir_ui_menu:
def _visible_menu_ids(self, debug=False):
"""Return the ids of the menu items visible to the user."""
context = {'ir.ui.menu.full_list': True}
menus = self.with_context(context).search([])
groups = self.env.user.groups_id
menus = menus.filtered(lambda menu: ... | the_stack_v2_python_sparse | OpenPROD/openprod-addons/favorite/ir_ui_menu.py | kazacube-mziouadi/ceci | train | 0 | |
a90e539c2706efb69424b6cce74bc0ff28e522ca | [
"if not configs_file:\n dir_path = os.path.dirname(os.path.realpath(__file__))\n configs_file = os.path.join(dir_path, 'my_bb_configs.ini')\nprint('Loading configs: ' + configs_file)",
"if io.is_file(f_configs) is False:\n warn.warn('configs (INI) file does not exist: ' + f_configs)\n return None",
... | <|body_start_0|>
if not configs_file:
dir_path = os.path.dirname(os.path.realpath(__file__))
configs_file = os.path.join(dir_path, 'my_bb_configs.ini')
print('Loading configs: ' + configs_file)
<|end_body_0|>
<|body_start_1|>
if io.is_file(f_configs) is False:
... | Simple class made-up of static methods for handling INI configuration files used in LOKI API. | Configurations | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Configurations:
"""Simple class made-up of static methods for handling INI configuration files used in LOKI API."""
def parse(configs_file):
"""Instantiates parser for INI (config) file :param cfconfigs_fileile: absolute path to config INI file :return: ConfigParser object with confi... | stack_v2_sparse_classes_36k_train_005501 | 6,802 | permissive | [
{
"docstring": "Instantiates parser for INI (config) file :param cfconfigs_fileile: absolute path to config INI file :return: ConfigParser object with configurations loaded",
"name": "parse",
"signature": "def parse(configs_file)"
},
{
"docstring": "Top-level function that reads & stores all (or... | 4 | stack_v2_sparse_classes_30k_train_014657 | Implement the Python class `Configurations` described below.
Class description:
Simple class made-up of static methods for handling INI configuration files used in LOKI API.
Method signatures and docstrings:
- def parse(configs_file): Instantiates parser for INI (config) file :param cfconfigs_fileile: absolute path t... | Implement the Python class `Configurations` described below.
Class description:
Simple class made-up of static methods for handling INI configuration files used in LOKI API.
Method signatures and docstrings:
- def parse(configs_file): Instantiates parser for INI (config) file :param cfconfigs_fileile: absolute path t... | bc07ba242ccaf762a55c80204d7da05d55847ec5 | <|skeleton|>
class Configurations:
"""Simple class made-up of static methods for handling INI configuration files used in LOKI API."""
def parse(configs_file):
"""Instantiates parser for INI (config) file :param cfconfigs_fileile: absolute path to config INI file :return: ConfigParser object with confi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Configurations:
"""Simple class made-up of static methods for handling INI configuration files used in LOKI API."""
def parse(configs_file):
"""Instantiates parser for INI (config) file :param cfconfigs_fileile: absolute path to config INI file :return: ConfigParser object with configurations loa... | the_stack_v2_python_sparse | src/fiwtools/utils/common.py | visionjo/FIW_KRT | train | 28 |
df5aae72c2b7cb7c3de4c2736d228c58523f3b9f | [
"self.eof_index = -1\nself.timeout_index = -1\nself._searches = []\nfor n, s in enumerate(patterns):\n if s is EOF:\n self.eof_index = n\n continue\n if s is TIMEOUT:\n self.timeout_index = n\n continue\n self._searches.append((n, s))",
"ss = list()\nfor n, s in self._searches... | <|body_start_0|>
self.eof_index = -1
self.timeout_index = -1
self._searches = []
for n, s in enumerate(patterns):
if s is EOF:
self.eof_index = n
continue
if s is TIMEOUT:
self.timeout_index = n
conti... | This is regular expression string search helper for the spawn.expect_any() method. This helper class is for powerful pattern matching. For speed, see the helper class, searcher_string. Attributes: eof_index - index of EOF, or -1 timeout_index - index of TIMEOUT, or -1 After a successful match by the search() method the... | searcher_re | [
"ISC",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-other-copyleft",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class searcher_re:
"""This is regular expression string search helper for the spawn.expect_any() method. This helper class is for powerful pattern matching. For speed, see the helper class, searcher_string. Attributes: eof_index - index of EOF, or -1 timeout_index - index of TIMEOUT, or -1 After a succ... | stack_v2_sparse_classes_36k_train_005502 | 13,827 | permissive | [
{
"docstring": "This creates an instance that searches for 'patterns' Where 'patterns' may be a list or other sequence of compiled regular expressions, or the EOF or TIMEOUT types.",
"name": "__init__",
"signature": "def __init__(self, patterns)"
},
{
"docstring": "This returns a human-readable ... | 3 | null | Implement the Python class `searcher_re` described below.
Class description:
This is regular expression string search helper for the spawn.expect_any() method. This helper class is for powerful pattern matching. For speed, see the helper class, searcher_string. Attributes: eof_index - index of EOF, or -1 timeout_index... | Implement the Python class `searcher_re` described below.
Class description:
This is regular expression string search helper for the spawn.expect_any() method. This helper class is for powerful pattern matching. For speed, see the helper class, searcher_string. Attributes: eof_index - index of EOF, or -1 timeout_index... | f5042e35b945aded77b23470ead62d7eacefde92 | <|skeleton|>
class searcher_re:
"""This is regular expression string search helper for the spawn.expect_any() method. This helper class is for powerful pattern matching. For speed, see the helper class, searcher_string. Attributes: eof_index - index of EOF, or -1 timeout_index - index of TIMEOUT, or -1 After a succ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class searcher_re:
"""This is regular expression string search helper for the spawn.expect_any() method. This helper class is for powerful pattern matching. For speed, see the helper class, searcher_string. Attributes: eof_index - index of EOF, or -1 timeout_index - index of TIMEOUT, or -1 After a successful match ... | the_stack_v2_python_sparse | contrib/python/pexpect/pexpect/expect.py | catboost/catboost | train | 8,012 |
8dfc3442c251ef8949ed8a70d83706a9437218d7 | [
"if n < 1:\n return []\nself.result = []\nself.cols = set()\nself.pie = set()\nself.na = set()\nself._dfs(n, 0, [])\nreturn self._generate_result(n)",
"if row >= n:\n self.result.append(cur_state)\n return\nfor col in range(n):\n if col in self.cols or row + col in self.pie or row - col in self.na:\n ... | <|body_start_0|>
if n < 1:
return []
self.result = []
self.cols = set()
self.pie = set()
self.na = set()
self._dfs(n, 0, [])
return self._generate_result(n)
<|end_body_0|>
<|body_start_1|>
if row >= n:
self.result.append(cur_state)... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def solveNQueens(self, n):
""":type n: int :rtype: List[List[str]]"""
<|body_0|>
def _dfs(self, n, row, cur_state):
"""迭代函数 :param n: n个皇后 :param row: 行数 :param cur_state: 当前情况下的皇后位置"""
<|body_1|>
def _generate_result(self, n):
"""将皇后位置... | stack_v2_sparse_classes_36k_train_005503 | 1,774 | no_license | [
{
"docstring": ":type n: int :rtype: List[List[str]]",
"name": "solveNQueens",
"signature": "def solveNQueens(self, n)"
},
{
"docstring": "迭代函数 :param n: n个皇后 :param row: 行数 :param cur_state: 当前情况下的皇后位置",
"name": "_dfs",
"signature": "def _dfs(self, n, row, cur_state)"
},
{
"docs... | 3 | stack_v2_sparse_classes_30k_train_000655 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solveNQueens(self, n): :type n: int :rtype: List[List[str]]
- def _dfs(self, n, row, cur_state): 迭代函数 :param n: n个皇后 :param row: 行数 :param cur_state: 当前情况下的皇后位置
- def _genera... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solveNQueens(self, n): :type n: int :rtype: List[List[str]]
- def _dfs(self, n, row, cur_state): 迭代函数 :param n: n个皇后 :param row: 行数 :param cur_state: 当前情况下的皇后位置
- def _genera... | a58e53715493688db0108611761946f7c4481ddd | <|skeleton|>
class Solution:
def solveNQueens(self, n):
""":type n: int :rtype: List[List[str]]"""
<|body_0|>
def _dfs(self, n, row, cur_state):
"""迭代函数 :param n: n个皇后 :param row: 行数 :param cur_state: 当前情况下的皇后位置"""
<|body_1|>
def _generate_result(self, n):
"""将皇后位置... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def solveNQueens(self, n):
""":type n: int :rtype: List[List[str]]"""
if n < 1:
return []
self.result = []
self.cols = set()
self.pie = set()
self.na = set()
self._dfs(n, 0, [])
return self._generate_result(n)
def _dfs(... | the_stack_v2_python_sparse | 51.py | yourSprite/LeetCodeExcercise | train | 0 | |
4d264961b45deaca2f4358166c582c83998cbac9 | [
"if name != '':\n self.is_unique = True\n self.name = name\nelse:\n self.is_unique = False\nself.name = name\nself.hp = hp\nself.speed = speed\nself.armor = armor\nself.power = power\nself.type_of_creature = type_of_creature\nself.status = {}\nself.magic = magic",
"print('I am a {}'.format(self.type_of_c... | <|body_start_0|>
if name != '':
self.is_unique = True
self.name = name
else:
self.is_unique = False
self.name = name
self.hp = hp
self.speed = speed
self.armor = armor
self.power = power
self.type_of_creature = type_of_c... | base class for all living things. All living things have: hp, speed, armor, power, type_of_creature and name | Living | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Living:
"""base class for all living things. All living things have: hp, speed, armor, power, type_of_creature and name"""
def __init__(self, hp, speed, armor, power, type_of_creature, name='', magic=0):
""":param hp: health :param speed: speed, used for attacks and turn order :param... | stack_v2_sparse_classes_36k_train_005504 | 1,201 | no_license | [
{
"docstring": ":param hp: health :param speed: speed, used for attacks and turn order :param armor: armor :param power: power, used for attacks :param type_of_creature: via the different classes :param name: a living thing has no name by default. If it has a name it is considered unique",
"name": "__init__... | 2 | stack_v2_sparse_classes_30k_val_000563 | Implement the Python class `Living` described below.
Class description:
base class for all living things. All living things have: hp, speed, armor, power, type_of_creature and name
Method signatures and docstrings:
- def __init__(self, hp, speed, armor, power, type_of_creature, name='', magic=0): :param hp: health :p... | Implement the Python class `Living` described below.
Class description:
base class for all living things. All living things have: hp, speed, armor, power, type_of_creature and name
Method signatures and docstrings:
- def __init__(self, hp, speed, armor, power, type_of_creature, name='', magic=0): :param hp: health :p... | 8a312a87ed00af616fa129e2ae789d2a38b45d26 | <|skeleton|>
class Living:
"""base class for all living things. All living things have: hp, speed, armor, power, type_of_creature and name"""
def __init__(self, hp, speed, armor, power, type_of_creature, name='', magic=0):
""":param hp: health :param speed: speed, used for attacks and turn order :param... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Living:
"""base class for all living things. All living things have: hp, speed, armor, power, type_of_creature and name"""
def __init__(self, hp, speed, armor, power, type_of_creature, name='', magic=0):
""":param hp: health :param speed: speed, used for attacks and turn order :param armor: armor... | the_stack_v2_python_sparse | living.py | DanielShalem1/real_dungeon | train | 0 |
988ba45c0579718547a9c8dbe43991f5b22ee55e | [
"l = 0\nr = len(nums) - 1\ni = 0\nwhile i <= r:\n if nums[i] == 2:\n nums[i], nums[r] = (nums[r], nums[i])\n r -= 1\n elif nums[i] == 0:\n nums[i], nums[l] = (nums[l], nums[i])\n l += 1\n i += 1\n else:\n i += 1\nreturn nums",
"def swap(i, j):\n nums[i], nums[... | <|body_start_0|>
l = 0
r = len(nums) - 1
i = 0
while i <= r:
if nums[i] == 2:
nums[i], nums[r] = (nums[r], nums[i])
r -= 1
elif nums[i] == 0:
nums[i], nums[l] = (nums[l], nums[i])
l += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortColors(self, nums):
"""04/25/2018 00:11"""
<|body_0|>
def sortColors(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l = 0
r = len(num... | stack_v2_sparse_classes_36k_train_005505 | 2,760 | no_license | [
{
"docstring": "04/25/2018 00:11",
"name": "sortColors",
"signature": "def sortColors(self, nums)"
},
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "sortColors",
"signature": "def sortColors(self, nums: List[int]) -> None"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums): 04/25/2018 00:11
- def sortColors(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead. | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums): 04/25/2018 00:11
- def sortColors(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
<|skeleton|>
class Solution:
... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def sortColors(self, nums):
"""04/25/2018 00:11"""
<|body_0|>
def sortColors(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sortColors(self, nums):
"""04/25/2018 00:11"""
l = 0
r = len(nums) - 1
i = 0
while i <= r:
if nums[i] == 2:
nums[i], nums[r] = (nums[r], nums[i])
r -= 1
elif nums[i] == 0:
nums[i], num... | the_stack_v2_python_sparse | leetcode/solved/75_Sort_Colors/solution.py | sungminoh/algorithms | train | 0 | |
707677be7827419225c21ce62c5f2a8a46e7e8d2 | [
"if not root:\n return ''\ns = ''\nq = collections.deque([root])\nwhile q:\n node = q.popleft()\n if node:\n s += str(node.val) + ' '\n q.append(node.left)\n q.append(node.right)\n else:\n s += 'n '\nreturn s",
"if not data:\n return None\nvals = data.split()\nroot = Tre... | <|body_start_0|>
if not root:
return ''
s = ''
q = collections.deque([root])
while q:
node = q.popleft()
if node:
s += str(node.val) + ' '
q.append(node.left)
q.append(node.right)
else:
... | Codec | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: 'TreeNode') -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> 'TreeNode':
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not roo... | stack_v2_sparse_classes_36k_train_005506 | 864 | permissive | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: 'TreeNode') -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> 'TreeNode'"
}
] | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'TreeNode') -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> 'TreeNode': Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'TreeNode') -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> 'TreeNode': Decodes your encoded data to tree.
<|skeleton|>
clas... | a27be41c174565d365cbfe785f0633f634a01b2a | <|skeleton|>
class Codec:
def serialize(self, root: 'TreeNode') -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> 'TreeNode':
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: 'TreeNode') -> str:
"""Encodes a tree to a single string."""
if not root:
return ''
s = ''
q = collections.deque([root])
while q:
node = q.popleft()
if node:
s += str(node.val) + ' '
... | the_stack_v2_python_sparse | solutions/0297. Serialize and Deserialize Binary Tree/0297.py | walkccc/LeetCode | train | 692 | |
6b7f082eedc43dfe4ed84789c27873d5074e5d41 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn BitLockerRemovableDrivePolicy()",
"from .bit_locker_encryption_method import BitLockerEncryptionMethod\nfrom .bit_locker_encryption_method import BitLockerEncryptionMethod\nfields: Dict[str, Callable[[Any], None]] = {'blockCrossOrganiz... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return BitLockerRemovableDrivePolicy()
<|end_body_0|>
<|body_start_1|>
from .bit_locker_encryption_method import BitLockerEncryptionMethod
from .bit_locker_encryption_method import BitLockerEnc... | BitLocker Removable Drive Policies. | BitLockerRemovableDrivePolicy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BitLockerRemovableDrivePolicy:
"""BitLocker Removable Drive Policies."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BitLockerRemovableDrivePolicy:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The p... | stack_v2_sparse_classes_36k_train_005507 | 3,902 | 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: BitLockerRemovableDrivePolicy",
"name": "create_from_discriminator_value",
"signature": "def create_from_dis... | 3 | null | Implement the Python class `BitLockerRemovableDrivePolicy` described below.
Class description:
BitLocker Removable Drive Policies.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BitLockerRemovableDrivePolicy: Creates a new instance of the appropriate c... | Implement the Python class `BitLockerRemovableDrivePolicy` described below.
Class description:
BitLocker Removable Drive Policies.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BitLockerRemovableDrivePolicy: Creates a new instance of the appropriate c... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class BitLockerRemovableDrivePolicy:
"""BitLocker Removable Drive Policies."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BitLockerRemovableDrivePolicy:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BitLockerRemovableDrivePolicy:
"""BitLocker Removable Drive Policies."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BitLockerRemovableDrivePolicy:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to ... | the_stack_v2_python_sparse | msgraph/generated/models/bit_locker_removable_drive_policy.py | microsoftgraph/msgraph-sdk-python | train | 135 |
c0198bd760324f7637a1012c4d35c3abdb8b40a5 | [
"if old in old2new:\n return old2new[old]\nnew = UndirectedGraphNode(old.label)\nnew.neighbors = [None] * len(old.neighbors)\nold2new[old] = new\nfor i, old_neighbor in enumerate(old.neighbors):\n new_neighbor = self._clone(old_neighbor, old2new)\n new.neighbors[i] = new_neighbor\nreturn new",
"if not no... | <|body_start_0|>
if old in old2new:
return old2new[old]
new = UndirectedGraphNode(old.label)
new.neighbors = [None] * len(old.neighbors)
old2new[old] = new
for i, old_neighbor in enumerate(old.neighbors):
new_neighbor = self._clone(old_neighbor, old2new)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _clone(self, old, old2new):
"""d maps old node to new neighbors"""
<|body_0|>
def cloneGraph(self, node):
""":type node: UndirectedGraphNode :rtype: UndirectedGraphNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if old in old2new:... | stack_v2_sparse_classes_36k_train_005508 | 938 | no_license | [
{
"docstring": "d maps old node to new neighbors",
"name": "_clone",
"signature": "def _clone(self, old, old2new)"
},
{
"docstring": ":type node: UndirectedGraphNode :rtype: UndirectedGraphNode",
"name": "cloneGraph",
"signature": "def cloneGraph(self, node)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018042 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _clone(self, old, old2new): d maps old node to new neighbors
- def cloneGraph(self, node): :type node: UndirectedGraphNode :rtype: UndirectedGraphNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _clone(self, old, old2new): d maps old node to new neighbors
- def cloneGraph(self, node): :type node: UndirectedGraphNode :rtype: UndirectedGraphNode
<|skeleton|>
class Sol... | 20580185c6f72f3c09a725168af48893156161f5 | <|skeleton|>
class Solution:
def _clone(self, old, old2new):
"""d maps old node to new neighbors"""
<|body_0|>
def cloneGraph(self, node):
""":type node: UndirectedGraphNode :rtype: UndirectedGraphNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def _clone(self, old, old2new):
"""d maps old node to new neighbors"""
if old in old2new:
return old2new[old]
new = UndirectedGraphNode(old.label)
new.neighbors = [None] * len(old.neighbors)
old2new[old] = new
for i, old_neighbor in enumera... | the_stack_v2_python_sparse | coding/00133-clone-graph/solution.py | misaka-10032/leetcode | train | 3 | |
51249bb68f88a9d608f062f090f8250f31e2c9b6 | [
"k = self.parameters['conv_kernel']\np = self.parameters['conv_pooling']\nw = self.parameters['conv_channel']\ndw = self.parameters['conv_channel_increment']\ncpp = self.parameters['conv_per_pooling']\nlayers = []\nfor j in range(cpp):\n if j == 0:\n conv = Convolution2D(round(w * dw ** i), k, strides=p, ... | <|body_start_0|>
k = self.parameters['conv_kernel']
p = self.parameters['conv_pooling']
w = self.parameters['conv_channel']
dw = self.parameters['conv_channel_increment']
cpp = self.parameters['conv_per_pooling']
layers = []
for j in range(cpp):
if j =... | StridedConvolutionalMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StridedConvolutionalMixin:
def encoder_block(self, i):
"""Extend this method for Residual Nets"""
<|body_0|>
def decoder_block(self, i, input_shape):
"""Extend this method for Residual Nets"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
k = self.pa... | stack_v2_sparse_classes_36k_train_005509 | 12,923 | no_license | [
{
"docstring": "Extend this method for Residual Nets",
"name": "encoder_block",
"signature": "def encoder_block(self, i)"
},
{
"docstring": "Extend this method for Residual Nets",
"name": "decoder_block",
"signature": "def decoder_block(self, i, input_shape)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007439 | Implement the Python class `StridedConvolutionalMixin` described below.
Class description:
Implement the StridedConvolutionalMixin class.
Method signatures and docstrings:
- def encoder_block(self, i): Extend this method for Residual Nets
- def decoder_block(self, i, input_shape): Extend this method for Residual Nets | Implement the Python class `StridedConvolutionalMixin` described below.
Class description:
Implement the StridedConvolutionalMixin class.
Method signatures and docstrings:
- def encoder_block(self, i): Extend this method for Residual Nets
- def decoder_block(self, i, input_shape): Extend this method for Residual Nets... | 75a2fc773de245b422a695b51fccaf17294da123 | <|skeleton|>
class StridedConvolutionalMixin:
def encoder_block(self, i):
"""Extend this method for Residual Nets"""
<|body_0|>
def decoder_block(self, i, input_shape):
"""Extend this method for Residual Nets"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StridedConvolutionalMixin:
def encoder_block(self, i):
"""Extend this method for Residual Nets"""
k = self.parameters['conv_kernel']
p = self.parameters['conv_pooling']
w = self.parameters['conv_channel']
dw = self.parameters['conv_channel_increment']
cpp = self... | the_stack_v2_python_sparse | latplan/mixins/encoder_decoder.py | guicho271828/latplan | train | 77 | |
ef79384b8e8f853316954ee3e363518f1d960cdd | [
"self.code = code\nself.amount = amount\nself.customer_id = customer_id\nself.customer = customer\nself.payment = payment\nself.metadata = metadata\nself.due_at = APIHelper.RFC3339DateTime(due_at) if due_at else None\nself.antifraud = antifraud\nself.order_id = order_id",
"if dictionary is None:\n return None\... | <|body_start_0|>
self.code = code
self.amount = amount
self.customer_id = customer_id
self.customer = customer
self.payment = payment
self.metadata = metadata
self.due_at = APIHelper.RFC3339DateTime(due_at) if due_at else None
self.antifraud = antifraud
... | Implementation of the 'Charges Request1' model. TODO: type model description here. Attributes: code (string): Code amount (int): The amount of the charge, in cents customer_id (string): The customer's id customer (Customer8): TODO: type description here. payment (Payment): TODO: type description here. metadata (dict<ob... | ChargesRequest1 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChargesRequest1:
"""Implementation of the 'Charges Request1' model. TODO: type model description here. Attributes: code (string): Code amount (int): The amount of the charge, in cents customer_id (string): The customer's id customer (Customer8): TODO: type description here. payment (Payment): TOD... | stack_v2_sparse_classes_36k_train_005510 | 3,779 | permissive | [
{
"docstring": "Constructor for the ChargesRequest1 class",
"name": "__init__",
"signature": "def __init__(self, code=None, amount=None, customer_id=None, customer=None, payment=None, metadata=None, antifraud=None, order_id=None, due_at=None)"
},
{
"docstring": "Creates an instance of this model... | 2 | null | Implement the Python class `ChargesRequest1` described below.
Class description:
Implementation of the 'Charges Request1' model. TODO: type model description here. Attributes: code (string): Code amount (int): The amount of the charge, in cents customer_id (string): The customer's id customer (Customer8): TODO: type d... | Implement the Python class `ChargesRequest1` described below.
Class description:
Implementation of the 'Charges Request1' model. TODO: type model description here. Attributes: code (string): Code amount (int): The amount of the charge, in cents customer_id (string): The customer's id customer (Customer8): TODO: type d... | 95c80c35dd57bb2a238faeaf30d1e3b4544d2298 | <|skeleton|>
class ChargesRequest1:
"""Implementation of the 'Charges Request1' model. TODO: type model description here. Attributes: code (string): Code amount (int): The amount of the charge, in cents customer_id (string): The customer's id customer (Customer8): TODO: type description here. payment (Payment): TOD... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChargesRequest1:
"""Implementation of the 'Charges Request1' model. TODO: type model description here. Attributes: code (string): Code amount (int): The amount of the charge, in cents customer_id (string): The customer's id customer (Customer8): TODO: type description here. payment (Payment): TODO: type descr... | the_stack_v2_python_sparse | mundiapi/models/charges_request_1.py | mundipagg/MundiAPI-PYTHON | train | 10 |
fa9ecb79eaa4d0c628c6e72fd3c6744e7d1b0eca | [
"super().__init__(visible=False)\nself.color('white')\nself.shape('square')\nself.setheading(90)\nself.shapesize(0.1, 1)\nself.speed(0)\nself.penup()\nself.pensize(3)\nself.game = game\nself.court = self.game.court\nself.court.onscreenclick(self.click)\nself.font_size = None",
"self.penup()\nself.goto(-self.court... | <|body_start_0|>
super().__init__(visible=False)
self.color('white')
self.shape('square')
self.setheading(90)
self.shapesize(0.1, 1)
self.speed(0)
self.penup()
self.pensize(3)
self.game = game
self.court = self.game.court
self.court... | Menu | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Menu:
def __init__(self, game):
"""Initialize game menu"""
<|body_0|>
def border(self):
"""Create court border"""
<|body_1|>
def play(self):
"""Create play button"""
<|body_2|>
def pause(self):
"""Create pause button"""
... | stack_v2_sparse_classes_36k_train_005511 | 21,836 | no_license | [
{
"docstring": "Initialize game menu",
"name": "__init__",
"signature": "def __init__(self, game)"
},
{
"docstring": "Create court border",
"name": "border",
"signature": "def border(self)"
},
{
"docstring": "Create play button",
"name": "play",
"signature": "def play(sel... | 5 | stack_v2_sparse_classes_30k_train_007562 | Implement the Python class `Menu` described below.
Class description:
Implement the Menu class.
Method signatures and docstrings:
- def __init__(self, game): Initialize game menu
- def border(self): Create court border
- def play(self): Create play button
- def pause(self): Create pause button
- def click(self, x, y)... | Implement the Python class `Menu` described below.
Class description:
Implement the Menu class.
Method signatures and docstrings:
- def __init__(self, game): Initialize game menu
- def border(self): Create court border
- def play(self): Create play button
- def pause(self): Create pause button
- def click(self, x, y)... | 982fb820257a425422305e076dbc4523f591dedb | <|skeleton|>
class Menu:
def __init__(self, game):
"""Initialize game menu"""
<|body_0|>
def border(self):
"""Create court border"""
<|body_1|>
def play(self):
"""Create play button"""
<|body_2|>
def pause(self):
"""Create pause button"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Menu:
def __init__(self, game):
"""Initialize game menu"""
super().__init__(visible=False)
self.color('white')
self.shape('square')
self.setheading(90)
self.shapesize(0.1, 1)
self.speed(0)
self.penup()
self.pensize(3)
self.game = ... | the_stack_v2_python_sparse | 07. Turtles/PongGame.py | pBogey/hello-world | train | 0 | |
ab1c02a75856d7dec84ab38f854f9d3ef21778ea | [
"self.timeData: TimeData = timeData\nself.sampleFreq: float = timeData.sampleFreq * 1.0\nself.chans: List = timeData.chans\nself.numSamples: int = timeData.numSamples\nself.decParams: DecimationParameters = decParams\nconfig = loadConfig()\nself.minSamples: int = config['Decimation']['minsamples']\nself.level: int ... | <|body_start_0|>
self.timeData: TimeData = timeData
self.sampleFreq: float = timeData.sampleFreq * 1.0
self.chans: List = timeData.chans
self.numSamples: int = timeData.numSamples
self.decParams: DecimationParameters = decParams
config = loadConfig()
self.minSampl... | Decimate time data Decimates time data by factors until the minimum number of required samples is reached. When a downsample factor is too large, downsampling is performed in multiple steps to maintain accuracy of result. Attributes ---------- timeData : TimeData timeData object to decimate sampleFreq : float Sampling ... | Decimator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decimator:
"""Decimate time data Decimates time data by factors until the minimum number of required samples is reached. When a downsample factor is too large, downsampling is performed in multiple steps to maintain accuracy of result. Attributes ---------- timeData : TimeData timeData object to ... | stack_v2_sparse_classes_36k_train_005512 | 6,514 | permissive | [
{
"docstring": "Initialise with timeData and decimation parameters Parameters ---------- timeData : TimeData The time data to decimate decParams : DecimationParams Decimation parameters for performing the decimation",
"name": "__init__",
"signature": "def __init__(self, timeData: TimeData, decParams: De... | 4 | null | Implement the Python class `Decimator` described below.
Class description:
Decimate time data Decimates time data by factors until the minimum number of required samples is reached. When a downsample factor is too large, downsampling is performed in multiple steps to maintain accuracy of result. Attributes ---------- ... | Implement the Python class `Decimator` described below.
Class description:
Decimate time data Decimates time data by factors until the minimum number of required samples is reached. When a downsample factor is too large, downsampling is performed in multiple steps to maintain accuracy of result. Attributes ---------- ... | a93040521fd6506929a59c363ee58b7ca073bac1 | <|skeleton|>
class Decimator:
"""Decimate time data Decimates time data by factors until the minimum number of required samples is reached. When a downsample factor is too large, downsampling is performed in multiple steps to maintain accuracy of result. Attributes ---------- timeData : TimeData timeData object to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Decimator:
"""Decimate time data Decimates time data by factors until the minimum number of required samples is reached. When a downsample factor is too large, downsampling is performed in multiple steps to maintain accuracy of result. Attributes ---------- timeData : TimeData timeData object to decimate samp... | the_stack_v2_python_sparse | resistics/decimate/decimator.py | Nishikinor/resistics | train | 0 |
4a1067d22edebd9066945a9626f60e6ec529575a | [
"super().__init__()\nself._subdags: List = []\nself.initial_layout = None\nself.gate = qiskit.circuit.library.CXGate\nself.decomposition = QuantumCircuit(2)\nif mode == 'ry':\n self.decomposition.ry(-np.pi / 2, 1)\n self.decomposition.cz(0, 1)\n self.decomposition.ry(np.pi / 2, 1)\nelse:\n self.decompos... | <|body_start_0|>
super().__init__()
self._subdags: List = []
self.initial_layout = None
self.gate = qiskit.circuit.library.CXGate
self.decomposition = QuantumCircuit(2)
if mode == 'ry':
self.decomposition.ry(-np.pi / 2, 1)
self.decomposition.cz(0, ... | Decompose CX into CZ and single qubit rotations | DecomposeCX | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecomposeCX:
"""Decompose CX into CZ and single qubit rotations"""
def __init__(self, mode: str='ry'):
"""Args:"""
<|body_0|>
def run(self, dag: DAGCircuit) -> DAGCircuit:
"""Run the Decompose pass on `dag`. Args: dag: input dag. Returns: output dag where ``CX`` ... | stack_v2_sparse_classes_36k_train_005513 | 14,382 | permissive | [
{
"docstring": "Args:",
"name": "__init__",
"signature": "def __init__(self, mode: str='ry')"
},
{
"docstring": "Run the Decompose pass on `dag`. Args: dag: input dag. Returns: output dag where ``CX`` was expanded.",
"name": "run",
"signature": "def run(self, dag: DAGCircuit) -> DAGCircu... | 2 | null | Implement the Python class `DecomposeCX` described below.
Class description:
Decompose CX into CZ and single qubit rotations
Method signatures and docstrings:
- def __init__(self, mode: str='ry'): Args:
- def run(self, dag: DAGCircuit) -> DAGCircuit: Run the Decompose pass on `dag`. Args: dag: input dag. Returns: out... | Implement the Python class `DecomposeCX` described below.
Class description:
Decompose CX into CZ and single qubit rotations
Method signatures and docstrings:
- def __init__(self, mode: str='ry'): Args:
- def run(self, dag: DAGCircuit) -> DAGCircuit: Run the Decompose pass on `dag`. Args: dag: input dag. Returns: out... | 208c9c53309e10484e9883d537b53282cb83a43d | <|skeleton|>
class DecomposeCX:
"""Decompose CX into CZ and single qubit rotations"""
def __init__(self, mode: str='ry'):
"""Args:"""
<|body_0|>
def run(self, dag: DAGCircuit) -> DAGCircuit:
"""Run the Decompose pass on `dag`. Args: dag: input dag. Returns: output dag where ``CX`` ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DecomposeCX:
"""Decompose CX into CZ and single qubit rotations"""
def __init__(self, mode: str='ry'):
"""Args:"""
super().__init__()
self._subdags: List = []
self.initial_layout = None
self.gate = qiskit.circuit.library.CXGate
self.decomposition = QuantumC... | the_stack_v2_python_sparse | src/qtt/qiskit/passes.py | QuTech-Delft/qtt | train | 58 |
1c1abc6534eabe9708d593c81417ce22b16bcb74 | [
"self.log = logging.getLogger('autopyfactory')\nself.parent = parent\nself.subdir = subdir\nself.path = os.path.join(parent.path, subdir)\nself.log.debug('SubDir: Object initialized for subdir %s.' % self.subdir)",
"self.log.debug('rm for subdir %s: Starting.' % self.subdir)\ndelta_days = self.parent.delta_t.days... | <|body_start_0|>
self.log = logging.getLogger('autopyfactory')
self.parent = parent
self.subdir = subdir
self.path = os.path.join(parent.path, subdir)
self.log.debug('SubDir: Object initialized for subdir %s.' % self.subdir)
<|end_body_0|>
<|body_start_1|>
self.log.debug... | class to handle each subdirectory. Subdirs look like <logDir>/2011-08-11/ANALY_BNL/ | SubDir | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubDir:
"""class to handle each subdirectory. Subdirs look like <logDir>/2011-08-11/ANALY_BNL/"""
def __init__(self, parent, subdir):
"""parent is a Dir object subdir is the APFQname"""
<|body_0|>
def rm(self, keepdays):
"""tries to delete a subdirectory, but onl... | stack_v2_sparse_classes_36k_train_005514 | 8,015 | permissive | [
{
"docstring": "parent is a Dir object subdir is the APFQname",
"name": "__init__",
"signature": "def __init__(self, parent, subdir)"
},
{
"docstring": "tries to delete a subdirectory, but only if the timing of the parent is older than what keepdays object has to say about it",
"name": "rm",... | 2 | null | Implement the Python class `SubDir` described below.
Class description:
class to handle each subdirectory. Subdirs look like <logDir>/2011-08-11/ANALY_BNL/
Method signatures and docstrings:
- def __init__(self, parent, subdir): parent is a Dir object subdir is the APFQname
- def rm(self, keepdays): tries to delete a ... | Implement the Python class `SubDir` described below.
Class description:
class to handle each subdirectory. Subdirs look like <logDir>/2011-08-11/ANALY_BNL/
Method signatures and docstrings:
- def __init__(self, parent, subdir): parent is a Dir object subdir is the APFQname
- def rm(self, keepdays): tries to delete a ... | 9d0d3890b38df2573045111182e45117ed232a46 | <|skeleton|>
class SubDir:
"""class to handle each subdirectory. Subdirs look like <logDir>/2011-08-11/ANALY_BNL/"""
def __init__(self, parent, subdir):
"""parent is a Dir object subdir is the APFQname"""
<|body_0|>
def rm(self, keepdays):
"""tries to delete a subdirectory, but onl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubDir:
"""class to handle each subdirectory. Subdirs look like <logDir>/2011-08-11/ANALY_BNL/"""
def __init__(self, parent, subdir):
"""parent is a Dir object subdir is the APFQname"""
self.log = logging.getLogger('autopyfactory')
self.parent = parent
self.subdir = subdir... | the_stack_v2_python_sparse | autopyfactory/cleanlogs.py | PanDAWMS/autopyfactory | train | 2 |
2604c08a7c02cbfa968b3f2e9c2fe4c6b2453306 | [
"try:\n self.sqlhandler = None\n self.args = {}\n if not utils.isUIDValid(self):\n self.write('need login')\n return\n utils.parseJsonRequestBody(self)\n self.classId = self.args['classId']\n self.practiceId = self.args['title']\n self.fullScore = self.args['fullScore']\n quest... | <|body_start_0|>
try:
self.sqlhandler = None
self.args = {}
if not utils.isUIDValid(self):
self.write('need login')
return
utils.parseJsonRequestBody(self)
self.classId = self.args['classId']
self.practiceId ... | TeaPushPracticeRequestHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeaPushPracticeRequestHandler:
def post(self):
"""将老师上传的题目存到数据库"""
<|body_0|>
def pushPractice(self):
"""从数据库读取学生信息"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
self.sqlhandler = None
self.args = {}
if not... | stack_v2_sparse_classes_36k_train_005515 | 2,796 | no_license | [
{
"docstring": "将老师上传的题目存到数据库",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "从数据库读取学生信息",
"name": "pushPractice",
"signature": "def pushPractice(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020218 | Implement the Python class `TeaPushPracticeRequestHandler` described below.
Class description:
Implement the TeaPushPracticeRequestHandler class.
Method signatures and docstrings:
- def post(self): 将老师上传的题目存到数据库
- def pushPractice(self): 从数据库读取学生信息 | Implement the Python class `TeaPushPracticeRequestHandler` described below.
Class description:
Implement the TeaPushPracticeRequestHandler class.
Method signatures and docstrings:
- def post(self): 将老师上传的题目存到数据库
- def pushPractice(self): 从数据库读取学生信息
<|skeleton|>
class TeaPushPracticeRequestHandler:
def post(self... | b28eb4163b02bd0a931653b94851592f2654b199 | <|skeleton|>
class TeaPushPracticeRequestHandler:
def post(self):
"""将老师上传的题目存到数据库"""
<|body_0|>
def pushPractice(self):
"""从数据库读取学生信息"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TeaPushPracticeRequestHandler:
def post(self):
"""将老师上传的题目存到数据库"""
try:
self.sqlhandler = None
self.args = {}
if not utils.isUIDValid(self):
self.write('need login')
return
utils.parseJsonRequestBody(self)
... | the_stack_v2_python_sparse | server/teacher/TeaPushPracticeRequestHandler.py | lyh-ADT/edu-app | train | 1 | |
ea9deb272d5ca1636b099675c39c47086e2dd3fa | [
"data = request.json\nif data is None:\n return self.json_message('No data received.', HTTP_BAD_REQUEST)\ntry:\n host = data['host']\n api_password = data['api_password']\nexcept KeyError:\n return self.json_message('No host or api_password received.', HTTP_BAD_REQUEST)\ntry:\n port = int(data['port'... | <|body_start_0|>
data = request.json
if data is None:
return self.json_message('No data received.', HTTP_BAD_REQUEST)
try:
host = data['host']
api_password = data['api_password']
except KeyError:
return self.json_message('No host or api_pas... | View to handle EventForwarding requests. | APIEventForwardingView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class APIEventForwardingView:
"""View to handle EventForwarding requests."""
def post(self, request):
"""Setup an event forwarder."""
<|body_0|>
def delete(self, request):
"""Remove event forwarer."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
data ... | stack_v2_sparse_classes_36k_train_005516 | 12,334 | permissive | [
{
"docstring": "Setup an event forwarder.",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "Remove event forwarer.",
"name": "delete",
"signature": "def delete(self, request)"
}
] | 2 | null | Implement the Python class `APIEventForwardingView` described below.
Class description:
View to handle EventForwarding requests.
Method signatures and docstrings:
- def post(self, request): Setup an event forwarder.
- def delete(self, request): Remove event forwarer. | Implement the Python class `APIEventForwardingView` described below.
Class description:
View to handle EventForwarding requests.
Method signatures and docstrings:
- def post(self, request): Setup an event forwarder.
- def delete(self, request): Remove event forwarer.
<|skeleton|>
class APIEventForwardingView:
""... | ca0e92aba83de2fd6cb1cc4d14f3b4471f17cf3d | <|skeleton|>
class APIEventForwardingView:
"""View to handle EventForwarding requests."""
def post(self, request):
"""Setup an event forwarder."""
<|body_0|>
def delete(self, request):
"""Remove event forwarer."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class APIEventForwardingView:
"""View to handle EventForwarding requests."""
def post(self, request):
"""Setup an event forwarder."""
data = request.json
if data is None:
return self.json_message('No data received.', HTTP_BAD_REQUEST)
try:
host = data['ho... | the_stack_v2_python_sparse | homeassistant/components/api.py | Smart-Torvy/torvy-home-assistant | train | 2 |
7dd174889e80af09bcfe84ad8e73b194da0444e6 | [
"self.root = root\nself.checksum = checksum\nif download:\n self._download()\nif not self._check_integrity():\n raise RuntimeError('Dataset not found or corrupted. ' + 'You can use download=True to download it')\nsuper().__init__(root, crs, res, transforms)",
"for prov_terr, md5 in zip(self.provinces_territ... | <|body_start_0|>
self.root = root
self.checksum = checksum
if download:
self._download()
if not self._check_integrity():
raise RuntimeError('Dataset not found or corrupted. ' + 'You can use download=True to download it')
super().__init__(root, crs, res, tr... | Canadian Building Footprints dataset. The `Canadian Building Footprints <https://github.com/Microsoft/CanadianBuildingFootprints>`__ dataset contains 11,842,186 computer generated building footprints in all Canadian provinces and territories in GeoJSON format. This data is freely available for download and use. | CanadianBuildingFootprints | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CanadianBuildingFootprints:
"""Canadian Building Footprints dataset. The `Canadian Building Footprints <https://github.com/Microsoft/CanadianBuildingFootprints>`__ dataset contains 11,842,186 computer generated building footprints in all Canadian provinces and territories in GeoJSON format. This ... | stack_v2_sparse_classes_36k_train_005517 | 5,763 | permissive | [
{
"docstring": "Initialize a new Dataset instance. Args: root: root directory where dataset can be found crs: :term:`coordinate reference system (CRS)` to warp to (defaults to the CRS of the first file found) res: resolution of the dataset in units of CRS transforms: a function/transform that takes an input sam... | 4 | null | Implement the Python class `CanadianBuildingFootprints` described below.
Class description:
Canadian Building Footprints dataset. The `Canadian Building Footprints <https://github.com/Microsoft/CanadianBuildingFootprints>`__ dataset contains 11,842,186 computer generated building footprints in all Canadian provinces a... | Implement the Python class `CanadianBuildingFootprints` described below.
Class description:
Canadian Building Footprints dataset. The `Canadian Building Footprints <https://github.com/Microsoft/CanadianBuildingFootprints>`__ dataset contains 11,842,186 computer generated building footprints in all Canadian provinces a... | 29985861614b3b93f9ef5389469ebb98570de7dd | <|skeleton|>
class CanadianBuildingFootprints:
"""Canadian Building Footprints dataset. The `Canadian Building Footprints <https://github.com/Microsoft/CanadianBuildingFootprints>`__ dataset contains 11,842,186 computer generated building footprints in all Canadian provinces and territories in GeoJSON format. This ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CanadianBuildingFootprints:
"""Canadian Building Footprints dataset. The `Canadian Building Footprints <https://github.com/Microsoft/CanadianBuildingFootprints>`__ dataset contains 11,842,186 computer generated building footprints in all Canadian provinces and territories in GeoJSON format. This data is freel... | the_stack_v2_python_sparse | torchgeo/datasets/cbf.py | microsoft/torchgeo | train | 1,724 |
0b69c78e9e1cd1ddb16a5401312b818a1e5a4fc4 | [
"super().__init__(coordinator, serial)\nself._attr_unique_id = f'{serial}_{SELECT_TYPE.key}'\nself.entity_description = SELECT_TYPE",
"sound_mode_value = getattr(SoundMode, self.data[self.entity_description.key]).value\nif sound_mode_value in [0, 1, 2]:\n return self.options[sound_mode_value]\nreturn None",
... | <|body_start_0|>
super().__init__(coordinator, serial)
self._attr_unique_id = f'{serial}_{SELECT_TYPE.key}'
self.entity_description = SELECT_TYPE
<|end_body_0|>
<|body_start_1|>
sound_mode_value = getattr(SoundMode, self.data[self.entity_description.key]).value
if sound_mode_val... | Representation of a EZVIZ select entity. | EzvizSelect | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EzvizSelect:
"""Representation of a EZVIZ select entity."""
def __init__(self, coordinator: EzvizDataUpdateCoordinator, serial: str) -> None:
"""Initialize the sensor."""
<|body_0|>
def current_option(self) -> str | None:
"""Return the selected entity option to r... | stack_v2_sparse_classes_36k_train_005518 | 3,026 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, coordinator: EzvizDataUpdateCoordinator, serial: str) -> None"
},
{
"docstring": "Return the selected entity option to represent the entity state.",
"name": "current_option",
"signature": "def c... | 3 | null | Implement the Python class `EzvizSelect` described below.
Class description:
Representation of a EZVIZ select entity.
Method signatures and docstrings:
- def __init__(self, coordinator: EzvizDataUpdateCoordinator, serial: str) -> None: Initialize the sensor.
- def current_option(self) -> str | None: Return the select... | Implement the Python class `EzvizSelect` described below.
Class description:
Representation of a EZVIZ select entity.
Method signatures and docstrings:
- def __init__(self, coordinator: EzvizDataUpdateCoordinator, serial: str) -> None: Initialize the sensor.
- def current_option(self) -> str | None: Return the select... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class EzvizSelect:
"""Representation of a EZVIZ select entity."""
def __init__(self, coordinator: EzvizDataUpdateCoordinator, serial: str) -> None:
"""Initialize the sensor."""
<|body_0|>
def current_option(self) -> str | None:
"""Return the selected entity option to r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EzvizSelect:
"""Representation of a EZVIZ select entity."""
def __init__(self, coordinator: EzvizDataUpdateCoordinator, serial: str) -> None:
"""Initialize the sensor."""
super().__init__(coordinator, serial)
self._attr_unique_id = f'{serial}_{SELECT_TYPE.key}'
self.entity... | the_stack_v2_python_sparse | homeassistant/components/ezviz/select.py | home-assistant/core | train | 35,501 |
139a67be94703b5979e587a828b8ce862535e6a2 | [
"if scipy.__version__ == '0.14.0':\n return self._fftconvolve_14(in1, in2, int2_fft, mode)\nelse:\n return self._fftconvolve_18(in1, in2, int2_fft, mode)",
"in1 = signaltools.asarray(in1)\nin2 = signaltools.asarray(in2)\nif in1.ndim == in2.ndim == 0:\n return in1 * in2\nelif not in1.ndim == in2.ndim:\n ... | <|body_start_0|>
if scipy.__version__ == '0.14.0':
return self._fftconvolve_14(in1, in2, int2_fft, mode)
else:
return self._fftconvolve_18(in1, in2, int2_fft, mode)
<|end_body_0|>
<|body_start_1|>
in1 = signaltools.asarray(in1)
in2 = signaltools.asarray(in2)
... | fft convolution routines optimized for different scipy versions | FFTConvolve | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FFTConvolve:
"""fft convolution routines optimized for different scipy versions"""
def fftconvolve(self, in1, in2, int2_fft, mode='same'):
""":param in1: :param in2: :param int2_fft: :param mode: :return:"""
<|body_0|>
def _fftconvolve_18(self, in1, in2, int2_fft, mode='... | stack_v2_sparse_classes_36k_train_005519 | 5,437 | permissive | [
{
"docstring": ":param in1: :param in2: :param int2_fft: :param mode: :return:",
"name": "fftconvolve",
"signature": "def fftconvolve(self, in1, in2, int2_fft, mode='same')"
},
{
"docstring": "scipy routine scipy.signal.fftconvolve with kernel already fourier transformed",
"name": "_fftconvo... | 6 | stack_v2_sparse_classes_30k_train_007094 | Implement the Python class `FFTConvolve` described below.
Class description:
fft convolution routines optimized for different scipy versions
Method signatures and docstrings:
- def fftconvolve(self, in1, in2, int2_fft, mode='same'): :param in1: :param in2: :param int2_fft: :param mode: :return:
- def _fftconvolve_18(... | Implement the Python class `FFTConvolve` described below.
Class description:
fft convolution routines optimized for different scipy versions
Method signatures and docstrings:
- def fftconvolve(self, in1, in2, int2_fft, mode='same'): :param in1: :param in2: :param int2_fft: :param mode: :return:
- def _fftconvolve_18(... | d2223705bc44d07575a5e93291375ab8e69ebfa8 | <|skeleton|>
class FFTConvolve:
"""fft convolution routines optimized for different scipy versions"""
def fftconvolve(self, in1, in2, int2_fft, mode='same'):
""":param in1: :param in2: :param int2_fft: :param mode: :return:"""
<|body_0|>
def _fftconvolve_18(self, in1, in2, int2_fft, mode='... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FFTConvolve:
"""fft convolution routines optimized for different scipy versions"""
def fftconvolve(self, in1, in2, int2_fft, mode='same'):
""":param in1: :param in2: :param int2_fft: :param mode: :return:"""
if scipy.__version__ == '0.14.0':
return self._fftconvolve_14(in1, in... | the_stack_v2_python_sparse | astrofunc/fft_convolve.py | sibirrer/astrofunc | train | 0 |
31e5f26313cbaac7212a79ef975ccb2d1a45e6fc | [
"if 'expr' in kwargs:\n raise ValueError(\"ObjectiveList does not accept the 'expr' keyword\")\n_rule = kwargs.pop('rule', None)\nself._starting_index = kwargs.pop('starting_index', 1)\nargs = (Set(dimen=1),)\nsuper().__init__(*args, **kwargs)\nself.rule = Initializer(_rule, allow_generators=True)\nif self.rule ... | <|body_start_0|>
if 'expr' in kwargs:
raise ValueError("ObjectiveList does not accept the 'expr' keyword")
_rule = kwargs.pop('rule', None)
self._starting_index = kwargs.pop('starting_index', 1)
args = (Set(dimen=1),)
super().__init__(*args, **kwargs)
self.rul... | An objective component that represents a list of objectives. Objectives can be indexed by their index, but when they are added an index value is not specified. | ObjectiveList | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectiveList:
"""An objective component that represents a list of objectives. Objectives can be indexed by their index, but when they are added an index value is not specified."""
def __init__(self, **kwargs):
"""Constructor"""
<|body_0|>
def construct(self, data=None):... | stack_v2_sparse_classes_36k_train_005520 | 20,043 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Construct the expression(s) for this objective.",
"name": "construct",
"signature": "def construct(self, data=None)"
},
{
"docstring": "Add an objective to the list.",... | 3 | null | Implement the Python class `ObjectiveList` described below.
Class description:
An objective component that represents a list of objectives. Objectives can be indexed by their index, but when they are added an index value is not specified.
Method signatures and docstrings:
- def __init__(self, **kwargs): Constructor
-... | Implement the Python class `ObjectiveList` described below.
Class description:
An objective component that represents a list of objectives. Objectives can be indexed by their index, but when they are added an index value is not specified.
Method signatures and docstrings:
- def __init__(self, **kwargs): Constructor
-... | 05ed25d76d244d983a3aee3ebc84545b276688a1 | <|skeleton|>
class ObjectiveList:
"""An objective component that represents a list of objectives. Objectives can be indexed by their index, but when they are added an index value is not specified."""
def __init__(self, **kwargs):
"""Constructor"""
<|body_0|>
def construct(self, data=None):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObjectiveList:
"""An objective component that represents a list of objectives. Objectives can be indexed by their index, but when they are added an index value is not specified."""
def __init__(self, **kwargs):
"""Constructor"""
if 'expr' in kwargs:
raise ValueError("Objective... | the_stack_v2_python_sparse | pyomo/core/base/objective.py | mrmundt/pyomo | train | 2 |
7a76768f600a22465cfc08608bbc7dee71a9176d | [
"query_result = {}\nquerier = wt_uu.CreateGenericWebTestQuerier()\nself.assertEqual(querier._GetRelevantExpectationFilesForQueryResult(query_result), [])",
"query_result = {'expectation_files': ['/posix/path', '/c:/windows/path']}\nquerier = wt_uu.CreateGenericWebTestQuerier()\nself.assertEqual(querier._GetReleva... | <|body_start_0|>
query_result = {}
querier = wt_uu.CreateGenericWebTestQuerier()
self.assertEqual(querier._GetRelevantExpectationFilesForQueryResult(query_result), [])
<|end_body_0|>
<|body_start_1|>
query_result = {'expectation_files': ['/posix/path', '/c:/windows/path']}
queri... | GetRelevantExpectationFilesForQueryResultUnittest | [
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetRelevantExpectationFilesForQueryResultUnittest:
def testNoFiles(self) -> None:
"""Tests that no reported expectation files are handled properly."""
<|body_0|>
def testAbsolutePath(self) -> None:
"""Tests that absolute paths are ignored."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_005521 | 21,966 | permissive | [
{
"docstring": "Tests that no reported expectation files are handled properly.",
"name": "testNoFiles",
"signature": "def testNoFiles(self) -> None"
},
{
"docstring": "Tests that absolute paths are ignored.",
"name": "testAbsolutePath",
"signature": "def testAbsolutePath(self) -> None"
... | 3 | null | Implement the Python class `GetRelevantExpectationFilesForQueryResultUnittest` described below.
Class description:
Implement the GetRelevantExpectationFilesForQueryResultUnittest class.
Method signatures and docstrings:
- def testNoFiles(self) -> None: Tests that no reported expectation files are handled properly.
- ... | Implement the Python class `GetRelevantExpectationFilesForQueryResultUnittest` described below.
Class description:
Implement the GetRelevantExpectationFilesForQueryResultUnittest class.
Method signatures and docstrings:
- def testNoFiles(self) -> None: Tests that no reported expectation files are handled properly.
- ... | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | <|skeleton|>
class GetRelevantExpectationFilesForQueryResultUnittest:
def testNoFiles(self) -> None:
"""Tests that no reported expectation files are handled properly."""
<|body_0|>
def testAbsolutePath(self) -> None:
"""Tests that absolute paths are ignored."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetRelevantExpectationFilesForQueryResultUnittest:
def testNoFiles(self) -> None:
"""Tests that no reported expectation files are handled properly."""
query_result = {}
querier = wt_uu.CreateGenericWebTestQuerier()
self.assertEqual(querier._GetRelevantExpectationFilesForQueryRe... | the_stack_v2_python_sparse | third_party/blink/tools/blinkpy/web_tests/stale_expectation_removal/queries_unittest.py | chromium/chromium | train | 17,408 | |
3b9bf33bc548d2ae18ccc14bc8cd26b8692ba8c8 | [
"GINConv.global_count += 1\nself.name = name if name else 'GIN_{}'.format(GINConv.global_count)\nself.nn = sequential_nn\nself.eps = eps\nself.input_channel_size = input_channels\nself.output_channel_size = output_channels\nself.num_nodes = num_nodes\nself.num_edges = num_edges",
"eps = lbann.Constant(value=1 + s... | <|body_start_0|>
GINConv.global_count += 1
self.name = name if name else 'GIN_{}'.format(GINConv.global_count)
self.nn = sequential_nn
self.eps = eps
self.input_channel_size = input_channels
self.output_channel_size = output_channels
self.num_nodes = num_nodes
... | Details of the kernel is available in: https://arxiv.org/abs/1810.00826 | GINConv | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GINConv:
"""Details of the kernel is available in: https://arxiv.org/abs/1810.00826"""
def __init__(self, sequential_nn, input_channels, output_channels, num_nodes, num_edges, eps=1e-06, name=None):
"""Initialize graph kernel as described in Graph Isomorphism Network. Args: sequentia... | stack_v2_sparse_classes_36k_train_005522 | 3,233 | permissive | [
{
"docstring": "Initialize graph kernel as described in Graph Isomorphism Network. Args: sequential_nn ([Module] or (Module)): A list or tuple of layer modules to be used input_channels (int): The size of the input node features output_channels (int): The output size of the node features num_nodes (int): Number... | 2 | stack_v2_sparse_classes_30k_train_008045 | Implement the Python class `GINConv` described below.
Class description:
Details of the kernel is available in: https://arxiv.org/abs/1810.00826
Method signatures and docstrings:
- def __init__(self, sequential_nn, input_channels, output_channels, num_nodes, num_edges, eps=1e-06, name=None): Initialize graph kernel a... | Implement the Python class `GINConv` described below.
Class description:
Details of the kernel is available in: https://arxiv.org/abs/1810.00826
Method signatures and docstrings:
- def __init__(self, sequential_nn, input_channels, output_channels, num_nodes, num_edges, eps=1e-06, name=None): Initialize graph kernel a... | e8cf85eed2acbd3383892bf7cb2d88b44c194f4f | <|skeleton|>
class GINConv:
"""Details of the kernel is available in: https://arxiv.org/abs/1810.00826"""
def __init__(self, sequential_nn, input_channels, output_channels, num_nodes, num_edges, eps=1e-06, name=None):
"""Initialize graph kernel as described in Graph Isomorphism Network. Args: sequentia... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GINConv:
"""Details of the kernel is available in: https://arxiv.org/abs/1810.00826"""
def __init__(self, sequential_nn, input_channels, output_channels, num_nodes, num_edges, eps=1e-06, name=None):
"""Initialize graph kernel as described in Graph Isomorphism Network. Args: sequential_nn ([Module... | the_stack_v2_python_sparse | python/lbann/modules/graph/sparse/GINConv.py | LLNL/lbann | train | 225 |
7217847836d8fea86df27c06c7dfa923abecadbe | [
"self.zeroth_coefficient = zeroth_coefficient\nself.zeroth_signal_scale = zeroth_signal_scale\nsuper().__init__(inner_coefficient=inner_coefficient, outer_coefficient=outer_coefficient, signal_scale=signal_scale)",
"regularization_weights = self.regularization_weights_from(linear_obj=linear_obj)\npix_sub_weights_... | <|body_start_0|>
self.zeroth_coefficient = zeroth_coefficient
self.zeroth_signal_scale = zeroth_signal_scale
super().__init__(inner_coefficient=inner_coefficient, outer_coefficient=outer_coefficient, signal_scale=signal_scale)
<|end_body_0|>
<|body_start_1|>
regularization_weights = sel... | AdaptiveBrightnessSplitZeroth | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdaptiveBrightnessSplitZeroth:
def __init__(self, zeroth_coefficient: float=1.0, zeroth_signal_scale: float=1.0, inner_coefficient: float=1.0, outer_coefficient: float=1.0, signal_scale: float=1.0):
"""An adaptive regularization scheme which splits every source pixel into a cross of four... | stack_v2_sparse_classes_36k_train_005523 | 5,208 | permissive | [
{
"docstring": "An adaptive regularization scheme which splits every source pixel into a cross of four regularization points (regularization is described in the `Regularization` class above) and interpolates to these points in order to apply smoothing on the solution of an `Inversion`. The size of this cross is... | 2 | stack_v2_sparse_classes_30k_train_007604 | Implement the Python class `AdaptiveBrightnessSplitZeroth` described below.
Class description:
Implement the AdaptiveBrightnessSplitZeroth class.
Method signatures and docstrings:
- def __init__(self, zeroth_coefficient: float=1.0, zeroth_signal_scale: float=1.0, inner_coefficient: float=1.0, outer_coefficient: float... | Implement the Python class `AdaptiveBrightnessSplitZeroth` described below.
Class description:
Implement the AdaptiveBrightnessSplitZeroth class.
Method signatures and docstrings:
- def __init__(self, zeroth_coefficient: float=1.0, zeroth_signal_scale: float=1.0, inner_coefficient: float=1.0, outer_coefficient: float... | 6639dd86d21ea28e942155753ec556752735b4e4 | <|skeleton|>
class AdaptiveBrightnessSplitZeroth:
def __init__(self, zeroth_coefficient: float=1.0, zeroth_signal_scale: float=1.0, inner_coefficient: float=1.0, outer_coefficient: float=1.0, signal_scale: float=1.0):
"""An adaptive regularization scheme which splits every source pixel into a cross of four... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdaptiveBrightnessSplitZeroth:
def __init__(self, zeroth_coefficient: float=1.0, zeroth_signal_scale: float=1.0, inner_coefficient: float=1.0, outer_coefficient: float=1.0, signal_scale: float=1.0):
"""An adaptive regularization scheme which splits every source pixel into a cross of four regularizatio... | the_stack_v2_python_sparse | autoarray/inversion/regularization/adaptive_brightness_split_zeroth.py | Jammy2211/PyAutoArray | train | 6 | |
b5692fb5126b65de5010d6a5108908db7877eb19 | [
"self.resolve = resolve\nself.args = args\nself.kwargs = kwargs\nif factory is not None:\n self.set_default_value_mode(DefaultValue.CallObject, factory)\nelif args is not None or kwargs is not None:\n mode = DefaultValue.MemberMethod_Object\n self.set_default_value_mode(mode, 'default')\nelif optional is F... | <|body_start_0|>
self.resolve = resolve
self.args = args
self.kwargs = kwargs
if factory is not None:
self.set_default_value_mode(DefaultValue.CallObject, factory)
elif args is not None or kwargs is not None:
mode = DefaultValue.MemberMethod_Object
... | An Instance which delays resolving the type definition. The first time the value is accessed or modified, the type will be resolved and the forward instance will behave identically to a normal instance. | ForwardInstance | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ForwardInstance:
"""An Instance which delays resolving the type definition. The first time the value is accessed or modified, the type will be resolved and the forward instance will behave identically to a normal instance."""
def __init__(self, resolve, args=None, kwargs=None, *, factory=Non... | stack_v2_sparse_classes_36k_train_005524 | 7,418 | permissive | [
{
"docstring": "Initialize a ForwardInstance. resolve : callable A callable which takes no arguments and returns the type or tuple of types to use for validating the values. args : tuple, optional If 'factory' is None, then 'resolve' will return a callable type and these arguments will be passed to the construc... | 4 | null | Implement the Python class `ForwardInstance` described below.
Class description:
An Instance which delays resolving the type definition. The first time the value is accessed or modified, the type will be resolved and the forward instance will behave identically to a normal instance.
Method signatures and docstrings:
... | Implement the Python class `ForwardInstance` described below.
Class description:
An Instance which delays resolving the type definition. The first time the value is accessed or modified, the type will be resolved and the forward instance will behave identically to a normal instance.
Method signatures and docstrings:
... | 761a52821d8c77b5718216256963682d11599c1e | <|skeleton|>
class ForwardInstance:
"""An Instance which delays resolving the type definition. The first time the value is accessed or modified, the type will be resolved and the forward instance will behave identically to a normal instance."""
def __init__(self, resolve, args=None, kwargs=None, *, factory=Non... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ForwardInstance:
"""An Instance which delays resolving the type definition. The first time the value is accessed or modified, the type will be resolved and the forward instance will behave identically to a normal instance."""
def __init__(self, resolve, args=None, kwargs=None, *, factory=None, optional=N... | the_stack_v2_python_sparse | atom/instance.py | nucleic/atom | train | 251 |
da86f1464f8ebb39e2d076e0259ec3a609b5c09d | [
"self.num += 1\nif self.opt.tofile or not self.opt.notitle:\n page_fmt = Formatter(page, self.opt.outputlang)\n self.output_list.append(page_fmt.output(num=self.num, fmt=self.opt.format))\nif self.opt['get']:\n try:\n pywikibot.stdout(page.text)\n except Error as err:\n pywikibot.error(err... | <|body_start_0|>
self.num += 1
if self.opt.tofile or not self.opt.notitle:
page_fmt = Formatter(page, self.opt.outputlang)
self.output_list.append(page_fmt.output(num=self.num, fmt=self.opt.format))
if self.opt['get']:
try:
pywikibot.stdout(pag... | Print a list of pages. | ListPagesBot | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListPagesBot:
"""Print a list of pages."""
def treat(self, page) -> None:
"""Process one page and add it to the `output_list`."""
<|body_0|>
def setup(self) -> None:
"""Initialize `output_list` and `num` and adjust base directory."""
<|body_1|>
def t... | stack_v2_sparse_classes_36k_train_005525 | 11,735 | permissive | [
{
"docstring": "Process one page and add it to the `output_list`.",
"name": "treat",
"signature": "def treat(self, page) -> None"
},
{
"docstring": "Initialize `output_list` and `num` and adjust base directory.",
"name": "setup",
"signature": "def setup(self) -> None"
},
{
"docst... | 3 | null | Implement the Python class `ListPagesBot` described below.
Class description:
Print a list of pages.
Method signatures and docstrings:
- def treat(self, page) -> None: Process one page and add it to the `output_list`.
- def setup(self) -> None: Initialize `output_list` and `num` and adjust base directory.
- def teard... | Implement the Python class `ListPagesBot` described below.
Class description:
Print a list of pages.
Method signatures and docstrings:
- def treat(self, page) -> None: Process one page and add it to the `output_list`.
- def setup(self) -> None: Initialize `output_list` and `num` and adjust base directory.
- def teard... | 5c01e6bfcd328bc6eae643e661f1a0ae57612808 | <|skeleton|>
class ListPagesBot:
"""Print a list of pages."""
def treat(self, page) -> None:
"""Process one page and add it to the `output_list`."""
<|body_0|>
def setup(self) -> None:
"""Initialize `output_list` and `num` and adjust base directory."""
<|body_1|>
def t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListPagesBot:
"""Print a list of pages."""
def treat(self, page) -> None:
"""Process one page and add it to the `output_list`."""
self.num += 1
if self.opt.tofile or not self.opt.notitle:
page_fmt = Formatter(page, self.opt.outputlang)
self.output_list.appe... | the_stack_v2_python_sparse | scripts/listpages.py | wikimedia/pywikibot | train | 432 |
93b3eae173a8cc589faea3e7007c8d4cba236de5 | [
"enc_hex = Encoder.encode_hex(bssid, psk)\nenc_freq = Encoder.encode_frequencies(enc_hex)\nreturn enc_freq",
"bssid = bssid.lower().strip()\npsk = psk.strip()\nmain = MainActivity()\nencoder = DataEncoder()\nshort_bssid = main._to_mac_address(bssid)\nmac = main._gen_mac_bytes(short_bssid)\nencoded = encoder.encod... | <|body_start_0|>
enc_hex = Encoder.encode_hex(bssid, psk)
enc_freq = Encoder.encode_frequencies(enc_hex)
return enc_freq
<|end_body_0|>
<|body_start_1|>
bssid = bssid.lower().strip()
psk = psk.strip()
main = MainActivity()
encoder = DataEncoder()
short_bs... | Essentially a minimalist wrapper for ..voice.encoder.DataEncoder.DataEncoder Utilising: ..voice.MainActivity.MainActivity ..voice.encoder.VoicePlayer.VoicePlayer | Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
"""Essentially a minimalist wrapper for ..voice.encoder.DataEncoder.DataEncoder Utilising: ..voice.MainActivity.MainActivity ..voice.encoder.VoicePlayer.VoicePlayer"""
def encode(bssid, psk):
"""Shortcut for: Encoder.encode_hex Encoder.encode_frequencies Encode 'bssid' and '... | stack_v2_sparse_classes_36k_train_005526 | 2,118 | no_license | [
{
"docstring": "Shortcut for: Encoder.encode_hex Encoder.encode_frequencies Encode 'bssid' and 'psk' into 'frequencies'",
"name": "encode",
"signature": "def encode(bssid, psk)"
},
{
"docstring": "Wrapper for: ..voice.MainActivity.MainActivity._to_mac_address ..voice.MainActivity.MainActivity._g... | 3 | stack_v2_sparse_classes_30k_train_005020 | Implement the Python class `Encoder` described below.
Class description:
Essentially a minimalist wrapper for ..voice.encoder.DataEncoder.DataEncoder Utilising: ..voice.MainActivity.MainActivity ..voice.encoder.VoicePlayer.VoicePlayer
Method signatures and docstrings:
- def encode(bssid, psk): Shortcut for: Encoder.e... | Implement the Python class `Encoder` described below.
Class description:
Essentially a minimalist wrapper for ..voice.encoder.DataEncoder.DataEncoder Utilising: ..voice.MainActivity.MainActivity ..voice.encoder.VoicePlayer.VoicePlayer
Method signatures and docstrings:
- def encode(bssid, psk): Shortcut for: Encoder.e... | 7d370342f34e26e6e66718ae397eb1d81253cd8a | <|skeleton|>
class Encoder:
"""Essentially a minimalist wrapper for ..voice.encoder.DataEncoder.DataEncoder Utilising: ..voice.MainActivity.MainActivity ..voice.encoder.VoicePlayer.VoicePlayer"""
def encode(bssid, psk):
"""Shortcut for: Encoder.encode_hex Encoder.encode_frequencies Encode 'bssid' and '... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Encoder:
"""Essentially a minimalist wrapper for ..voice.encoder.DataEncoder.DataEncoder Utilising: ..voice.MainActivity.MainActivity ..voice.encoder.VoicePlayer.VoicePlayer"""
def encode(bssid, psk):
"""Shortcut for: Encoder.encode_hex Encoder.encode_frequencies Encode 'bssid' and 'psk' into 'fr... | the_stack_v2_python_sparse | yatwin/onekeywifi/encoder/Encoder.py | andre95d/python-yatwin | train | 0 |
c435ccde939562c7781bb0c6671872a5e16fe4d8 | [
"doc_dict = super(FullCasePillow, self).change_trigger(changes_dict)\nif doc_dict is not None:\n domain = doc_dict.get('domain', None)\n if domain is None:\n domain = UNKNOWN_DOMAIN\n dynamic_domains = getattr(settings, 'ES_CASE_FULL_INDEX_DOMAINS', [])\n if domain in dynamic_domains:\n re... | <|body_start_0|>
doc_dict = super(FullCasePillow, self).change_trigger(changes_dict)
if doc_dict is not None:
domain = doc_dict.get('domain', None)
if domain is None:
domain = UNKNOWN_DOMAIN
dynamic_domains = getattr(settings, 'ES_CASE_FULL_INDEX_DOMAI... | an extension to CasePillow that provides for indexing of custom case properties NOTE: deprecated and superseded by ReportCasePillow! | FullCasePillow | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FullCasePillow:
"""an extension to CasePillow that provides for indexing of custom case properties NOTE: deprecated and superseded by ReportCasePillow!"""
def change_trigger(self, changes_dict):
"""Override and check to ensure that the opened doc's domain matches those enabled for fu... | stack_v2_sparse_classes_36k_train_005527 | 1,749 | no_license | [
{
"docstring": "Override and check to ensure that the opened doc's domain matches those enabled for fully indexed case docs",
"name": "change_trigger",
"signature": "def change_trigger(self, changes_dict)"
},
{
"docstring": "Unique ES type key for each case",
"name": "get_type_string",
"... | 2 | null | Implement the Python class `FullCasePillow` described below.
Class description:
an extension to CasePillow that provides for indexing of custom case properties NOTE: deprecated and superseded by ReportCasePillow!
Method signatures and docstrings:
- def change_trigger(self, changes_dict): Override and check to ensure ... | Implement the Python class `FullCasePillow` described below.
Class description:
an extension to CasePillow that provides for indexing of custom case properties NOTE: deprecated and superseded by ReportCasePillow!
Method signatures and docstrings:
- def change_trigger(self, changes_dict): Override and check to ensure ... | b1b894f4cb4a266b2dff7598cf9a9ae295bfa671 | <|skeleton|>
class FullCasePillow:
"""an extension to CasePillow that provides for indexing of custom case properties NOTE: deprecated and superseded by ReportCasePillow!"""
def change_trigger(self, changes_dict):
"""Override and check to ensure that the opened doc's domain matches those enabled for fu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FullCasePillow:
"""an extension to CasePillow that provides for indexing of custom case properties NOTE: deprecated and superseded by ReportCasePillow!"""
def change_trigger(self, changes_dict):
"""Override and check to ensure that the opened doc's domain matches those enabled for fully indexed c... | the_stack_v2_python_sparse | corehq/pillows/fullcase.py | kennknowles/commcare-hq | train | 0 |
0d29a47cff4aa8c9d70176e614d8fa386ab03461 | [
"gym.Wrapper.__init__(self, env)\nself.noop_max = noop_max\nself.noop_action = 0\nassert env.unwrapped.get_action_meanings()[0] == 'NOOP'",
"self.env.reset()\nnoops = random.randrange(1, self.noop_max + 1)\nassert noops > 0\nobs = None\nfor _ in range(noops):\n obs, _, done, _ = self.env.step(self.noop_action)... | <|body_start_0|>
gym.Wrapper.__init__(self, env)
self.noop_max = noop_max
self.noop_action = 0
assert env.unwrapped.get_action_meanings()[0] == 'NOOP'
<|end_body_0|>
<|body_start_1|>
self.env.reset()
noops = random.randrange(1, self.noop_max + 1)
assert noops > 0... | NoopResetEnv | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoopResetEnv:
def __init__(self, env, noop_max=30):
"""Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0."""
<|body_0|>
def _reset(self):
"""Do no-op action for a number of steps in [1, noop_max]."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_005528 | 16,880 | permissive | [
{
"docstring": "Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0.",
"name": "__init__",
"signature": "def __init__(self, env, noop_max=30)"
},
{
"docstring": "Do no-op action for a number of steps in [1, noop_max].",
"name": "_reset",
"sig... | 2 | stack_v2_sparse_classes_30k_train_001316 | Implement the Python class `NoopResetEnv` described below.
Class description:
Implement the NoopResetEnv class.
Method signatures and docstrings:
- def __init__(self, env, noop_max=30): Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0.
- def _reset(self): Do no-op acti... | Implement the Python class `NoopResetEnv` described below.
Class description:
Implement the NoopResetEnv class.
Method signatures and docstrings:
- def __init__(self, env, noop_max=30): Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0.
- def _reset(self): Do no-op acti... | 9eb833f1f5a144f49849d2bc9ab90450b3c8a6dd | <|skeleton|>
class NoopResetEnv:
def __init__(self, env, noop_max=30):
"""Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0."""
<|body_0|>
def _reset(self):
"""Do no-op action for a number of steps in [1, noop_max]."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NoopResetEnv:
def __init__(self, env, noop_max=30):
"""Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0."""
gym.Wrapper.__init__(self, env)
self.noop_max = noop_max
self.noop_action = 0
assert env.unwrapped.get_action_mea... | the_stack_v2_python_sparse | rl_a3c_pytorch/environment_for_render.py | doronsobol/Visual_analogies_for_RL_transfer_Learning | train | 2 | |
3e0565af8f5a79dc390eaf4f4cd97d50de9dd3f9 | [
"transactions_to_include = cast(list[str], self._parameter('transactions_to_include'))\ntransactions_to_ignore = cast(list[str], self._parameter('transactions_to_ignore'))\ncounts = dict(failed=0, success=0)\nfor response in responses:\n count = await self.__parse_response(response, transactions_to_include, tran... | <|body_start_0|>
transactions_to_include = cast(list[str], self._parameter('transactions_to_include'))
transactions_to_ignore = cast(list[str], self._parameter('transactions_to_ignore'))
counts = dict(failed=0, success=0)
for response in responses:
count = await self.__parse_... | Collector for the number of performance test transactions. | PerformanceTestRunnerTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PerformanceTestRunnerTests:
"""Collector for the number of performance test transactions."""
async def _parse_source_responses(self, responses: SourceResponses) -> SourceMeasurement:
"""Override to parse the transactions from the responses and return the transactions with the desired... | stack_v2_sparse_classes_36k_train_005529 | 2,267 | permissive | [
{
"docstring": "Override to parse the transactions from the responses and return the transactions with the desired status.",
"name": "_parse_source_responses",
"signature": "async def _parse_source_responses(self, responses: SourceResponses) -> SourceMeasurement"
},
{
"docstring": "Parse the tra... | 2 | stack_v2_sparse_classes_30k_train_009780 | Implement the Python class `PerformanceTestRunnerTests` described below.
Class description:
Collector for the number of performance test transactions.
Method signatures and docstrings:
- async def _parse_source_responses(self, responses: SourceResponses) -> SourceMeasurement: Override to parse the transactions from t... | Implement the Python class `PerformanceTestRunnerTests` described below.
Class description:
Collector for the number of performance test transactions.
Method signatures and docstrings:
- async def _parse_source_responses(self, responses: SourceResponses) -> SourceMeasurement: Override to parse the transactions from t... | 602b6970e5d9088cb89cc6d488337349e54e1c9a | <|skeleton|>
class PerformanceTestRunnerTests:
"""Collector for the number of performance test transactions."""
async def _parse_source_responses(self, responses: SourceResponses) -> SourceMeasurement:
"""Override to parse the transactions from the responses and return the transactions with the desired... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PerformanceTestRunnerTests:
"""Collector for the number of performance test transactions."""
async def _parse_source_responses(self, responses: SourceResponses) -> SourceMeasurement:
"""Override to parse the transactions from the responses and return the transactions with the desired status."""
... | the_stack_v2_python_sparse | components/collector/src/source_collectors/performancetest_runner/tests.py | Erik-Stel/quality-time | train | 0 |
caf5ea35f2109f7f61bcc5b4961def81f1152511 | [
"n = len(prices)\nif n < 2:\n return 0\nif k >= n / 2:\n return sum((i - j for i, j in zip(prices[1:], prices[:-1]) if i - j > 0))\nglobal_max = [[0] * n for _ in xrange(k + 1)]\nfor i in xrange(1, k + 1):\n local_max = [0] * n\n for j in xrange(1, n):\n profit = prices[j] - prices[j - 1]\n ... | <|body_start_0|>
n = len(prices)
if n < 2:
return 0
if k >= n / 2:
return sum((i - j for i, j in zip(prices[1:], prices[:-1]) if i - j > 0))
global_max = [[0] * n for _ in xrange(k + 1)]
for i in xrange(1, k + 1):
local_max = [0] * n
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, k, prices):
""":type k: int :type prices: List[int] :rtype: int beats 35.60%"""
<|body_0|>
def maxProfit1(self, k, prices):
""":type k: int :type prices: List[int] :rtype: int beats 50.00%"""
<|body_1|>
def maxProfit2(self, ... | stack_v2_sparse_classes_36k_train_005530 | 3,377 | no_license | [
{
"docstring": ":type k: int :type prices: List[int] :rtype: int beats 35.60%",
"name": "maxProfit",
"signature": "def maxProfit(self, k, prices)"
},
{
"docstring": ":type k: int :type prices: List[int] :rtype: int beats 50.00%",
"name": "maxProfit1",
"signature": "def maxProfit1(self, k... | 3 | stack_v2_sparse_classes_30k_train_009326 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, k, prices): :type k: int :type prices: List[int] :rtype: int beats 35.60%
- def maxProfit1(self, k, prices): :type k: int :type prices: List[int] :rtype: int ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, k, prices): :type k: int :type prices: List[int] :rtype: int beats 35.60%
- def maxProfit1(self, k, prices): :type k: int :type prices: List[int] :rtype: int ... | 7e0e917c15d3e35f49da3a00ef395bd5ff180d79 | <|skeleton|>
class Solution:
def maxProfit(self, k, prices):
""":type k: int :type prices: List[int] :rtype: int beats 35.60%"""
<|body_0|>
def maxProfit1(self, k, prices):
""":type k: int :type prices: List[int] :rtype: int beats 50.00%"""
<|body_1|>
def maxProfit2(self, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, k, prices):
""":type k: int :type prices: List[int] :rtype: int beats 35.60%"""
n = len(prices)
if n < 2:
return 0
if k >= n / 2:
return sum((i - j for i, j in zip(prices[1:], prices[:-1]) if i - j > 0))
global_max =... | the_stack_v2_python_sparse | LeetCode/188_best_time_to_buy_and_sell_stock_IV.py | yao23/Machine_Learning_Playground | train | 12 | |
f1c3d22dacc7b4333d38d095819b9d3eeb158559 | [
"cur = None\nwhile head:\n tmp = head.next\n head.next = cur\n cur = head\n head = tmp\nreturn cur",
"if not head or not head.next:\n return head\nrec = self.reverseListRecursion(head.next)\nhead.next.next = head\nhead.next = None\nreturn rec"
] | <|body_start_0|>
cur = None
while head:
tmp = head.next
head.next = cur
cur = head
head = tmp
return cur
<|end_body_0|>
<|body_start_1|>
if not head or not head.next:
return head
rec = self.reverseListRecursion(head.nex... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList_loop(self, head):
"""初始化一个指针为None,作为链表起点 每次循环取出head放到新的指针头, head指向head的下一个node 完成翻转"""
<|body_0|>
def reverseListRecursion(self, head):
"""递归翻转 取到最后一个元素, 递归从最后一个元素开始指向上一个元素"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cu... | stack_v2_sparse_classes_36k_train_005531 | 1,555 | no_license | [
{
"docstring": "初始化一个指针为None,作为链表起点 每次循环取出head放到新的指针头, head指向head的下一个node 完成翻转",
"name": "reverseList_loop",
"signature": "def reverseList_loop(self, head)"
},
{
"docstring": "递归翻转 取到最后一个元素, 递归从最后一个元素开始指向上一个元素",
"name": "reverseListRecursion",
"signature": "def reverseListRecursion(self,... | 2 | stack_v2_sparse_classes_30k_train_003264 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList_loop(self, head): 初始化一个指针为None,作为链表起点 每次循环取出head放到新的指针头, head指向head的下一个node 完成翻转
- def reverseListRecursion(self, head): 递归翻转 取到最后一个元素, 递归从最后一个元素开始指向上一个元素 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList_loop(self, head): 初始化一个指针为None,作为链表起点 每次循环取出head放到新的指针头, head指向head的下一个node 完成翻转
- def reverseListRecursion(self, head): 递归翻转 取到最后一个元素, 递归从最后一个元素开始指向上一个元素
<|skel... | dc795dad23e54311dee8d79c7bac60b7f5a00495 | <|skeleton|>
class Solution:
def reverseList_loop(self, head):
"""初始化一个指针为None,作为链表起点 每次循环取出head放到新的指针头, head指向head的下一个node 完成翻转"""
<|body_0|>
def reverseListRecursion(self, head):
"""递归翻转 取到最后一个元素, 递归从最后一个元素开始指向上一个元素"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseList_loop(self, head):
"""初始化一个指针为None,作为链表起点 每次循环取出head放到新的指针头, head指向head的下一个node 完成翻转"""
cur = None
while head:
tmp = head.next
head.next = cur
cur = head
head = tmp
return cur
def reverseListRecursion... | the_stack_v2_python_sparse | leet_code/sword_offerII/24.reverseList.py | rookieygl/LeetCode | train | 0 | |
a314e9d42e749bc9a4413b8e445c96c4ab1a3ace | [
"super(TriggerVelocity, self).__init__(name)\nself.logger.debug('%s.__init__()' % self.__class__.__name__)\nself._actor = actor\nself._target_velocity = target_velocity",
"new_status = py_trees.common.Status.RUNNING\ndelta_velocity = self._target_velocity - CarlaDataProvider.get_velocity(self._actor)\nif delta_ve... | <|body_start_0|>
super(TriggerVelocity, self).__init__(name)
self.logger.debug('%s.__init__()' % self.__class__.__name__)
self._actor = actor
self._target_velocity = target_velocity
<|end_body_0|>
<|body_start_1|>
new_status = py_trees.common.Status.RUNNING
delta_velocit... | This class contains the trigger velocity (condition) of a scenario Important parameters: - actor: CARLA actor to execute the behavior - name: Name of the condition - target_velocity: The behavior is successful, if the actor is at least as fast as target_velocity in m/s The condition terminates with SUCCESS, when the ac... | TriggerVelocity | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TriggerVelocity:
"""This class contains the trigger velocity (condition) of a scenario Important parameters: - actor: CARLA actor to execute the behavior - name: Name of the condition - target_velocity: The behavior is successful, if the actor is at least as fast as target_velocity in m/s The con... | stack_v2_sparse_classes_36k_train_005532 | 18,494 | permissive | [
{
"docstring": "Setup trigger velocity",
"name": "__init__",
"signature": "def __init__(self, actor, target_velocity, name='TriggerVelocity')"
},
{
"docstring": "Check if the actor has the trigger velocity",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017269 | Implement the Python class `TriggerVelocity` described below.
Class description:
This class contains the trigger velocity (condition) of a scenario Important parameters: - actor: CARLA actor to execute the behavior - name: Name of the condition - target_velocity: The behavior is successful, if the actor is at least as... | Implement the Python class `TriggerVelocity` described below.
Class description:
This class contains the trigger velocity (condition) of a scenario Important parameters: - actor: CARLA actor to execute the behavior - name: Name of the condition - target_velocity: The behavior is successful, if the actor is at least as... | 8ab0894b92e1f994802a218002021ee075c405bf | <|skeleton|>
class TriggerVelocity:
"""This class contains the trigger velocity (condition) of a scenario Important parameters: - actor: CARLA actor to execute the behavior - name: Name of the condition - target_velocity: The behavior is successful, if the actor is at least as fast as target_velocity in m/s The con... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TriggerVelocity:
"""This class contains the trigger velocity (condition) of a scenario Important parameters: - actor: CARLA actor to execute the behavior - name: Name of the condition - target_velocity: The behavior is successful, if the actor is at least as fast as target_velocity in m/s The condition termin... | the_stack_v2_python_sparse | carla_rllib/carla_rllib-prak_evaluator-carla_rllib-prak_evaluator/carla_rllib/prak_evaluator/srunner/scenarioconfigs/scenariomanager/scenarioatomics/atomic_trigger_conditions.py | TinaMenke/Deep-Reinforcement-Learning | train | 9 |
ca1ec382ef5b4d9b5d14cece87aa3612a3e39ab9 | [
"m = defaultdict(list)\nfor i, v in enumerate(nums):\n m[v].append(i)\nfor v in nums:\n try:\n x = m[v].pop()\n y = m[target - v].pop()\n return sorted([x, y])\n except:\n pass",
"lookup = {}\nfor i, num in enumerate(nums):\n if target - num in lookup:\n return [look... | <|body_start_0|>
m = defaultdict(list)
for i, v in enumerate(nums):
m[v].append(i)
for v in nums:
try:
x = m[v].pop()
y = m[target - v].pop()
return sorted([x, y])
except:
pass
<|end_body_0|>
<|b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum_1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_005533 | 806 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum_1",
"signature": "def twoSum_1(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum",
"signature": "def twoSum(self, nums, target)"
... | 2 | stack_v2_sparse_classes_30k_train_016113 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_1(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_1(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List... | d8ed762d1005975f0de4f07760c9671195621c88 | <|skeleton|>
class Solution:
def twoSum_1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum_1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
m = defaultdict(list)
for i, v in enumerate(nums):
m[v].append(i)
for v in nums:
try:
x = m[v].pop()
y = m[target ... | the_stack_v2_python_sparse | two-sum/solution.py | uxlsl/leetcode_practice | train | 0 | |
5cc0da53ab7b7488e7c4174ef3f50f05e73f94f6 | [
"super(ContactGeometry2DProfile, self).__init__(filename, parent=parent)\nself._parent = parent\nself.body = body\nself.profile = profile\nself.vtk_actor = None\nself.color = color\nself.profile_type = profile_type\nif self.geom_data.tangents is None and self.geom_data.normals is None:\n self._create_normals_and... | <|body_start_0|>
super(ContactGeometry2DProfile, self).__init__(filename, parent=parent)
self._parent = parent
self.body = body
self.profile = profile
self.vtk_actor = None
self.color = color
self.profile_type = profile_type
if self.geom_data.tangents is N... | classdocs | ContactGeometry2DProfile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContactGeometry2DProfile:
"""classdocs"""
def __init__(self, filename, profile, profile_type='opened', color=np.array([0, 1, 0], dtype='float32'), _dict={}, body=None, parent=None):
"""Constructor :param parent: :return:"""
<|body_0|>
def _create_normals_and_tangents(sel... | stack_v2_sparse_classes_36k_train_005534 | 5,056 | no_license | [
{
"docstring": "Constructor :param parent: :return:",
"name": "__init__",
"signature": "def __init__(self, filename, profile, profile_type='opened', color=np.array([0, 1, 0], dtype='float32'), _dict={}, body=None, parent=None)"
},
{
"docstring": ":return:",
"name": "_create_normals_and_tange... | 2 | stack_v2_sparse_classes_30k_train_007344 | Implement the Python class `ContactGeometry2DProfile` described below.
Class description:
classdocs
Method signatures and docstrings:
- def __init__(self, filename, profile, profile_type='opened', color=np.array([0, 1, 0], dtype='float32'), _dict={}, body=None, parent=None): Constructor :param parent: :return:
- def ... | Implement the Python class `ContactGeometry2DProfile` described below.
Class description:
classdocs
Method signatures and docstrings:
- def __init__(self, filename, profile, profile_type='opened', color=np.array([0, 1, 0], dtype='float32'), _dict={}, body=None, parent=None): Constructor :param parent: :return:
- def ... | 5e6a54dee662206664dde022ccca372f966b1789 | <|skeleton|>
class ContactGeometry2DProfile:
"""classdocs"""
def __init__(self, filename, profile, profile_type='opened', color=np.array([0, 1, 0], dtype='float32'), _dict={}, body=None, parent=None):
"""Constructor :param parent: :return:"""
<|body_0|>
def _create_normals_and_tangents(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContactGeometry2DProfile:
"""classdocs"""
def __init__(self, filename, profile, profile_type='opened', color=np.array([0, 1, 0], dtype='float32'), _dict={}, body=None, parent=None):
"""Constructor :param parent: :return:"""
super(ContactGeometry2DProfile, self).__init__(filename, parent=p... | the_stack_v2_python_sparse | MBD_system/body/geometry/geometry_2D_profile.py | xupeiwust/DyS | train | 0 |
30de206659d84a5cc820f282ffd26e9e98a3b54f | [
"assert len(input_list) > 0\nsuper().__init__(self.PROBLEM_NAME)\nself.input_list = input_list",
"print('Solving {} problem ...'.format(self.PROBLEM_NAME))\nvalue_stack = Stack()\nroot = -sys.maxsize\nfor value in self.input_list:\n if value < root:\n return False\n while len(value_stack) > 0 and val... | <|body_start_0|>
assert len(input_list) > 0
super().__init__(self.PROBLEM_NAME)
self.input_list = input_list
<|end_body_0|>
<|body_start_1|>
print('Solving {} problem ...'.format(self.PROBLEM_NAME))
value_stack = Stack()
root = -sys.maxsize
for value in self.inpu... | Check if the given array represents a pre-order binary tree. | CheckArrayIsPreOrderBST | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckArrayIsPreOrderBST:
"""Check if the given array represents a pre-order binary tree."""
def __init__(self, input_list):
"""CheckArrayIsPreOrderBST Args: input_list: Contains an array of numbers Returns: None Raises: None"""
<|body_0|>
def solve(self):
"""Solv... | stack_v2_sparse_classes_36k_train_005535 | 1,952 | no_license | [
{
"docstring": "CheckArrayIsPreOrderBST Args: input_list: Contains an array of numbers Returns: None Raises: None",
"name": "__init__",
"signature": "def __init__(self, input_list)"
},
{
"docstring": "Solve the problem Note: O(n logn) (runtime) and O(n) (Space) works by using a stack to store th... | 2 | null | Implement the Python class `CheckArrayIsPreOrderBST` described below.
Class description:
Check if the given array represents a pre-order binary tree.
Method signatures and docstrings:
- def __init__(self, input_list): CheckArrayIsPreOrderBST Args: input_list: Contains an array of numbers Returns: None Raises: None
- ... | Implement the Python class `CheckArrayIsPreOrderBST` described below.
Class description:
Check if the given array represents a pre-order binary tree.
Method signatures and docstrings:
- def __init__(self, input_list): CheckArrayIsPreOrderBST Args: input_list: Contains an array of numbers Returns: None Raises: None
- ... | 11f4d25cb211740514c119a60962d075a0817abd | <|skeleton|>
class CheckArrayIsPreOrderBST:
"""Check if the given array represents a pre-order binary tree."""
def __init__(self, input_list):
"""CheckArrayIsPreOrderBST Args: input_list: Contains an array of numbers Returns: None Raises: None"""
<|body_0|>
def solve(self):
"""Solv... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CheckArrayIsPreOrderBST:
"""Check if the given array represents a pre-order binary tree."""
def __init__(self, input_list):
"""CheckArrayIsPreOrderBST Args: input_list: Contains an array of numbers Returns: None Raises: None"""
assert len(input_list) > 0
super().__init__(self.PROB... | the_stack_v2_python_sparse | python/problems/binary_tree/check_array_is_preorder_bst.py | santhosh-kumar/AlgorithmsAndDataStructures | train | 2 |
98a21ef74103c5afe58091994df806509c9aed4f | [
"self.z_start = z_start\nself.z_end = z_end\nself.gamma_boost = gamma_boost\nif m == 'all':\n self.modes = None\nelif isinstance(m, int):\n self.modes = [m]\nelif isinstance(m, list):\n self.modes = m\nelse:\n raise TypeError('m should be an int or a list of ints.')",
"if self.gamma_boost is None:\n ... | <|body_start_0|>
self.z_start = z_start
self.z_end = z_end
self.gamma_boost = gamma_boost
if m == 'all':
self.modes = None
elif isinstance(m, int):
self.modes = [m]
elif isinstance(m, list):
self.modes = m
else:
rais... | Mirror | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mirror:
def __init__(self, z_start, z_end, gamma_boost=None, m='all'):
"""Initialize a mirror. The mirror reflects the fields in the z direction, by setting the specified field modes to 0 in a thin slice orthogonal to z, at each timestep.s By default, all modes are zeroed. Parameters ---... | stack_v2_sparse_classes_36k_train_005536 | 3,295 | permissive | [
{
"docstring": "Initialize a mirror. The mirror reflects the fields in the z direction, by setting the specified field modes to 0 in a thin slice orthogonal to z, at each timestep.s By default, all modes are zeroed. Parameters ---------- z_start: float Start position of the mirror in the lab frame z_end: float ... | 2 | stack_v2_sparse_classes_30k_train_012104 | Implement the Python class `Mirror` described below.
Class description:
Implement the Mirror class.
Method signatures and docstrings:
- def __init__(self, z_start, z_end, gamma_boost=None, m='all'): Initialize a mirror. The mirror reflects the fields in the z direction, by setting the specified field modes to 0 in a ... | Implement the Python class `Mirror` described below.
Class description:
Implement the Mirror class.
Method signatures and docstrings:
- def __init__(self, z_start, z_end, gamma_boost=None, m='all'): Initialize a mirror. The mirror reflects the fields in the z direction, by setting the specified field modes to 0 in a ... | 5744598571eab40c4fb45cc3db21f346b69b1f37 | <|skeleton|>
class Mirror:
def __init__(self, z_start, z_end, gamma_boost=None, m='all'):
"""Initialize a mirror. The mirror reflects the fields in the z direction, by setting the specified field modes to 0 in a thin slice orthogonal to z, at each timestep.s By default, all modes are zeroed. Parameters ---... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Mirror:
def __init__(self, z_start, z_end, gamma_boost=None, m='all'):
"""Initialize a mirror. The mirror reflects the fields in the z direction, by setting the specified field modes to 0 in a thin slice orthogonal to z, at each timestep.s By default, all modes are zeroed. Parameters ---------- z_star... | the_stack_v2_python_sparse | fbpic/lpa_utils/mirrors.py | fbpic/fbpic | train | 163 | |
a59be2338f98961ea1354a8dece5d9f33c220211 | [
"if category:\n self.services[category].update()\nelse:\n for category in self.services:\n self.services[category].update()",
"if category:\n self.services[category].refresh_current_semester()\nelse:\n for category in self.refreshable_services:\n self.services[category].refresh_current_s... | <|body_start_0|>
if category:
self.services[category].update()
else:
for category in self.services:
self.services[category].update()
<|end_body_0|>
<|body_start_1|>
if category:
self.services[category].refresh_current_semester()
else:
... | Playlist Service. | PlaylistService | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlaylistService:
"""Playlist Service."""
def update(self, category=None):
"""Update all playlist categories. If given category, update only playlists in that category."""
<|body_0|>
def refresh_current_semester(self, category=None):
"""Fetch the playlist courses ... | stack_v2_sparse_classes_36k_train_005537 | 2,278 | permissive | [
{
"docstring": "Update all playlist categories. If given category, update only playlists in that category.",
"name": "update",
"signature": "def update(self, category=None)"
},
{
"docstring": "Fetch the playlist courses from SIS for the current semester, overwriting the cache.",
"name": "ref... | 3 | stack_v2_sparse_classes_30k_train_018758 | Implement the Python class `PlaylistService` described below.
Class description:
Playlist Service.
Method signatures and docstrings:
- def update(self, category=None): Update all playlist categories. If given category, update only playlists in that category.
- def refresh_current_semester(self, category=None): Fetch ... | Implement the Python class `PlaylistService` described below.
Class description:
Playlist Service.
Method signatures and docstrings:
- def update(self, category=None): Update all playlist categories. If given category, update only playlists in that category.
- def refresh_current_semester(self, category=None): Fetch ... | 34578dc14c8e5c2cfb28f8d6710e791cdd773d59 | <|skeleton|>
class PlaylistService:
"""Playlist Service."""
def update(self, category=None):
"""Update all playlist categories. If given category, update only playlists in that category."""
<|body_0|>
def refresh_current_semester(self, category=None):
"""Fetch the playlist courses ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlaylistService:
"""Playlist Service."""
def update(self, category=None):
"""Update all playlist categories. If given category, update only playlists in that category."""
if category:
self.services[category].update()
else:
for category in self.services:
... | the_stack_v2_python_sparse | backend/playlist/service/playlist.py | AviFS/berkeleytime | train | 0 |
7d7d37163c88858e4549c80b13bda84f2316794e | [
"if not head:\n return False\npointer1 = head\npointer2 = head\nwhile pointer1 is not None and pointer2 is not None:\n pointer1 = pointer1.next\n try:\n pointer2 = pointer2.next.next\n except Exception as e:\n return False\n if pointer1 == pointer2:\n return True\nreturn False",
... | <|body_start_0|>
if not head:
return False
pointer1 = head
pointer2 = head
while pointer1 is not None and pointer2 is not None:
pointer1 = pointer1.next
try:
pointer2 = pointer2.next.next
except Exception as e:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hasCycle(self, head):
""":type head: ListNode :rtype: bool"""
<|body_0|>
def hasCycle2(self, head):
""":type head: ListNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not head:
return False
poin... | stack_v2_sparse_classes_36k_train_005538 | 1,079 | no_license | [
{
"docstring": ":type head: ListNode :rtype: bool",
"name": "hasCycle",
"signature": "def hasCycle(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: bool",
"name": "hasCycle2",
"signature": "def hasCycle2(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001801 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasCycle(self, head): :type head: ListNode :rtype: bool
- def hasCycle2(self, head): :type head: ListNode :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasCycle(self, head): :type head: ListNode :rtype: bool
- def hasCycle2(self, head): :type head: ListNode :rtype: bool
<|skeleton|>
class Solution:
def hasCycle(self, h... | d4a33dc28a6d3f99d5179fdb6a83b2ab8c5a0beb | <|skeleton|>
class Solution:
def hasCycle(self, head):
""":type head: ListNode :rtype: bool"""
<|body_0|>
def hasCycle2(self, head):
""":type head: ListNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def hasCycle(self, head):
""":type head: ListNode :rtype: bool"""
if not head:
return False
pointer1 = head
pointer2 = head
while pointer1 is not None and pointer2 is not None:
pointer1 = pointer1.next
try:
p... | the_stack_v2_python_sparse | leetcode/141_linked_list_cycle.py | 294150302hxq/python_learn | train | 0 | |
90601a5194897661efbb0583b8a32d239c787db7 | [
"if not hasattr(cls, 'event_formatters'):\n cls.event_formatters = {}\n cls.default_formatter = DefaultFormatter()\n for cls_formatter in EventFormatter.classes:\n try:\n formatter = EventFormatter.classes[cls_formatter]()\n if formatter.DATA_TYPE in cls.event_formatters:\n ... | <|body_start_0|>
if not hasattr(cls, 'event_formatters'):
cls.event_formatters = {}
cls.default_formatter = DefaultFormatter()
for cls_formatter in EventFormatter.classes:
try:
formatter = EventFormatter.classes[cls_formatter]()
... | Class to manage the event formatters. | EventFormatterManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventFormatterManager:
"""Class to manage the event formatters."""
def GetFormatter(cls, event_object):
"""Retrieves the formatter for a specific event object. This function builds a map of data types and the corresponding event formatters. At the moment this map is only build once. ... | stack_v2_sparse_classes_36k_train_005539 | 15,049 | permissive | [
{
"docstring": "Retrieves the formatter for a specific event object. This function builds a map of data types and the corresponding event formatters. At the moment this map is only build once. Args: event_object: The event object (EventObject) which is used to identify the formatter. Returns: The corresponding ... | 3 | stack_v2_sparse_classes_30k_train_016189 | Implement the Python class `EventFormatterManager` described below.
Class description:
Class to manage the event formatters.
Method signatures and docstrings:
- def GetFormatter(cls, event_object): Retrieves the formatter for a specific event object. This function builds a map of data types and the corresponding even... | Implement the Python class `EventFormatterManager` described below.
Class description:
Class to manage the event formatters.
Method signatures and docstrings:
- def GetFormatter(cls, event_object): Retrieves the formatter for a specific event object. This function builds a map of data types and the corresponding even... | b4dc64b3a2d2906e8947824c493a2bc311d765c1 | <|skeleton|>
class EventFormatterManager:
"""Class to manage the event formatters."""
def GetFormatter(cls, event_object):
"""Retrieves the formatter for a specific event object. This function builds a map of data types and the corresponding event formatters. At the moment this map is only build once. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventFormatterManager:
"""Class to manage the event formatters."""
def GetFormatter(cls, event_object):
"""Retrieves the formatter for a specific event object. This function builds a map of data types and the corresponding event formatters. At the moment this map is only build once. Args: event_o... | the_stack_v2_python_sparse | plaso/lib/eventdata.py | iwm911/plaso | train | 0 |
f7644841b6b3379a8769cc7fc2b286298441475f | [
"self.sleft = Block()\nself.sright = Block(left=self.sleft)\nself.sleft.right = self.sright\nself.keyblock = {}",
"preb = self.sleft\nif key in self.keyblock:\n preb = self.keyblock[key]\n preb.kids.remove(key)\nval = preb.val + 1\nif preb.right.val == val:\n curb = preb.right\nelse:\n curb = Block(va... | <|body_start_0|>
self.sleft = Block()
self.sright = Block(left=self.sleft)
self.sleft.right = self.sright
self.keyblock = {}
<|end_body_0|>
<|body_start_1|>
preb = self.sleft
if key in self.keyblock:
preb = self.keyblock[key]
preb.kids.remove(key)... | AllOne | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AllOne:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def inc(self, key: str) -> None:
"""Inserts a new key <Key> with value 1. Or increments an existing key by 1."""
<|body_1|>
def dec(self, key: str) -> None:
"""Decr... | stack_v2_sparse_classes_36k_train_005540 | 2,418 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a new key <Key> with value 1. Or increments an existing key by 1.",
"name": "inc",
"signature": "def inc(self, key: str) -> None"
},
{
"docstrin... | 5 | null | Implement the Python class `AllOne` described below.
Class description:
Implement the AllOne class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def inc(self, key: str) -> None: Inserts a new key <Key> with value 1. Or increments an existing key by 1.
- def dec(self, ... | Implement the Python class `AllOne` described below.
Class description:
Implement the AllOne class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def inc(self, key: str) -> None: Inserts a new key <Key> with value 1. Or increments an existing key by 1.
- def dec(self, ... | 498308e6a065af444a1d5570341231e4c51dfa3f | <|skeleton|>
class AllOne:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def inc(self, key: str) -> None:
"""Inserts a new key <Key> with value 1. Or increments an existing key by 1."""
<|body_1|>
def dec(self, key: str) -> None:
"""Decr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AllOne:
def __init__(self):
"""Initialize your data structure here."""
self.sleft = Block()
self.sright = Block(left=self.sleft)
self.sleft.right = self.sright
self.keyblock = {}
def inc(self, key: str) -> None:
"""Inserts a new key <Key> with value 1. Or i... | the_stack_v2_python_sparse | lc432_ood.py | Mela2014/lc_punch | train | 0 | |
7e4848c4087951dc6e0c0ff5892aa17670f8ae04 | [
"log.info('Starting Infrastructure Layer...')\nself.topology = None\nsuper(InfrastructureLayerAPI, self).__init__(standalone, **kwargs)",
"log.debug('Initializing Infrastructure Layer...')\nCONFIG.set_layer_loaded(self._core_name)\nmn_opts = CONFIG.get_mn_network_opts()\noptional_topo = getattr(self, '_topo', Non... | <|body_start_0|>
log.info('Starting Infrastructure Layer...')
self.topology = None
super(InfrastructureLayerAPI, self).__init__(standalone, **kwargs)
<|end_body_0|>
<|body_start_1|>
log.debug('Initializing Infrastructure Layer...')
CONFIG.set_layer_loaded(self._core_name)
... | Entry point for Infrastructure Layer (IL). Maintain the contact with other UNIFY layers. Implement a specific part of the Co - Rm reference point. | InfrastructureLayerAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InfrastructureLayerAPI:
"""Entry point for Infrastructure Layer (IL). Maintain the contact with other UNIFY layers. Implement a specific part of the Co - Rm reference point."""
def __init__(self, standalone=False, **kwargs):
""".. seealso:: :func:`AbstractAPI.__init__() <escape.util.... | stack_v2_sparse_classes_36k_train_005541 | 4,843 | no_license | [
{
"docstring": ".. seealso:: :func:`AbstractAPI.__init__() <escape.util.api.AbstractAPI.__init__>`",
"name": "__init__",
"signature": "def __init__(self, standalone=False, **kwargs)"
},
{
"docstring": ".. seealso:: :func:`AbstractAPI.initialize() <escape.util.api.AbstractAPI.initialize>`",
"... | 5 | stack_v2_sparse_classes_30k_train_012835 | Implement the Python class `InfrastructureLayerAPI` described below.
Class description:
Entry point for Infrastructure Layer (IL). Maintain the contact with other UNIFY layers. Implement a specific part of the Co - Rm reference point.
Method signatures and docstrings:
- def __init__(self, standalone=False, **kwargs):... | Implement the Python class `InfrastructureLayerAPI` described below.
Class description:
Entry point for Infrastructure Layer (IL). Maintain the contact with other UNIFY layers. Implement a specific part of the Co - Rm reference point.
Method signatures and docstrings:
- def __init__(self, standalone=False, **kwargs):... | 30a220b4042b74ea5cccec725eddd4e7f95ba97d | <|skeleton|>
class InfrastructureLayerAPI:
"""Entry point for Infrastructure Layer (IL). Maintain the contact with other UNIFY layers. Implement a specific part of the Co - Rm reference point."""
def __init__(self, standalone=False, **kwargs):
""".. seealso:: :func:`AbstractAPI.__init__() <escape.util.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InfrastructureLayerAPI:
"""Entry point for Infrastructure Layer (IL). Maintain the contact with other UNIFY layers. Implement a specific part of the Co - Rm reference point."""
def __init__(self, standalone=False, **kwargs):
""".. seealso:: :func:`AbstractAPI.__init__() <escape.util.api.AbstractA... | the_stack_v2_python_sparse | escape/escape/infr/il_API.py | hsnlab/fero | train | 3 |
fbe605689c39e55040494d8f4f44c0ce6a9d0d44 | [
"assert type(players) is list and len(players) == 2\nassert type(rules) is list and len(rules) >= 1\nself.players = players\nself.rules = rules\nself.tick = 0",
"self.tick = 0\nwhile self.tick < 1000:\n self.tick += 1\n for player in self.players:\n player.action.tick += 1\n changed = False\n f... | <|body_start_0|>
assert type(players) is list and len(players) == 2
assert type(rules) is list and len(rules) >= 1
self.players = players
self.rules = rules
self.tick = 0
<|end_body_0|>
<|body_start_1|>
self.tick = 0
while self.tick < 1000:
self.tick ... | Main object that performs game emulation according to specified rules | GameEmulator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameEmulator:
"""Main object that performs game emulation according to specified rules"""
def __init__(self, players, rules):
""":param players: list (with length of 2) of PlayerState instances :param rules: list of Rule instances"""
<|body_0|>
def run(self):
"""... | stack_v2_sparse_classes_36k_train_005542 | 2,222 | permissive | [
{
"docstring": ":param players: list (with length of 2) of PlayerState instances :param rules: list of Rule instances",
"name": "__init__",
"signature": "def __init__(self, players, rules)"
},
{
"docstring": "Run emulator",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006768 | Implement the Python class `GameEmulator` described below.
Class description:
Main object that performs game emulation according to specified rules
Method signatures and docstrings:
- def __init__(self, players, rules): :param players: list (with length of 2) of PlayerState instances :param rules: list of Rule instan... | Implement the Python class `GameEmulator` described below.
Class description:
Main object that performs game emulation according to specified rules
Method signatures and docstrings:
- def __init__(self, players, rules): :param players: list (with length of 2) of PlayerState instances :param rules: list of Rule instan... | 647b9cbba936ee76ed71ba9ac54ceb2a32e1c88c | <|skeleton|>
class GameEmulator:
"""Main object that performs game emulation according to specified rules"""
def __init__(self, players, rules):
""":param players: list (with length of 2) of PlayerState instances :param rules: list of Rule instances"""
<|body_0|>
def run(self):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GameEmulator:
"""Main object that performs game emulation according to specified rules"""
def __init__(self, players, rules):
""":param players: list (with length of 2) of PlayerState instances :param rules: list of Rule instances"""
assert type(players) is list and len(players) == 2
... | the_stack_v2_python_sparse | source/emulator/game_emulator.py | teopeurt/pywars | train | 0 |
93324e9ecc3126097e8095b01fee12e8f048537a | [
"u = self.uniform(size=size)\nvalues = -tau * np.log(1 - u)\nreturn values",
"u = self.uniform(size=size)\nvalues = (u * (x_max ** (1 - n) - x_min ** (1 - n)) + x_min ** (1 - n)) ** (1 / (1 - n))\nreturn values",
"u = self.uniform(size=size)\nvalues = np.tan(np.pi * u - np.pi / 2)\nvalues = np.zeros(size)\nretu... | <|body_start_0|>
u = self.uniform(size=size)
values = -tau * np.log(1 - u)
return values
<|end_body_0|>
<|body_start_1|>
u = self.uniform(size=size)
values = (u * (x_max ** (1 - n) - x_min ** (1 - n)) + x_min ** (1 - n)) ** (1 / (1 - n))
return values
<|end_body_1|>
<|b... | Generate random numbers from different distribtions self.uniform(size=size) creates standard uniform random numbers. | Generator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Generator:
"""Generate random numbers from different distribtions self.uniform(size=size) creates standard uniform random numbers."""
def exponential(self, tau, size=None):
"""Draw exponentially distributed random numbers. Blatt 3, Aufgabe 2a)"""
<|body_0|>
def power(sel... | stack_v2_sparse_classes_36k_train_005543 | 4,178 | no_license | [
{
"docstring": "Draw exponentially distributed random numbers. Blatt 3, Aufgabe 2a)",
"name": "exponential",
"signature": "def exponential(self, tau, size=None)"
},
{
"docstring": "Draw random numbers from a power law distribution with index n between x_min and x_max Blatt 3, Aufgabe 2b)",
"... | 5 | null | Implement the Python class `Generator` described below.
Class description:
Generate random numbers from different distribtions self.uniform(size=size) creates standard uniform random numbers.
Method signatures and docstrings:
- def exponential(self, tau, size=None): Draw exponentially distributed random numbers. Blat... | Implement the Python class `Generator` described below.
Class description:
Generate random numbers from different distribtions self.uniform(size=size) creates standard uniform random numbers.
Method signatures and docstrings:
- def exponential(self, tau, size=None): Draw exponentially distributed random numbers. Blat... | 0d7442bd78f9899536a109e87a4c4639ade82a58 | <|skeleton|>
class Generator:
"""Generate random numbers from different distribtions self.uniform(size=size) creates standard uniform random numbers."""
def exponential(self, tau, size=None):
"""Draw exponentially distributed random numbers. Blatt 3, Aufgabe 2a)"""
<|body_0|>
def power(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Generator:
"""Generate random numbers from different distribtions self.uniform(size=size) creates standard uniform random numbers."""
def exponential(self, tau, size=None):
"""Draw exponentially distributed random numbers. Blatt 3, Aufgabe 2a)"""
u = self.uniform(size=size)
values... | the_stack_v2_python_sparse | Blatt05/Blatt05_Mang_Rezik_Scheugenpflug/random.py | yungsalami/linuxtest | train | 0 |
0bc268e0959ebd52db661aadc09388190f61175c | [
"super(Linker, self).__init__()\nself.config = config\nself.encoder = encoder\nself.entity_embeddings = nn.Embedding(self.config.entity_size, self.config.embedding_dim)\nif self.config.priors:\n self.char_feature_weight = nn.Parameter(torch.FloatTensor([1]))\n self.model_feature_weight = nn.Parameter(torch.Fl... | <|body_start_0|>
super(Linker, self).__init__()
self.config = config
self.encoder = encoder
self.entity_embeddings = nn.Embedding(self.config.entity_size, self.config.embedding_dim)
if self.config.priors:
self.char_feature_weight = nn.Parameter(torch.FloatTensor([1]))... | Linker | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Linker:
def __init__(self, config, encoder):
""":param config: A config object that specifies the hyperparameters of the model :param encoder: A Encoder for encoding mentions"""
<|body_0|>
def forward(self, entity_candidates, mention_representation, sentence, char_scores, au... | stack_v2_sparse_classes_36k_train_005544 | 42,719 | permissive | [
{
"docstring": ":param config: A config object that specifies the hyperparameters of the model :param encoder: A Encoder for encoding mentions",
"name": "__init__",
"signature": "def __init__(self, config, encoder)"
},
{
"docstring": ":return: unnormalized log probabilities (logits) of gold enti... | 2 | stack_v2_sparse_classes_30k_train_015992 | Implement the Python class `Linker` described below.
Class description:
Implement the Linker class.
Method signatures and docstrings:
- def __init__(self, config, encoder): :param config: A config object that specifies the hyperparameters of the model :param encoder: A Encoder for encoding mentions
- def forward(self... | Implement the Python class `Linker` described below.
Class description:
Implement the Linker class.
Method signatures and docstrings:
- def __init__(self, config, encoder): :param config: A config object that specifies the hyperparameters of the model :param encoder: A Encoder for encoding mentions
- def forward(self... | 6a7dcd7d3756327c61ef949e5b4f6af6e2849187 | <|skeleton|>
class Linker:
def __init__(self, config, encoder):
""":param config: A config object that specifies the hyperparameters of the model :param encoder: A Encoder for encoding mentions"""
<|body_0|>
def forward(self, entity_candidates, mention_representation, sentence, char_scores, au... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Linker:
def __init__(self, config, encoder):
""":param config: A config object that specifies the hyperparameters of the model :param encoder: A Encoder for encoding mentions"""
super(Linker, self).__init__()
self.config = config
self.encoder = encoder
self.entity_embed... | the_stack_v2_python_sparse | typenet/src/model.py | dhruvdcoder/dl-with-constraints | train | 0 | |
f55a9e9b1450b6336add72e8bc38bb2163c22517 | [
"data = np.ones((3, 3, 3), dtype=np.float32)\nthreshold_points = np.array([276, 277, 278], dtype=np.float32)\nself.cube = set_up_probability_cube(data, threshold_points)\nself.cube.rename('probability_of_X_above_threshold')",
"correct_name_above = 'probability_of_X_in_vicinity_above_threshold'\nnew_name_above = i... | <|body_start_0|>
data = np.ones((3, 3, 3), dtype=np.float32)
threshold_points = np.array([276, 277, 278], dtype=np.float32)
self.cube = set_up_probability_cube(data, threshold_points)
self.cube.rename('probability_of_X_above_threshold')
<|end_body_0|>
<|body_start_1|>
correct_na... | Test that the 'in_vicinity' above/below threshold probability cube naming function produces the correctly formatted names. | Test_in_vicinity_name_format | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_in_vicinity_name_format:
"""Test that the 'in_vicinity' above/below threshold probability cube naming function produces the correctly formatted names."""
def setUp(self):
"""Set up test cube"""
<|body_0|>
def test_in_vicinity_name_format(self):
"""Test that ... | stack_v2_sparse_classes_36k_train_005545 | 19,394 | permissive | [
{
"docstring": "Set up test cube",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test that 'in_vicinity' is added correctly to the name for both above and below threshold cases",
"name": "test_in_vicinity_name_format",
"signature": "def test_in_vicinity_name_format(s... | 5 | stack_v2_sparse_classes_30k_train_011334 | Implement the Python class `Test_in_vicinity_name_format` described below.
Class description:
Test that the 'in_vicinity' above/below threshold probability cube naming function produces the correctly formatted names.
Method signatures and docstrings:
- def setUp(self): Set up test cube
- def test_in_vicinity_name_for... | Implement the Python class `Test_in_vicinity_name_format` described below.
Class description:
Test that the 'in_vicinity' above/below threshold probability cube naming function produces the correctly formatted names.
Method signatures and docstrings:
- def setUp(self): Set up test cube
- def test_in_vicinity_name_for... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_in_vicinity_name_format:
"""Test that the 'in_vicinity' above/below threshold probability cube naming function produces the correctly formatted names."""
def setUp(self):
"""Set up test cube"""
<|body_0|>
def test_in_vicinity_name_format(self):
"""Test that ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_in_vicinity_name_format:
"""Test that the 'in_vicinity' above/below threshold probability cube naming function produces the correctly formatted names."""
def setUp(self):
"""Set up test cube"""
data = np.ones((3, 3, 3), dtype=np.float32)
threshold_points = np.array([276, 277,... | the_stack_v2_python_sparse | improver_tests/metadata/test_probabilistic.py | metoppv/improver | train | 101 |
dd511a79c49f7b0e1dc953e36b6bd7b1d2c96be4 | [
"if n in [0, 1]:\n return []\nif n in [2, 3]:\n return [n]\nresult = [2, 3]\nfor each in range(4, n, 1):\n prime = True\n for i in range(2, each - 1):\n if each % i == 0:\n prime = False\n break\n if prime:\n result.append(each)\nreturn result",
"if n in [0, 1]:\... | <|body_start_0|>
if n in [0, 1]:
return []
if n in [2, 3]:
return [n]
result = [2, 3]
for each in range(4, n, 1):
prime = True
for i in range(2, each - 1):
if each % i == 0:
prime = False
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def enumeratePrimes(self, n):
""":type n: int :rtype: list of int"""
<|body_0|>
def enumeratePrimes_1(self, n):
""":type n: int :rtype: list of int"""
<|body_1|>
def enumeratePrimes_2(self, n):
""":type n: int :rtype: list of int"""
... | stack_v2_sparse_classes_36k_train_005546 | 2,243 | no_license | [
{
"docstring": ":type n: int :rtype: list of int",
"name": "enumeratePrimes",
"signature": "def enumeratePrimes(self, n)"
},
{
"docstring": ":type n: int :rtype: list of int",
"name": "enumeratePrimes_1",
"signature": "def enumeratePrimes_1(self, n)"
},
{
"docstring": ":type n: i... | 3 | stack_v2_sparse_classes_30k_train_021325 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def enumeratePrimes(self, n): :type n: int :rtype: list of int
- def enumeratePrimes_1(self, n): :type n: int :rtype: list of int
- def enumeratePrimes_2(self, n): :type n: int :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def enumeratePrimes(self, n): :type n: int :rtype: list of int
- def enumeratePrimes_1(self, n): :type n: int :rtype: list of int
- def enumeratePrimes_2(self, n): :type n: int :... | ec48cbde4356208afac226d41752daffe674be2c | <|skeleton|>
class Solution:
def enumeratePrimes(self, n):
""":type n: int :rtype: list of int"""
<|body_0|>
def enumeratePrimes_1(self, n):
""":type n: int :rtype: list of int"""
<|body_1|>
def enumeratePrimes_2(self, n):
""":type n: int :rtype: list of int"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def enumeratePrimes(self, n):
""":type n: int :rtype: list of int"""
if n in [0, 1]:
return []
if n in [2, 3]:
return [n]
result = [2, 3]
for each in range(4, n, 1):
prime = True
for i in range(2, each - 1):
... | the_stack_v2_python_sparse | B2BSWE/Arrays/all_primes_to_n.py | librar127/PythonDS | train | 0 | |
f9189ca19fe6494edb76093fd218334267bac49d | [
"args = ['strace', '-o', output_file, '-p', str(os.getpid())]\nprint(args)\nself._strace_process = subprocess.Popen(args)\nstart_time = time.time()\nwhile time.time() - start_time < self.STRACE_TIMEOUT:\n if os.path.isfile(output_file) and open(output_file).read(1):\n return True\n time.sleep(1)\nretur... | <|body_start_0|>
args = ['strace', '-o', output_file, '-p', str(os.getpid())]
print(args)
self._strace_process = subprocess.Popen(args)
start_time = time.time()
while time.time() - start_time < self.STRACE_TIMEOUT:
if os.path.isfile(output_file) and open(output_file).... | Test to ensure we're not touching /dev/ptmx when running commands. | NoPsuedoTerminalTest | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoPsuedoTerminalTest:
"""Test to ensure we're not touching /dev/ptmx when running commands."""
def _AttachStraceToSelf(self, output_file):
"""Attaches strace to the current process."""
<|body_0|>
def _KillStraceProcess(self):
"""Kills strace that was started by _... | stack_v2_sparse_classes_36k_train_005547 | 1,552 | permissive | [
{
"docstring": "Attaches strace to the current process.",
"name": "_AttachStraceToSelf",
"signature": "def _AttachStraceToSelf(self, output_file)"
},
{
"docstring": "Kills strace that was started by _AttachStraceToSelf().",
"name": "_KillStraceProcess",
"signature": "def _KillStraceProce... | 3 | null | Implement the Python class `NoPsuedoTerminalTest` described below.
Class description:
Test to ensure we're not touching /dev/ptmx when running commands.
Method signatures and docstrings:
- def _AttachStraceToSelf(self, output_file): Attaches strace to the current process.
- def _KillStraceProcess(self): Kills strace ... | Implement the Python class `NoPsuedoTerminalTest` described below.
Class description:
Test to ensure we're not touching /dev/ptmx when running commands.
Method signatures and docstrings:
- def _AttachStraceToSelf(self, output_file): Attaches strace to the current process.
- def _KillStraceProcess(self): Kills strace ... | e2745b756317aac3c7a27a4c10bdfe0921a82a1c | <|skeleton|>
class NoPsuedoTerminalTest:
"""Test to ensure we're not touching /dev/ptmx when running commands."""
def _AttachStraceToSelf(self, output_file):
"""Attaches strace to the current process."""
<|body_0|>
def _KillStraceProcess(self):
"""Kills strace that was started by _... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NoPsuedoTerminalTest:
"""Test to ensure we're not touching /dev/ptmx when running commands."""
def _AttachStraceToSelf(self, output_file):
"""Attaches strace to the current process."""
args = ['strace', '-o', output_file, '-p', str(os.getpid())]
print(args)
self._strace_pr... | the_stack_v2_python_sparse | app/src/main/java/com/syd/source/aosp/external/toolchain-utils/cros_utils/no_pseudo_terminal_test.py | lz-purple/Source | train | 4 |
9a9a228bed751d8dece14bb3c71066c9e1ccae0f | [
"if not head or not head.next:\n return head\npre = None\ncurr = head\nwhile curr:\n temp = curr.next\n curr.next = pre\n pre = curr\n curr = temp\nreturn pre",
"pre, pre.next = (None, head)\nwhile pre.next and pre.next.next:\n a = pre.next\n b = a.next\n pre.next, b.next, a.next = (b, a, ... | <|body_start_0|>
if not head or not head.next:
return head
pre = None
curr = head
while curr:
temp = curr.next
curr.next = pre
pre = curr
curr = temp
return pre
<|end_body_0|>
<|body_start_1|>
pre, pre.next = (N... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse_list(head):
"""链表反转 :type head: ListNode :rtype: ListNode"""
<|body_0|>
def swap_paris(head):
"""链表交换相邻元素 1->2->3->4 2->1->4->3 :type head: ListNode :rtype: ListNode"""
<|body_1|>
def has_cycle(head):
"""判断链表是否有环 :param head... | stack_v2_sparse_classes_36k_train_005548 | 1,711 | no_license | [
{
"docstring": "链表反转 :type head: ListNode :rtype: ListNode",
"name": "reverse_list",
"signature": "def reverse_list(head)"
},
{
"docstring": "链表交换相邻元素 1->2->3->4 2->1->4->3 :type head: ListNode :rtype: ListNode",
"name": "swap_paris",
"signature": "def swap_paris(head)"
},
{
"doc... | 4 | stack_v2_sparse_classes_30k_train_013365 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse_list(head): 链表反转 :type head: ListNode :rtype: ListNode
- def swap_paris(head): 链表交换相邻元素 1->2->3->4 2->1->4->3 :type head: ListNode :rtype: ListNode
- def has_cycle(he... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse_list(head): 链表反转 :type head: ListNode :rtype: ListNode
- def swap_paris(head): 链表交换相邻元素 1->2->3->4 2->1->4->3 :type head: ListNode :rtype: ListNode
- def has_cycle(he... | 76f4990bf6e2168cbe1336e17621018f82f99a68 | <|skeleton|>
class Solution:
def reverse_list(head):
"""链表反转 :type head: ListNode :rtype: ListNode"""
<|body_0|>
def swap_paris(head):
"""链表交换相邻元素 1->2->3->4 2->1->4->3 :type head: ListNode :rtype: ListNode"""
<|body_1|>
def has_cycle(head):
"""判断链表是否有环 :param head... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverse_list(head):
"""链表反转 :type head: ListNode :rtype: ListNode"""
if not head or not head.next:
return head
pre = None
curr = head
while curr:
temp = curr.next
curr.next = pre
pre = curr
curr =... | the_stack_v2_python_sparse | datastruct/LinkedList.py | xiaoqiangjava/python_basic | train | 0 | |
92a26ea192637dcdf422b462a446a22806887140 | [
"super().__init__()\nself.image_conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels // 2, **kwargs)\nself.kspace_conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels // 2, **kwargs)\nself.forward_operator = forward_operator\nself.backward_operator = backward_operator\nself._channels_d... | <|body_start_0|>
super().__init__()
self.image_conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels // 2, **kwargs)
self.kspace_conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels // 2, **kwargs)
self.forward_operator = forward_operator
self.backwar... | MultiDomainConv2d | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiDomainConv2d:
def __init__(self, forward_operator: Callable, backward_operator: Callable, in_channels: int, out_channels: int, **kwargs):
"""Inits :class:`MultiDomainConv2d`. Parameters ---------- forward_operator: Callable Forward Operator. backward_operator: Callable Backward Oper... | stack_v2_sparse_classes_36k_train_005549 | 11,794 | permissive | [
{
"docstring": "Inits :class:`MultiDomainConv2d`. Parameters ---------- forward_operator: Callable Forward Operator. backward_operator: Callable Backward Operator. in_channels: int Number of input channels. out_channels: int Number of output channels.",
"name": "__init__",
"signature": "def __init__(sel... | 2 | stack_v2_sparse_classes_30k_train_009604 | Implement the Python class `MultiDomainConv2d` described below.
Class description:
Implement the MultiDomainConv2d class.
Method signatures and docstrings:
- def __init__(self, forward_operator: Callable, backward_operator: Callable, in_channels: int, out_channels: int, **kwargs): Inits :class:`MultiDomainConv2d`. Pa... | Implement the Python class `MultiDomainConv2d` described below.
Class description:
Implement the MultiDomainConv2d class.
Method signatures and docstrings:
- def __init__(self, forward_operator: Callable, backward_operator: Callable, in_channels: int, out_channels: int, **kwargs): Inits :class:`MultiDomainConv2d`. Pa... | 2a4c29342bc52a404aae097bc2654fb4323e1ac8 | <|skeleton|>
class MultiDomainConv2d:
def __init__(self, forward_operator: Callable, backward_operator: Callable, in_channels: int, out_channels: int, **kwargs):
"""Inits :class:`MultiDomainConv2d`. Parameters ---------- forward_operator: Callable Forward Operator. backward_operator: Callable Backward Oper... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiDomainConv2d:
def __init__(self, forward_operator: Callable, backward_operator: Callable, in_channels: int, out_channels: int, **kwargs):
"""Inits :class:`MultiDomainConv2d`. Parameters ---------- forward_operator: Callable Forward Operator. backward_operator: Callable Backward Operator. in_chann... | the_stack_v2_python_sparse | direct/nn/multidomainnet/multidomain.py | NKI-AI/direct | train | 151 | |
994fb26d37c2679640f432a2acba33c6047c2574 | [
"self.account_sid = os.environ.get('TWILIO_ACCOUNT_SID', '')\nself.auth_token = os.environ.get('TWILIO_AUTH_TOKEN', '')\nif not self.account_sid and (not self.auth_token):\n logging.warning(WARNING_MESSAGE)\n return\nself.client = Client(self.account_sid, self.auth_token)",
"if not self.account_sid and (not... | <|body_start_0|>
self.account_sid = os.environ.get('TWILIO_ACCOUNT_SID', '')
self.auth_token = os.environ.get('TWILIO_AUTH_TOKEN', '')
if not self.account_sid and (not self.auth_token):
logging.warning(WARNING_MESSAGE)
return
self.client = Client(self.account_sid,... | Base twilio service. | TwilioService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwilioService:
"""Base twilio service."""
def __init__(self):
"""Initialize twilio service; Instanciate Client object."""
<|body_0|>
def phone_lookup(self, phone):
"""Verify the give phone number."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_005550 | 1,145 | no_license | [
{
"docstring": "Initialize twilio service; Instanciate Client object.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Verify the give phone number.",
"name": "phone_lookup",
"signature": "def phone_lookup(self, phone)"
}
] | 2 | null | Implement the Python class `TwilioService` described below.
Class description:
Base twilio service.
Method signatures and docstrings:
- def __init__(self): Initialize twilio service; Instanciate Client object.
- def phone_lookup(self, phone): Verify the give phone number. | Implement the Python class `TwilioService` described below.
Class description:
Base twilio service.
Method signatures and docstrings:
- def __init__(self): Initialize twilio service; Instanciate Client object.
- def phone_lookup(self, phone): Verify the give phone number.
<|skeleton|>
class TwilioService:
"""Bas... | 252b0ebd77eefbcc945a0efc3068cc3421f46d5f | <|skeleton|>
class TwilioService:
"""Base twilio service."""
def __init__(self):
"""Initialize twilio service; Instanciate Client object."""
<|body_0|>
def phone_lookup(self, phone):
"""Verify the give phone number."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TwilioService:
"""Base twilio service."""
def __init__(self):
"""Initialize twilio service; Instanciate Client object."""
self.account_sid = os.environ.get('TWILIO_ACCOUNT_SID', '')
self.auth_token = os.environ.get('TWILIO_AUTH_TOKEN', '')
if not self.account_sid and (not ... | the_stack_v2_python_sparse | common/services/twilio_service.py | vsokoltsov/Interview360Server | train | 2 |
cdbed7e802fbe8b7231cb6897724796fc36d5bf9 | [
"self.circuit = circuit\nself.num_qubits = num_qubits\nself.qubit_list = LineQubit.range(num_qubits)\nif noise_dict is None:\n noise_dict = get_default_noise_dict()\nself.noise_dict = noise_dict\nself.simulate_ideal = simulate_ideal",
"self.circuit = Circuit()\njson_obj = json.loads(json_string)\ngate: Union[o... | <|body_start_0|>
self.circuit = circuit
self.num_qubits = num_qubits
self.qubit_list = LineQubit.range(num_qubits)
if noise_dict is None:
noise_dict = get_default_noise_dict()
self.noise_dict = noise_dict
self.simulate_ideal = simulate_ideal
<|end_body_0|>
<|... | A simulator for the AQT device. | AQTSimulator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AQTSimulator:
"""A simulator for the AQT device."""
def __init__(self, num_qubits: int, circuit: Circuit=Circuit(), simulate_ideal: bool=False, noise_dict: Union[dict, None]=None):
"""Initializes the AQT simulator Args: num_qubits: Number of qubits circuit: Optional, circuit to be si... | stack_v2_sparse_classes_36k_train_005551 | 9,285 | permissive | [
{
"docstring": "Initializes the AQT simulator Args: num_qubits: Number of qubits circuit: Optional, circuit to be simulated. Last moment needs to be a measurement over all qubits with key 'm' simulate_ideal: If True, an ideal circuit will be simulated",
"name": "__init__",
"signature": "def __init__(sel... | 3 | null | Implement the Python class `AQTSimulator` described below.
Class description:
A simulator for the AQT device.
Method signatures and docstrings:
- def __init__(self, num_qubits: int, circuit: Circuit=Circuit(), simulate_ideal: bool=False, noise_dict: Union[dict, None]=None): Initializes the AQT simulator Args: num_qub... | Implement the Python class `AQTSimulator` described below.
Class description:
A simulator for the AQT device.
Method signatures and docstrings:
- def __init__(self, num_qubits: int, circuit: Circuit=Circuit(), simulate_ideal: bool=False, noise_dict: Union[dict, None]=None): Initializes the AQT simulator Args: num_qub... | a3afa13f60160e014512a89abd85f10118047f0d | <|skeleton|>
class AQTSimulator:
"""A simulator for the AQT device."""
def __init__(self, num_qubits: int, circuit: Circuit=Circuit(), simulate_ideal: bool=False, noise_dict: Union[dict, None]=None):
"""Initializes the AQT simulator Args: num_qubits: Number of qubits circuit: Optional, circuit to be si... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AQTSimulator:
"""A simulator for the AQT device."""
def __init__(self, num_qubits: int, circuit: Circuit=Circuit(), simulate_ideal: bool=False, noise_dict: Union[dict, None]=None):
"""Initializes the AQT simulator Args: num_qubits: Number of qubits circuit: Optional, circuit to be simulated. Last... | the_stack_v2_python_sparse | cirq/aqt/aqt_device.py | shaswata56/Cirq | train | 3 |
d5b242a2421f4083a2228db54f07edd91e085105 | [
"self.buffer.seek(0)\ndata = self.buffer.getvalue()\ndata_chunks = [data[start:end] for start, end in self._to_sized_blocks(end=len(data))]\nfor data_chunk in data_chunks:\n self.fs._add_data(handle=self.handle, data=data_chunk)\nif final:\n self.fs._close_handle(handle=self.handle)\n return True",
"retu... | <|body_start_0|>
self.buffer.seek(0)
data = self.buffer.getvalue()
data_chunks = [data[start:end] for start, end in self._to_sized_blocks(end=len(data))]
for data_chunk in data_chunks:
self.fs._add_data(handle=self.handle, data=data_chunk)
if final:
self.f... | Overrides DatabricksFile to add the following fix: https://github.com/fsspec/filesystem_spec/pull/1278 | DatabricksFileBugFixed | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatabricksFileBugFixed:
"""Overrides DatabricksFile to add the following fix: https://github.com/fsspec/filesystem_spec/pull/1278"""
def _upload_chunk(self, final=False):
"""Internal function to add a chunk of data to a started upload"""
<|body_0|>
def _fetch_range(self,... | stack_v2_sparse_classes_36k_train_005552 | 6,526 | permissive | [
{
"docstring": "Internal function to add a chunk of data to a started upload",
"name": "_upload_chunk",
"signature": "def _upload_chunk(self, final=False)"
},
{
"docstring": "Internal function to download a block of data",
"name": "_fetch_range",
"signature": "def _fetch_range(self, star... | 3 | null | Implement the Python class `DatabricksFileBugFixed` described below.
Class description:
Overrides DatabricksFile to add the following fix: https://github.com/fsspec/filesystem_spec/pull/1278
Method signatures and docstrings:
- def _upload_chunk(self, final=False): Internal function to add a chunk of data to a started... | Implement the Python class `DatabricksFileBugFixed` described below.
Class description:
Overrides DatabricksFile to add the following fix: https://github.com/fsspec/filesystem_spec/pull/1278
Method signatures and docstrings:
- def _upload_chunk(self, final=False): Internal function to add a chunk of data to a started... | b5fe0c05ae7f5818a4a5a5a40245c851ff9b2c77 | <|skeleton|>
class DatabricksFileBugFixed:
"""Overrides DatabricksFile to add the following fix: https://github.com/fsspec/filesystem_spec/pull/1278"""
def _upload_chunk(self, final=False):
"""Internal function to add a chunk of data to a started upload"""
<|body_0|>
def _fetch_range(self,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DatabricksFileBugFixed:
"""Overrides DatabricksFile to add the following fix: https://github.com/fsspec/filesystem_spec/pull/1278"""
def _upload_chunk(self, final=False):
"""Internal function to add a chunk of data to a started upload"""
self.buffer.seek(0)
data = self.buffer.getv... | the_stack_v2_python_sparse | mlrun/datastore/dbfs_store.py | mlrun/mlrun | train | 1,093 |
3dc01d0aea014a13affd7c161978a87343a9ac3b | [
"matrix.reverse()\nfor i in range(len(matrix)):\n for j in range(i):\n matrix[i][j], matrix[j][i] = (matrix[j][i], matrix[i][j])",
"for i in range(len(matrix)):\n for j in range(i):\n matrix[i][j], matrix[j][i] = (matrix[j][i], matrix[i][j])\nmatrix.reverse()"
] | <|body_start_0|>
matrix.reverse()
for i in range(len(matrix)):
for j in range(i):
matrix[i][j], matrix[j][i] = (matrix[j][i], matrix[i][j])
<|end_body_0|>
<|body_start_1|>
for i in range(len(matrix)):
for j in range(i):
matrix[i][j], matri... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""clockwise rotate * first reverse up to down, then swap the symmetry * 1 2 3 7 8 9 7 4 1 * 4 5 6 => 4 5 6 => 8 5 2 * 7 8 9 1 2 3 9 6 3"""
<|body_0|>
def anti_rotate(self, matrix: List[List[int]]) -> None:
... | stack_v2_sparse_classes_36k_train_005553 | 1,189 | no_license | [
{
"docstring": "clockwise rotate * first reverse up to down, then swap the symmetry * 1 2 3 7 8 9 7 4 1 * 4 5 6 => 4 5 6 => 8 5 2 * 7 8 9 1 2 3 9 6 3",
"name": "rotate",
"signature": "def rotate(self, matrix: List[List[int]]) -> None"
},
{
"docstring": "anti-clockwise rotate * first swap the sym... | 2 | stack_v2_sparse_classes_30k_train_001178 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, matrix: List[List[int]]) -> None: clockwise rotate * first reverse up to down, then swap the symmetry * 1 2 3 7 8 9 7 4 1 * 4 5 6 => 4 5 6 => 8 5 2 * 7 8 9 1 2 3... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, matrix: List[List[int]]) -> None: clockwise rotate * first reverse up to down, then swap the symmetry * 1 2 3 7 8 9 7 4 1 * 4 5 6 => 4 5 6 => 8 5 2 * 7 8 9 1 2 3... | 73654b6567fdb282af84a868608929be234075c5 | <|skeleton|>
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""clockwise rotate * first reverse up to down, then swap the symmetry * 1 2 3 7 8 9 7 4 1 * 4 5 6 => 4 5 6 => 8 5 2 * 7 8 9 1 2 3 9 6 3"""
<|body_0|>
def anti_rotate(self, matrix: List[List[int]]) -> None:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""clockwise rotate * first reverse up to down, then swap the symmetry * 1 2 3 7 8 9 7 4 1 * 4 5 6 => 4 5 6 => 8 5 2 * 7 8 9 1 2 3 9 6 3"""
matrix.reverse()
for i in range(len(matrix)):
for j in range(i):
... | the_stack_v2_python_sparse | LeetCode/0048-Rotate image/main.py | PRKKILLER/Algorithm_Practice | train | 0 | |
5f3b847e745a3c64fadb3a9a382b8cd5349edb79 | [
"super().setUp()\nalt_part = Part.objects.create(name='alt part', description='An alternative part!', component=True)\nBomItemSubstitute.objects.create(bom_item=self.bom_item_2, part=alt_part)\nStockItem.objects.create(part=alt_part, quantity=500)",
"self.assertEqual(self.build.allocated_stock.count(), 0)\nself.a... | <|body_start_0|>
super().setUp()
alt_part = Part.objects.create(name='alt part', description='An alternative part!', component=True)
BomItemSubstitute.objects.create(bom_item=self.bom_item_2, part=alt_part)
StockItem.objects.create(part=alt_part, quantity=500)
<|end_body_0|>
<|body_star... | Tests for auto allocating stock against a build order | AutoAllocationTests | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoAllocationTests:
"""Tests for auto allocating stock against a build order"""
def setUp(self):
"""Init routines for this unit test class"""
<|body_0|>
def test_auto_allocate(self):
"""Run the 'auto-allocate' function. What do we expect to happen? There are two... | stack_v2_sparse_classes_36k_train_005554 | 22,452 | permissive | [
{
"docstring": "Init routines for this unit test class",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Run the 'auto-allocate' function. What do we expect to happen? There are two \"untracked\" parts: - sub_part_1 (quantity 5 per BOM = 50 required total) / 103 in stock (2 it... | 3 | null | Implement the Python class `AutoAllocationTests` described below.
Class description:
Tests for auto allocating stock against a build order
Method signatures and docstrings:
- def setUp(self): Init routines for this unit test class
- def test_auto_allocate(self): Run the 'auto-allocate' function. What do we expect to ... | Implement the Python class `AutoAllocationTests` described below.
Class description:
Tests for auto allocating stock against a build order
Method signatures and docstrings:
- def setUp(self): Init routines for this unit test class
- def test_auto_allocate(self): Run the 'auto-allocate' function. What do we expect to ... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class AutoAllocationTests:
"""Tests for auto allocating stock against a build order"""
def setUp(self):
"""Init routines for this unit test class"""
<|body_0|>
def test_auto_allocate(self):
"""Run the 'auto-allocate' function. What do we expect to happen? There are two... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutoAllocationTests:
"""Tests for auto allocating stock against a build order"""
def setUp(self):
"""Init routines for this unit test class"""
super().setUp()
alt_part = Part.objects.create(name='alt part', description='An alternative part!', component=True)
BomItemSubstit... | the_stack_v2_python_sparse | InvenTree/build/test_build.py | inventree/InvenTree | train | 3,077 |
0a099600e608780a77344ff4fd25ed3197912b91 | [
"if week_parity.upper() == 'ЧЕТНАЯ' or str(week_parity) == '0':\n week = 'чет'\nelif week_parity.upper() == 'НЕЧЕТНАЯ' or str(week_parity) == '1':\n week = 'нечет'\nelse:\n return 'Не правильно введана четность недели. Простите! Возможно, это ошибка программы...Пожалуйста, сообщите моему создателю.'\nf = o... | <|body_start_0|>
if week_parity.upper() == 'ЧЕТНАЯ' or str(week_parity) == '0':
week = 'чет'
elif week_parity.upper() == 'НЕЧЕТНАЯ' or str(week_parity) == '1':
week = 'нечет'
else:
return 'Не правильно введана четность недели. Простите! Возможно, это ошибка пр... | ScheduleFromFile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScheduleFromFile:
def get_schedule_from_file(filename, day, week_parity):
""":param filename: путь к файлу с расписанием . Формат файла: (1 строка - Заголовок расписания, возвращается как первая строка 2 строка - указание названий столбцов (необязательно, но строка должна быть) С третьег... | stack_v2_sparse_classes_36k_train_005555 | 2,911 | no_license | [
{
"docstring": ":param filename: путь к файлу с расписанием . Формат файла: (1 строка - Заголовок расписания, возвращается как первая строка 2 строка - указание названий столбцов (необязательно, но строка должна быть) С третьего начинаются дни с парами в формате: <День недели> <Время> <четность недели> <аудитор... | 2 | stack_v2_sparse_classes_30k_test_000225 | Implement the Python class `ScheduleFromFile` described below.
Class description:
Implement the ScheduleFromFile class.
Method signatures and docstrings:
- def get_schedule_from_file(filename, day, week_parity): :param filename: путь к файлу с расписанием . Формат файла: (1 строка - Заголовок расписания, возвращается... | Implement the Python class `ScheduleFromFile` described below.
Class description:
Implement the ScheduleFromFile class.
Method signatures and docstrings:
- def get_schedule_from_file(filename, day, week_parity): :param filename: путь к файлу с расписанием . Формат файла: (1 строка - Заголовок расписания, возвращается... | ea15b419f6213edf69f10b4999872ec02057b23d | <|skeleton|>
class ScheduleFromFile:
def get_schedule_from_file(filename, day, week_parity):
""":param filename: путь к файлу с расписанием . Формат файла: (1 строка - Заголовок расписания, возвращается как первая строка 2 строка - указание названий столбцов (необязательно, но строка должна быть) С третьег... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScheduleFromFile:
def get_schedule_from_file(filename, day, week_parity):
""":param filename: путь к файлу с расписанием . Формат файла: (1 строка - Заголовок расписания, возвращается как первая строка 2 строка - указание названий столбцов (необязательно, но строка должна быть) С третьего начинаются д... | the_stack_v2_python_sparse | vk-bot YALICEUM/Bot/schedule/schedule_from_file.py | Amir227/TheLastProject3 | train | 0 | |
9a6fa7c5100e41174a26548a9a962b1e82c30ae2 | [
"super().__init__(source=path)\nself.path = path\ntry:\n self.config.read(path)\nexcept configparser.ParsingError as e:\n raise ValidationError('%s: %s' % (path, e)) from e\nself._validate()",
"for path in paths:\n path = os.path.join(path, cls.FILENAME)\n if os.path.exists(path):\n yield cls(p... | <|body_start_0|>
super().__init__(source=path)
self.path = path
try:
self.config.read(path)
except configparser.ParsingError as e:
raise ValidationError('%s: %s' % (path, e)) from e
self._validate()
<|end_body_0|>
<|body_start_1|>
for path in path... | A single config (file) used for `repo upload` hooks. This is an abstract class that requires subclasses to define the FILENAME constant. Attributes: path: The path of the file. | PreUploadFile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreUploadFile:
"""A single config (file) used for `repo upload` hooks. This is an abstract class that requires subclasses to define the FILENAME constant. Attributes: path: The path of the file."""
def __init__(self, path):
"""Initialize. Args: path: The config file to load."""
... | stack_v2_sparse_classes_36k_train_005556 | 11,838 | no_license | [
{
"docstring": "Initialize. Args: path: The config file to load.",
"name": "__init__",
"signature": "def __init__(self, path)"
},
{
"docstring": "Search for files within paths that matches the class FILENAME. Args: paths: List of directories to look for config files. Yields: For each valid file ... | 2 | null | Implement the Python class `PreUploadFile` described below.
Class description:
A single config (file) used for `repo upload` hooks. This is an abstract class that requires subclasses to define the FILENAME constant. Attributes: path: The path of the file.
Method signatures and docstrings:
- def __init__(self, path): ... | Implement the Python class `PreUploadFile` described below.
Class description:
A single config (file) used for `repo upload` hooks. This is an abstract class that requires subclasses to define the FILENAME constant. Attributes: path: The path of the file.
Method signatures and docstrings:
- def __init__(self, path): ... | 78a61ca023cbf1a0cecfef8b97df2b274ac3a988 | <|skeleton|>
class PreUploadFile:
"""A single config (file) used for `repo upload` hooks. This is an abstract class that requires subclasses to define the FILENAME constant. Attributes: path: The path of the file."""
def __init__(self, path):
"""Initialize. Args: path: The config file to load."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PreUploadFile:
"""A single config (file) used for `repo upload` hooks. This is an abstract class that requires subclasses to define the FILENAME constant. Attributes: path: The path of the file."""
def __init__(self, path):
"""Initialize. Args: path: The config file to load."""
super().__... | the_stack_v2_python_sparse | tools/repohooks/rh/config.py | ZYHGOD-1/Aosp11 | train | 0 |
3338c146779a475893c9cc89ce3d8e9dbd3ca209 | [
"data_indices = output_dict['data_idx']\npred_logits = output_dict['logits']\npred_class_idxs = torch.argmax(pred_logits, dim=-1)\npredictions = {self._dataset.get_id(data_idx.item()): {'class_idx': pred_class_idx.item()} for data_idx, pred_class_idx in zip(list(data_indices.data), list(pred_class_idxs.data))}\nret... | <|body_start_0|>
data_indices = output_dict['data_idx']
pred_logits = output_dict['logits']
pred_class_idxs = torch.argmax(pred_logits, dim=-1)
predictions = {self._dataset.get_id(data_idx.item()): {'class_idx': pred_class_idx.item()} for data_idx, pred_class_idx in zip(list(data_indices... | Sequence Classification Mixin Class | SequenceClassification | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequenceClassification:
"""Sequence Classification Mixin Class"""
def make_predictions(self, output_dict):
"""Make predictions with model's output_dict * Args: output_dict: model's output dictionary consisting of - sequence_embed: embedding vector of the sequence - logits: representi... | stack_v2_sparse_classes_36k_train_005557 | 6,557 | permissive | [
{
"docstring": "Make predictions with model's output_dict * Args: output_dict: model's output dictionary consisting of - sequence_embed: embedding vector of the sequence - logits: representing unnormalized log probabilities of the class - class_idx: target class idx - data_idx: data idx - loss: a scalar loss to... | 5 | stack_v2_sparse_classes_30k_train_010885 | Implement the Python class `SequenceClassification` described below.
Class description:
Sequence Classification Mixin Class
Method signatures and docstrings:
- def make_predictions(self, output_dict): Make predictions with model's output_dict * Args: output_dict: model's output dictionary consisting of - sequence_emb... | Implement the Python class `SequenceClassification` described below.
Class description:
Sequence Classification Mixin Class
Method signatures and docstrings:
- def make_predictions(self, output_dict): Make predictions with model's output_dict * Args: output_dict: model's output dictionary consisting of - sequence_emb... | 89b3e5c5ec0486886876ea3bac381508c6a6bf58 | <|skeleton|>
class SequenceClassification:
"""Sequence Classification Mixin Class"""
def make_predictions(self, output_dict):
"""Make predictions with model's output_dict * Args: output_dict: model's output dictionary consisting of - sequence_embed: embedding vector of the sequence - logits: representi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SequenceClassification:
"""Sequence Classification Mixin Class"""
def make_predictions(self, output_dict):
"""Make predictions with model's output_dict * Args: output_dict: model's output dictionary consisting of - sequence_embed: embedding vector of the sequence - logits: representing unnormaliz... | the_stack_v2_python_sparse | claf/model/sequence_classification/mixin.py | srlee-ai/claf | train | 0 |
58084122f432a51e940bc912c977e4a59393de90 | [
"if root is None:\n return []\nqueue = [root]\ndata = []\n\ndef dfs():\n if queue == []:\n return\n node = queue.pop(0)\n data.append(node.val)\n if node.left:\n queue.append(node.left)\n dfs()\n else:\n data.append(None)\n if node.right:\n queue.append(node.r... | <|body_start_0|>
if root is None:
return []
queue = [root]
data = []
def dfs():
if queue == []:
return
node = queue.pop(0)
data.append(node.val)
if node.left:
queue.append(node.left)
... | Codec | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_005558 | 1,631 | permissive | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_015421 | 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:... | cdf785856941f7ea546aee56ebcda8801cbb04de | <|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 root is None:
return []
queue = [root]
data = []
def dfs():
if queue == []:
return
node = queue.pop(0)
... | the_stack_v2_python_sparse | ProgrammingQuestions/leetcode/297.py | strawsyz/straw | train | 2 | |
0f84d908c2fb2461c5b4ab6020352ada431397a0 | [
"res = super(account_voucher, self).proforma_voucher()\npurchase_rs = self.purchase_id\nif purchase_rs:\n purchase_rs.write({'check_paid': True})\n purchase_rs.picking_ids.write({'payment_lock': False})\nreturn res",
"partner_type_obj = self.env['res.partner.purchase.type']\nsearch_partner_ids = []\nnew_par... | <|body_start_0|>
res = super(account_voucher, self).proforma_voucher()
purchase_rs = self.purchase_id
if purchase_rs:
purchase_rs.write({'check_paid': True})
purchase_rs.picking_ids.write({'payment_lock': False})
return res
<|end_body_0|>
<|body_start_1|>
... | account_voucher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class account_voucher:
def proforma_voucher(self):
"""Surcharge pour prendre en compte la libération de l'achat et des pickings en cas de validation du paiement"""
<|body_0|>
def recompute_voucher_lines(self, partner_ids, journal_id, price, currency_id, ttype, date):
"""Su... | stack_v2_sparse_classes_36k_train_005559 | 5,566 | no_license | [
{
"docstring": "Surcharge pour prendre en compte la libération de l'achat et des pickings en cas de validation du paiement",
"name": "proforma_voucher",
"signature": "def proforma_voucher(self)"
},
{
"docstring": "Surcharge pour prendre en compte les partenaires facturés du partenaire payeur",
... | 2 | stack_v2_sparse_classes_30k_train_017295 | Implement the Python class `account_voucher` described below.
Class description:
Implement the account_voucher class.
Method signatures and docstrings:
- def proforma_voucher(self): Surcharge pour prendre en compte la libération de l'achat et des pickings en cas de validation du paiement
- def recompute_voucher_lines... | Implement the Python class `account_voucher` described below.
Class description:
Implement the account_voucher class.
Method signatures and docstrings:
- def proforma_voucher(self): Surcharge pour prendre en compte la libération de l'achat et des pickings en cas de validation du paiement
- def recompute_voucher_lines... | eb394e1f79ba1995da2dcd81adfdd511c22caff9 | <|skeleton|>
class account_voucher:
def proforma_voucher(self):
"""Surcharge pour prendre en compte la libération de l'achat et des pickings en cas de validation du paiement"""
<|body_0|>
def recompute_voucher_lines(self, partner_ids, journal_id, price, currency_id, ttype, date):
"""Su... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class account_voucher:
def proforma_voucher(self):
"""Surcharge pour prendre en compte la libération de l'achat et des pickings en cas de validation du paiement"""
res = super(account_voucher, self).proforma_voucher()
purchase_rs = self.purchase_id
if purchase_rs:
purchas... | the_stack_v2_python_sparse | OpenPROD/openprod-addons/purchase/account.py | kazacube-mziouadi/ceci | train | 0 | |
6ea6bdc86b1e9966be1f165390fa1bc94fbecf96 | [
"length = 0\nwhile root:\n length += 1\n root = root.next\nreturn length",
"if not root:\n return (None, None)\ncur = root\nnew_root = None\nwhile cur:\n if length == 1:\n new_root = cur.next\n cur.next = None\n break\n else:\n cur = cur.next\n length -= 1\nreturn (ro... | <|body_start_0|>
length = 0
while root:
length += 1
root = root.next
return length
<|end_body_0|>
<|body_start_1|>
if not root:
return (None, None)
cur = root
new_root = None
while cur:
if length == 1:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def get_length_of_linked_list(self, root):
""":type root: ListNode :rtype: int"""
<|body_0|>
def get_linked_list(self, root, length):
""":type root: ListNode :type length: int"""
<|body_1|>
def splitListToParts(self, root, k):
""":type ... | stack_v2_sparse_classes_36k_train_005560 | 1,527 | no_license | [
{
"docstring": ":type root: ListNode :rtype: int",
"name": "get_length_of_linked_list",
"signature": "def get_length_of_linked_list(self, root)"
},
{
"docstring": ":type root: ListNode :type length: int",
"name": "get_linked_list",
"signature": "def get_linked_list(self, root, length)"
... | 3 | stack_v2_sparse_classes_30k_train_016326 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_length_of_linked_list(self, root): :type root: ListNode :rtype: int
- def get_linked_list(self, root, length): :type root: ListNode :type length: int
- def splitListToPar... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_length_of_linked_list(self, root): :type root: ListNode :rtype: int
- def get_linked_list(self, root, length): :type root: ListNode :type length: int
- def splitListToPar... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def get_length_of_linked_list(self, root):
""":type root: ListNode :rtype: int"""
<|body_0|>
def get_linked_list(self, root, length):
""":type root: ListNode :type length: int"""
<|body_1|>
def splitListToParts(self, root, k):
""":type ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def get_length_of_linked_list(self, root):
""":type root: ListNode :rtype: int"""
length = 0
while root:
length += 1
root = root.next
return length
def get_linked_list(self, root, length):
""":type root: ListNode :type length: int"... | the_stack_v2_python_sparse | python/leetcode/725_Split_Linked_List_in_Parts.py | bobcaoge/my-code | train | 0 | |
9df0e1cef63f8f7da8828b4f8d6fb89512d7e368 | [
"size = len(nums)\nif not nums:\n return False\nif size == 1:\n return True\nq = [{0: nums[0]}]\nwhile q:\n temp = q.pop(0)\n for index, value in temp.items():\n for i in range(1, value + 1):\n if index + i == size - 1 and nums[index + i] == nums[-1]:\n return True\n ... | <|body_start_0|>
size = len(nums)
if not nums:
return False
if size == 1:
return True
q = [{0: nums[0]}]
while q:
temp = q.pop(0)
for index, value in temp.items():
for i in range(1, value + 1):
if... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canJump(self, nums: list) -> bool:
"""超时 :param nums: :return:"""
<|body_0|>
def canJump1(self, nums):
"""贪心算法 :param nums: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
size = len(nums)
if not nums:
retu... | stack_v2_sparse_classes_36k_train_005561 | 1,543 | no_license | [
{
"docstring": "超时 :param nums: :return:",
"name": "canJump",
"signature": "def canJump(self, nums: list) -> bool"
},
{
"docstring": "贪心算法 :param nums: :return:",
"name": "canJump1",
"signature": "def canJump1(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump(self, nums: list) -> bool: 超时 :param nums: :return:
- def canJump1(self, nums): 贪心算法 :param nums: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump(self, nums: list) -> bool: 超时 :param nums: :return:
- def canJump1(self, nums): 贪心算法 :param nums: :return:
<|skeleton|>
class Solution:
def canJump(self, nums: ... | 99f2c3181d7ed93981f6ab1072e2d7a12f22b830 | <|skeleton|>
class Solution:
def canJump(self, nums: list) -> bool:
"""超时 :param nums: :return:"""
<|body_0|>
def canJump1(self, nums):
"""贪心算法 :param nums: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canJump(self, nums: list) -> bool:
"""超时 :param nums: :return:"""
size = len(nums)
if not nums:
return False
if size == 1:
return True
q = [{0: nums[0]}]
while q:
temp = q.pop(0)
for index, value in t... | the_stack_v2_python_sparse | src/algorithm/greedy/canJump.py | superY-25/algorithm-learning | train | 2 | |
2eb0039c29170317fc716a61917e393bb9f11129 | [
"resources = weakref.WeakValueDictionary()\nself._resources = resources\nself.port_options = []\napp = tornado.web.Application([('.*', _ResourceHandler, dict(resources=self._resources))])\nsuper(_Provider, self).__init__(app)",
"sources = sum(map(bool, (content, filepath, handler)))\nif sources != 1:\n raise V... | <|body_start_0|>
resources = weakref.WeakValueDictionary()
self._resources = resources
self.port_options = []
app = tornado.web.Application([('.*', _ResourceHandler, dict(resources=self._resources))])
super(_Provider, self).__init__(app)
<|end_body_0|>
<|body_start_1|>
s... | Background server which can provide a set of resources. | _Provider | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Provider:
"""Background server which can provide a set of resources."""
def __init__(self):
"""Initialize the server with a ResourceHandler script."""
<|body_0|>
def create(self, content=None, filepath=None, handler=None, headers=None, extension=None, route=None):
... | stack_v2_sparse_classes_36k_train_005562 | 6,653 | permissive | [
{
"docstring": "Initialize the server with a ResourceHandler script.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Creates and provides a new resource to be served. Can only provide one of content, path, or handler. Args: content: The string or byte content to return... | 2 | stack_v2_sparse_classes_30k_train_012011 | Implement the Python class `_Provider` described below.
Class description:
Background server which can provide a set of resources.
Method signatures and docstrings:
- def __init__(self): Initialize the server with a ResourceHandler script.
- def create(self, content=None, filepath=None, handler=None, headers=None, ex... | Implement the Python class `_Provider` described below.
Class description:
Background server which can provide a set of resources.
Method signatures and docstrings:
- def __init__(self): Initialize the server with a ResourceHandler script.
- def create(self, content=None, filepath=None, handler=None, headers=None, ex... | f73520dc61e9fdddb62ac0ab1c897d81d893113d | <|skeleton|>
class _Provider:
"""Background server which can provide a set of resources."""
def __init__(self):
"""Initialize the server with a ResourceHandler script."""
<|body_0|>
def create(self, content=None, filepath=None, handler=None, headers=None, extension=None, route=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _Provider:
"""Background server which can provide a set of resources."""
def __init__(self):
"""Initialize the server with a ResourceHandler script."""
resources = weakref.WeakValueDictionary()
self._resources = resources
self.port_options = []
app = tornado.web.Ap... | the_stack_v2_python_sparse | google/colab/html/_provide.py | googlecolab/colabtools | train | 1,962 |
85945abf96e9e65965011588448b15a8942286ea | [
"self._data_access = data_access\nself._scenario_info = scenario_info\nself.backup_config = server_setup.PathConfig(server_setup.BACKUP_DATA_ROOT_DIR)\nself.server_config = server_setup.PathConfig(server_setup.DATA_ROOT_DIR)",
"print('--> Moving scenario input data to backup disk')\nsource = posixpath.join(self.s... | <|body_start_0|>
self._data_access = data_access
self._scenario_info = scenario_info
self.backup_config = server_setup.PathConfig(server_setup.BACKUP_DATA_ROOT_DIR)
self.server_config = server_setup.PathConfig(server_setup.DATA_ROOT_DIR)
<|end_body_0|>
<|body_start_1|>
print('--... | Back up scenario data to backup disk mounted on server. :param powersimdata.data_access.data_access.DataAccess data_access: data access object. :param dict scenario: scenario information. | BackUpDisk | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BackUpDisk:
"""Back up scenario data to backup disk mounted on server. :param powersimdata.data_access.data_access.DataAccess data_access: data access object. :param dict scenario: scenario information."""
def __init__(self, data_access, scenario_info):
"""Constructor."""
<|b... | stack_v2_sparse_classes_36k_train_005563 | 4,029 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, data_access, scenario_info)"
},
{
"docstring": "Moves input data.",
"name": "move_input_data",
"signature": "def move_input_data(self)"
},
{
"docstring": "Copies base profile",
"name": "copy_b... | 5 | stack_v2_sparse_classes_30k_train_020724 | Implement the Python class `BackUpDisk` described below.
Class description:
Back up scenario data to backup disk mounted on server. :param powersimdata.data_access.data_access.DataAccess data_access: data access object. :param dict scenario: scenario information.
Method signatures and docstrings:
- def __init__(self,... | Implement the Python class `BackUpDisk` described below.
Class description:
Back up scenario data to backup disk mounted on server. :param powersimdata.data_access.data_access.DataAccess data_access: data access object. :param dict scenario: scenario information.
Method signatures and docstrings:
- def __init__(self,... | 59f10383eca9f89be6ca606a4eed5bcc9a00a9be | <|skeleton|>
class BackUpDisk:
"""Back up scenario data to backup disk mounted on server. :param powersimdata.data_access.data_access.DataAccess data_access: data access object. :param dict scenario: scenario information."""
def __init__(self, data_access, scenario_info):
"""Constructor."""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BackUpDisk:
"""Back up scenario data to backup disk mounted on server. :param powersimdata.data_access.data_access.DataAccess data_access: data access object. :param dict scenario: scenario information."""
def __init__(self, data_access, scenario_info):
"""Constructor."""
self._data_acces... | the_stack_v2_python_sparse | powersimdata/scenario/move.py | eliasidanimas/PowerSimData | train | 0 |
8dd08a6c8996e6186c6ac7453ebd0861442ae969 | [
"if len(value) % 4 == 0:\n next_hop = str(netaddr.IPAddress(int(binascii.b2a_hex(value[0:4]), 16)))\n return next_hop\nelse:\n raise excep.UpdateMessageError(sub_error=bgp_cons.ERR_MSG_UPDATE_ATTR_LEN, data=value)",
"try:\n if netaddr.IPAddress(value).version == 4:\n ip_addr_raw = netaddr.IPAdd... | <|body_start_0|>
if len(value) % 4 == 0:
next_hop = str(netaddr.IPAddress(int(binascii.b2a_hex(value[0:4]), 16)))
return next_hop
else:
raise excep.UpdateMessageError(sub_error=bgp_cons.ERR_MSG_UPDATE_ATTR_LEN, data=value)
<|end_body_0|>
<|body_start_1|>
try:... | This is a well-known mandatory attribute that defines the (unicast) IP address of the router that SHOULD be used as the next hop to the destinations listed in the Network Layer Reachability Information field of the UPDATE message. | NextHop | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NextHop:
"""This is a well-known mandatory attribute that defines the (unicast) IP address of the router that SHOULD be used as the next hop to the destinations listed in the Network Layer Reachability Information field of the UPDATE message."""
def parse(cls, value):
"""Parse BGP ne... | stack_v2_sparse_classes_36k_train_005564 | 2,545 | permissive | [
{
"docstring": "Parse BGP nexthop. :param value: raw binary value",
"name": "parse",
"signature": "def parse(cls, value)"
},
{
"docstring": "encode BGP nexthop attribute. :param value: ipv4 format string like 1.1.1.1",
"name": "construct",
"signature": "def construct(cls, value)"
}
] | 2 | null | Implement the Python class `NextHop` described below.
Class description:
This is a well-known mandatory attribute that defines the (unicast) IP address of the router that SHOULD be used as the next hop to the destinations listed in the Network Layer Reachability Information field of the UPDATE message.
Method signatu... | Implement the Python class `NextHop` described below.
Class description:
This is a well-known mandatory attribute that defines the (unicast) IP address of the router that SHOULD be used as the next hop to the destinations listed in the Network Layer Reachability Information field of the UPDATE message.
Method signatu... | 24cbb732d4380ab54d000ac08690e521c60d4f2a | <|skeleton|>
class NextHop:
"""This is a well-known mandatory attribute that defines the (unicast) IP address of the router that SHOULD be used as the next hop to the destinations listed in the Network Layer Reachability Information field of the UPDATE message."""
def parse(cls, value):
"""Parse BGP ne... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NextHop:
"""This is a well-known mandatory attribute that defines the (unicast) IP address of the router that SHOULD be used as the next hop to the destinations listed in the Network Layer Reachability Information field of the UPDATE message."""
def parse(cls, value):
"""Parse BGP nexthop. :param... | the_stack_v2_python_sparse | yabgp/message/attribute/nexthop.py | smartbgp/yabgp | train | 227 |
a902cb7f01dee9967ab0b38ddfd4acaa4af4c307 | [
"self.mean = []\nself.std = []\nself.d = []\nself.h = []\nself.w = []",
"self.mean.append(mean)\nself.std.append(std)\nself.d.append(d)\nself.h.append(h)\nself.w.append(w)",
"self.mean = np.median(np.array(self.mean))\nself.std = np.median(np.array(self.std))\nself.d = np.median(np.array(self.d))\nself.h = np.m... | <|body_start_0|>
self.mean = []
self.std = []
self.d = []
self.h = []
self.w = []
<|end_body_0|>
<|body_start_1|>
self.mean.append(mean)
self.std.append(std)
self.d.append(d)
self.h.append(h)
self.w.append(w)
<|end_body_1|>
<|body_start_2... | A class collecting value distribution of preprocessed images in KiTS19 dataset Attributes ---------- mean: list collects average values in the preprocessed images std: list collects standard deviation of values in the preprocessed images d: collects depths of the preprocessed images h: collects heights of the preproces... | Stats | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stats:
"""A class collecting value distribution of preprocessed images in KiTS19 dataset Attributes ---------- mean: list collects average values in the preprocessed images std: list collects standard deviation of values in the preprocessed images d: collects depths of the preprocessed images h: ... | stack_v2_sparse_classes_36k_train_005565 | 23,958 | permissive | [
{
"docstring": "Initiates all the attributes Attributes ---------- mean: list collects average values in the preprocessed images std: list collects standard deviation of values in the preprocessed images d: collects depths of the preprocessed images h: collects heights of the preprocessed images w: collects wid... | 3 | null | Implement the Python class `Stats` described below.
Class description:
A class collecting value distribution of preprocessed images in KiTS19 dataset Attributes ---------- mean: list collects average values in the preprocessed images std: list collects standard deviation of values in the preprocessed images d: collect... | Implement the Python class `Stats` described below.
Class description:
A class collecting value distribution of preprocessed images in KiTS19 dataset Attributes ---------- mean: list collects average values in the preprocessed images std: list collects standard deviation of values in the preprocessed images d: collect... | c540fcc99eeacfb5c51de8daa0f8cca339f50799 | <|skeleton|>
class Stats:
"""A class collecting value distribution of preprocessed images in KiTS19 dataset Attributes ---------- mean: list collects average values in the preprocessed images std: list collects standard deviation of values in the preprocessed images d: collects depths of the preprocessed images h: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Stats:
"""A class collecting value distribution of preprocessed images in KiTS19 dataset Attributes ---------- mean: list collects average values in the preprocessed images std: list collects standard deviation of values in the preprocessed images d: collects depths of the preprocessed images h: collects heig... | the_stack_v2_python_sparse | vision/medical_imaging/3d-unet-kits19/preprocess.py | mlcommons/inference | train | 575 |
a4e971c773e846d243344bae3db0d820fe928072 | [
"self.args = args\nself.sim = Pong()\nself.nn = NeuralNetwork(Pong.STATE_DIM, Pong.NUM_ACTIONS, [50, 50, 50])\nself.db = ReplayDB(Pong.STATE_DIM, args.db_size)\nself.save_path, self.load_path = common.read_save_load_args(args)\nself.actions = tf.placeholder(tf.int32, (None,), 'actions')\nself.q_values = self.nn.tak... | <|body_start_0|>
self.args = args
self.sim = Pong()
self.nn = NeuralNetwork(Pong.STATE_DIM, Pong.NUM_ACTIONS, [50, 50, 50])
self.db = ReplayDB(Pong.STATE_DIM, args.db_size)
self.save_path, self.load_path = common.read_save_load_args(args)
self.actions = tf.placeholder(tf.... | Learn using a function-approximation version of the Value Iteration algorithm. | DeepValueIteration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeepValueIteration:
"""Learn using a function-approximation version of the Value Iteration algorithm."""
def __init__(self, args):
"""Create a DeepValueIteration instance using args."""
<|body_0|>
def add_data_points(self):
"""Use the simulator to create new data... | stack_v2_sparse_classes_36k_train_005566 | 5,662 | permissive | [
{
"docstring": "Create a DeepValueIteration instance using args.",
"name": "__init__",
"signature": "def __init__(self, args)"
},
{
"docstring": "Use the simulator to create new data points.",
"name": "add_data_points",
"signature": "def add_data_points(self)"
},
{
"docstring": "... | 4 | stack_v2_sparse_classes_30k_train_010891 | Implement the Python class `DeepValueIteration` described below.
Class description:
Learn using a function-approximation version of the Value Iteration algorithm.
Method signatures and docstrings:
- def __init__(self, args): Create a DeepValueIteration instance using args.
- def add_data_points(self): Use the simulat... | Implement the Python class `DeepValueIteration` described below.
Class description:
Learn using a function-approximation version of the Value Iteration algorithm.
Method signatures and docstrings:
- def __init__(self, args): Create a DeepValueIteration instance using args.
- def add_data_points(self): Use the simulat... | bf0474cd141d51f40af12ee5aba9b7c911ccc4d2 | <|skeleton|>
class DeepValueIteration:
"""Learn using a function-approximation version of the Value Iteration algorithm."""
def __init__(self, args):
"""Create a DeepValueIteration instance using args."""
<|body_0|>
def add_data_points(self):
"""Use the simulator to create new data... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeepValueIteration:
"""Learn using a function-approximation version of the Value Iteration algorithm."""
def __init__(self, args):
"""Create a DeepValueIteration instance using args."""
self.args = args
self.sim = Pong()
self.nn = NeuralNetwork(Pong.STATE_DIM, Pong.NUM_ACT... | the_stack_v2_python_sparse | ApproxiPong-master/pong/learning/deep_value_iteration.py | bareluz93/exam | train | 0 |
0c537649fc89f3a6db7c05b8ef1c75265fe7524d | [
"selection = reflection_table.get_flags(reflection_table.flags.integrated_sum)\nreflection_table = reflection_table.select(selection)\nlogger.info('Selected %d summation integrated reflections', reflection_table.size())\nreturn reflection_table",
"reflection_table, conversion = cls.calculate_lp_qe_correction_and_... | <|body_start_0|>
selection = reflection_table.get_flags(reflection_table.flags.integrated_sum)
reflection_table = reflection_table.select(selection)
logger.info('Selected %d summation integrated reflections', reflection_table.size())
return reflection_table
<|end_body_0|>
<|body_start_1... | Reduction methods for data with sum intensities. | SumIntensityReducer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SumIntensityReducer:
"""Reduction methods for data with sum intensities."""
def reduce_on_intensities(reflection_table):
"""Select reflections successfully integrated by summation method."""
<|body_0|>
def apply_scaling_factors(cls, reflection_table):
"""Apply co... | stack_v2_sparse_classes_36k_train_005567 | 38,270 | permissive | [
{
"docstring": "Select reflections successfully integrated by summation method.",
"name": "reduce_on_intensities",
"signature": "def reduce_on_intensities(reflection_table)"
},
{
"docstring": "Apply corrections to the intensities and variances (partiality, lp, qe).",
"name": "apply_scaling_f... | 2 | null | Implement the Python class `SumIntensityReducer` described below.
Class description:
Reduction methods for data with sum intensities.
Method signatures and docstrings:
- def reduce_on_intensities(reflection_table): Select reflections successfully integrated by summation method.
- def apply_scaling_factors(cls, reflec... | Implement the Python class `SumIntensityReducer` described below.
Class description:
Reduction methods for data with sum intensities.
Method signatures and docstrings:
- def reduce_on_intensities(reflection_table): Select reflections successfully integrated by summation method.
- def apply_scaling_factors(cls, reflec... | 88bf7f7c5ac44defc046ebf0719cde748092cfff | <|skeleton|>
class SumIntensityReducer:
"""Reduction methods for data with sum intensities."""
def reduce_on_intensities(reflection_table):
"""Select reflections successfully integrated by summation method."""
<|body_0|>
def apply_scaling_factors(cls, reflection_table):
"""Apply co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SumIntensityReducer:
"""Reduction methods for data with sum intensities."""
def reduce_on_intensities(reflection_table):
"""Select reflections successfully integrated by summation method."""
selection = reflection_table.get_flags(reflection_table.flags.integrated_sum)
reflection_t... | the_stack_v2_python_sparse | src/dials/util/filter_reflections.py | dials/dials | train | 71 |
6ab31a74b77a2701a335022fb9eeb21d7c1b64ec | [
"self.name = name\nself.private = private\nself.member = member",
"member = self.member\nmember.instance = instance\ntry:\n if member.mapper is not None:\n value = member.premap(value)\n value = member.transform(value)\nfinally:\n member.instance = None\nself.private.values[self.name] = value",
... | <|body_start_0|>
self.name = name
self.private = private
self.member = member
<|end_body_0|>
<|body_start_1|>
member = self.member
member.instance = instance
try:
if member.mapper is not None:
value = member.premap(value)
value = m... | Member descriptor class :IVariables: - `name`: The name of the member - `private`: The private data container - `member`: The actual member instance :Types: - `name`: ``str`` - `private`: `Private` - `member`: `Member` | Descriptor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Descriptor:
"""Member descriptor class :IVariables: - `name`: The name of the member - `private`: The private data container - `member`: The actual member instance :Types: - `name`: ``str`` - `private`: `Private` - `member`: `Member`"""
def __init__(self, name, private, member):
"""I... | stack_v2_sparse_classes_36k_train_005568 | 22,737 | permissive | [
{
"docstring": "Initialization :Parameters: - `name`: The name of the member - `private`: The private data container - `member`: The actual member instance :Types: - `name`: ``str`` - `private`: `Private` - `member`: `Member`",
"name": "__init__",
"signature": "def __init__(self, name, private, member)"... | 4 | stack_v2_sparse_classes_30k_train_011781 | Implement the Python class `Descriptor` described below.
Class description:
Member descriptor class :IVariables: - `name`: The name of the member - `private`: The private data container - `member`: The actual member instance :Types: - `name`: ``str`` - `private`: `Private` - `member`: `Member`
Method signatures and d... | Implement the Python class `Descriptor` described below.
Class description:
Member descriptor class :IVariables: - `name`: The name of the member - `private`: The private data container - `member`: The actual member instance :Types: - `name`: ``str`` - `private`: `Private` - `member`: `Member`
Method signatures and d... | faecefdabd8fbf6d40738a24004772020c244f64 | <|skeleton|>
class Descriptor:
"""Member descriptor class :IVariables: - `name`: The name of the member - `private`: The private data container - `member`: The actual member instance :Types: - `name`: ``str`` - `private`: `Private` - `member`: `Member`"""
def __init__(self, name, private, member):
"""I... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Descriptor:
"""Member descriptor class :IVariables: - `name`: The name of the member - `private`: The private data container - `member`: The actual member instance :Types: - `name`: ``str`` - `private`: `Private` - `member`: `Member`"""
def __init__(self, name, private, member):
"""Initialization... | the_stack_v2_python_sparse | src/lib/svnmailer/settings/_typedstruct.py | m-tmatma/svnmailer | train | 1 |
2023ff4e68ce884accbbff4f1b40aaf8728764bd | [
"self.Whf = np.random.normal(size=(i + h, h))\nself.Whb = np.random.normal(size=(i + h, h))\nself.Wy = np.random.normal(size=(2 * h, o))\nself.bhf = np.zeros((1, h))\nself.bhb = np.zeros((1, h))\nself.by = np.zeros((1, o))",
"n = np.concatenate((h_prev, x_t), axis=1)\nh_next = np.tanh(np.dot(n, self.Whf) + self.b... | <|body_start_0|>
self.Whf = np.random.normal(size=(i + h, h))
self.Whb = np.random.normal(size=(i + h, h))
self.Wy = np.random.normal(size=(2 * h, o))
self.bhf = np.zeros((1, h))
self.bhb = np.zeros((1, h))
self.by = np.zeros((1, o))
<|end_body_0|>
<|body_start_1|>
... | class bidirectionalcell | BidirectionalCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BidirectionalCell:
"""class bidirectionalcell"""
def __init__(self, i, h, o):
"""class constructor"""
<|body_0|>
def forward(self, h_prev, x_t):
"""represents a bidirectional cell of an RNN"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.Wh... | stack_v2_sparse_classes_36k_train_005569 | 691 | no_license | [
{
"docstring": "class constructor",
"name": "__init__",
"signature": "def __init__(self, i, h, o)"
},
{
"docstring": "represents a bidirectional cell of an RNN",
"name": "forward",
"signature": "def forward(self, h_prev, x_t)"
}
] | 2 | null | Implement the Python class `BidirectionalCell` described below.
Class description:
class bidirectionalcell
Method signatures and docstrings:
- def __init__(self, i, h, o): class constructor
- def forward(self, h_prev, x_t): represents a bidirectional cell of an RNN | Implement the Python class `BidirectionalCell` described below.
Class description:
class bidirectionalcell
Method signatures and docstrings:
- def __init__(self, i, h, o): class constructor
- def forward(self, h_prev, x_t): represents a bidirectional cell of an RNN
<|skeleton|>
class BidirectionalCell:
"""class ... | a49eb348ff994f35b0efbbd5ac3ac8ae8ccb57d2 | <|skeleton|>
class BidirectionalCell:
"""class bidirectionalcell"""
def __init__(self, i, h, o):
"""class constructor"""
<|body_0|>
def forward(self, h_prev, x_t):
"""represents a bidirectional cell of an RNN"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BidirectionalCell:
"""class bidirectionalcell"""
def __init__(self, i, h, o):
"""class constructor"""
self.Whf = np.random.normal(size=(i + h, h))
self.Whb = np.random.normal(size=(i + h, h))
self.Wy = np.random.normal(size=(2 * h, o))
self.bhf = np.zeros((1, h))
... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/5-bi_forward.py | salmenz/holbertonschool-machine_learning | train | 4 |
f15f5e4eef04f0b9db2a4ddacd8abbf5f0e1d61f | [
"self.validate_parameters(dealer_id=dealer_id, dealer_logo=dealer_logo)\n_query_builder = Configuration.get_base_uri()\n_query_builder += '/admin/dealer/logo/{dealerId}'\n_query_builder = APIHelper.append_url_with_template_parameters(_query_builder, {'dealerId': dealer_id})\n_query_url = APIHelper.clean_url(_query_... | <|body_start_0|>
self.validate_parameters(dealer_id=dealer_id, dealer_logo=dealer_logo)
_query_builder = Configuration.get_base_uri()
_query_builder += '/admin/dealer/logo/{dealerId}'
_query_builder = APIHelper.append_url_with_template_parameters(_query_builder, {'dealerId': dealer_id})
... | A Controller to access Endpoints in the idfy_rest_client API. | DealerController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DealerController:
"""A Controller to access Endpoints in the idfy_rest_client API."""
def update_dealer_logo(self, dealer_id, dealer_logo):
"""Does a POST request to /admin/dealer/logo/{dealerId}. Set dealer Logo. Requires the following scope: [dealer] Args: dealer_id (uuid|string): ... | stack_v2_sparse_classes_36k_train_005570 | 8,814 | permissive | [
{
"docstring": "Does a POST request to /admin/dealer/logo/{dealerId}. Set dealer Logo. Requires the following scope: [dealer] Args: dealer_id (uuid|string): Your Idfy dealer ID dealer_logo (DealerLogo): TODO: type description here. Example: Returns: string: Response from the API. Ok Raises: APIException: When a... | 4 | stack_v2_sparse_classes_30k_train_017857 | Implement the Python class `DealerController` described below.
Class description:
A Controller to access Endpoints in the idfy_rest_client API.
Method signatures and docstrings:
- def update_dealer_logo(self, dealer_id, dealer_logo): Does a POST request to /admin/dealer/logo/{dealerId}. Set dealer Logo. Requires the ... | Implement the Python class `DealerController` described below.
Class description:
A Controller to access Endpoints in the idfy_rest_client API.
Method signatures and docstrings:
- def update_dealer_logo(self, dealer_id, dealer_logo): Does a POST request to /admin/dealer/logo/{dealerId}. Set dealer Logo. Requires the ... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class DealerController:
"""A Controller to access Endpoints in the idfy_rest_client API."""
def update_dealer_logo(self, dealer_id, dealer_logo):
"""Does a POST request to /admin/dealer/logo/{dealerId}. Set dealer Logo. Requires the following scope: [dealer] Args: dealer_id (uuid|string): ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DealerController:
"""A Controller to access Endpoints in the idfy_rest_client API."""
def update_dealer_logo(self, dealer_id, dealer_logo):
"""Does a POST request to /admin/dealer/logo/{dealerId}. Set dealer Logo. Requires the following scope: [dealer] Args: dealer_id (uuid|string): Your Idfy dea... | the_stack_v2_python_sparse | idfy_rest_client/controllers/dealer_controller.py | dealflowteam/Idfy | train | 0 |
595216bae5a4661f03cce2a802de9cd329219ad5 | [
"super(AddFlyerDatesForm, self).__init__(*args, **kwargs)\nif checked_data:\n self.fields['subdivision_consumer_count'].initial = checked_data.get('subdivision_consumer_count', 0)\nelse:\n self.fields['subdivision_consumer_count'].initial = subdivision_consumer_count\nfor flyer_month in available_flyer_dates_... | <|body_start_0|>
super(AddFlyerDatesForm, self).__init__(*args, **kwargs)
if checked_data:
self.fields['subdivision_consumer_count'].initial = checked_data.get('subdivision_consumer_count', 0)
else:
self.fields['subdivision_consumer_count'].initial = subdivision_consumer_... | The Add Flyer Dates Form. | AddFlyerDatesForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddFlyerDatesForm:
"""The Add Flyer Dates Form."""
def __init__(self, available_flyer_dates_list, subdivision_consumer_count=None, checked_data=None, *args, **kwargs):
"""Dynamically create 10 sets of location fields."""
<|body_0|>
def clean_dynamic_fields(self, post_dat... | stack_v2_sparse_classes_36k_train_005571 | 27,686 | no_license | [
{
"docstring": "Dynamically create 10 sets of location fields.",
"name": "__init__",
"signature": "def __init__(self, available_flyer_dates_list, subdivision_consumer_count=None, checked_data=None, *args, **kwargs)"
},
{
"docstring": "Clean method for this form.",
"name": "clean_dynamic_fiel... | 3 | stack_v2_sparse_classes_30k_train_006479 | Implement the Python class `AddFlyerDatesForm` described below.
Class description:
The Add Flyer Dates Form.
Method signatures and docstrings:
- def __init__(self, available_flyer_dates_list, subdivision_consumer_count=None, checked_data=None, *args, **kwargs): Dynamically create 10 sets of location fields.
- def cle... | Implement the Python class `AddFlyerDatesForm` described below.
Class description:
The Add Flyer Dates Form.
Method signatures and docstrings:
- def __init__(self, available_flyer_dates_list, subdivision_consumer_count=None, checked_data=None, *args, **kwargs): Dynamically create 10 sets of location fields.
- def cle... | a780ccdc3350d4b5c7990c65d1af8d71060c62cc | <|skeleton|>
class AddFlyerDatesForm:
"""The Add Flyer Dates Form."""
def __init__(self, available_flyer_dates_list, subdivision_consumer_count=None, checked_data=None, *args, **kwargs):
"""Dynamically create 10 sets of location fields."""
<|body_0|>
def clean_dynamic_fields(self, post_dat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddFlyerDatesForm:
"""The Add Flyer Dates Form."""
def __init__(self, available_flyer_dates_list, subdivision_consumer_count=None, checked_data=None, *args, **kwargs):
"""Dynamically create 10 sets of location fields."""
super(AddFlyerDatesForm, self).__init__(*args, **kwargs)
if ... | the_stack_v2_python_sparse | coupon/forms.py | wcirillo/ten | train | 0 |
106608ec916d8fda7aa5c9b67190395162accb91 | [
"data.config.fps = self.read_int(root, self.FPS, data.config.fps)\ndata.config.max_frame_time = self.read_float(root, self.MAX_FRAME_TIME, data.config.max_frame_time)\ndata.config.num_fps_avg = self.read_int(root, self.NUM_FPS_AVG, data.config.num_fps_avg)\ndata.config.render_decision_trees = self.read_boolean(root... | <|body_start_0|>
data.config.fps = self.read_int(root, self.FPS, data.config.fps)
data.config.max_frame_time = self.read_float(root, self.MAX_FRAME_TIME, data.config.max_frame_time)
data.config.num_fps_avg = self.read_int(root, self.NUM_FPS_AVG, data.config.num_fps_avg)
data.config.rende... | Yaml reader for config types. Constants: ACTION FPS KEY KEYS MAX_FRAME_TIME NUM_FPS_AVG RENDER_DECISION_TREES SCROLL_WIDTH_X SCROLL_WIDTH_Y STATE_ID VIEW_X VIEW_Y WINDOW_TITLE | YamlConfigReader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YamlConfigReader:
"""Yaml reader for config types. Constants: ACTION FPS KEY KEYS MAX_FRAME_TIME NUM_FPS_AVG RENDER_DECISION_TREES SCROLL_WIDTH_X SCROLL_WIDTH_Y STATE_ID VIEW_X VIEW_Y WINDOW_TITLE"""
def parse(self, root, data):
"""Parse the game structure. Writes the parsed informat... | stack_v2_sparse_classes_36k_train_005572 | 2,266 | no_license | [
{
"docstring": "Parse the game structure. Writes the parsed information into the data object.",
"name": "parse",
"signature": "def parse(self, root, data)"
},
{
"docstring": "Parse keys.",
"name": "__keys",
"signature": "def __keys(self, root, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020110 | Implement the Python class `YamlConfigReader` described below.
Class description:
Yaml reader for config types. Constants: ACTION FPS KEY KEYS MAX_FRAME_TIME NUM_FPS_AVG RENDER_DECISION_TREES SCROLL_WIDTH_X SCROLL_WIDTH_Y STATE_ID VIEW_X VIEW_Y WINDOW_TITLE
Method signatures and docstrings:
- def parse(self, root, da... | Implement the Python class `YamlConfigReader` described below.
Class description:
Yaml reader for config types. Constants: ACTION FPS KEY KEYS MAX_FRAME_TIME NUM_FPS_AVG RENDER_DECISION_TREES SCROLL_WIDTH_X SCROLL_WIDTH_Y STATE_ID VIEW_X VIEW_Y WINDOW_TITLE
Method signatures and docstrings:
- def parse(self, root, da... | c38b43edb7ec54f18768564c42859195bc2477e4 | <|skeleton|>
class YamlConfigReader:
"""Yaml reader for config types. Constants: ACTION FPS KEY KEYS MAX_FRAME_TIME NUM_FPS_AVG RENDER_DECISION_TREES SCROLL_WIDTH_X SCROLL_WIDTH_Y STATE_ID VIEW_X VIEW_Y WINDOW_TITLE"""
def parse(self, root, data):
"""Parse the game structure. Writes the parsed informat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class YamlConfigReader:
"""Yaml reader for config types. Constants: ACTION FPS KEY KEYS MAX_FRAME_TIME NUM_FPS_AVG RENDER_DECISION_TREES SCROLL_WIDTH_X SCROLL_WIDTH_Y STATE_ID VIEW_X VIEW_Y WINDOW_TITLE"""
def parse(self, root, data):
"""Parse the game structure. Writes the parsed information into the ... | the_stack_v2_python_sparse | python-prototype/config/configreader.py | tea2code/fantasy-rts | train | 0 |
ce67ed1171d865e94a87ec5384d7d7c4bf22566e | [
"self._last_id = None\nself.dao = dao\nself.tree = Tree()\nself.last_id = None\ntry:\n self.tree.create_node(tag=self._tag, identifier=0, parent=None)\nexcept (tree.MultipleRootError, tree.NodeIDAbsentError, tree.DuplicatedNodeIdError):\n pass",
"try:\n _entity = self.tree.get_node(node_id).data\nexcept ... | <|body_start_0|>
self._last_id = None
self.dao = dao
self.tree = Tree()
self.last_id = None
try:
self.tree.create_node(tag=self._tag, identifier=0, parent=None)
except (tree.MultipleRootError, tree.NodeIDAbsentError, tree.DuplicatedNodeIdError):
pa... | This is the meta-class for all RAMSTK Data Models. :ivar tree: the :class:`treelib.Tree` that will contain the structure of the RAMSTK module being modeled.. :ivar dao: the :class:`ramstk.dao.DAO` object used to communicate with the RAMSTK Program database. | RAMSTKDataModel | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RAMSTKDataModel:
"""This is the meta-class for all RAMSTK Data Models. :ivar tree: the :class:`treelib.Tree` that will contain the structure of the RAMSTK module being modeled.. :ivar dao: the :class:`ramstk.dao.DAO` object used to communicate with the RAMSTK Program database."""
def __init_... | stack_v2_sparse_classes_36k_train_005573 | 5,664 | permissive | [
{
"docstring": "Initialize an RAMSTK data model instance. :param dao: the data access object for communicating with the RAMSTK Program database. :type dao: :class:`ramstk.dao.DAO.DAO`",
"name": "__init__",
"signature": "def __init__(self, dao)"
},
{
"docstring": "Retrieve the instance of the RAM... | 6 | null | Implement the Python class `RAMSTKDataModel` described below.
Class description:
This is the meta-class for all RAMSTK Data Models. :ivar tree: the :class:`treelib.Tree` that will contain the structure of the RAMSTK module being modeled.. :ivar dao: the :class:`ramstk.dao.DAO` object used to communicate with the RAMST... | Implement the Python class `RAMSTKDataModel` described below.
Class description:
This is the meta-class for all RAMSTK Data Models. :ivar tree: the :class:`treelib.Tree` that will contain the structure of the RAMSTK module being modeled.. :ivar dao: the :class:`ramstk.dao.DAO` object used to communicate with the RAMST... | 488ffed8b842399ddcae93007de6c6f1dda23d05 | <|skeleton|>
class RAMSTKDataModel:
"""This is the meta-class for all RAMSTK Data Models. :ivar tree: the :class:`treelib.Tree` that will contain the structure of the RAMSTK module being modeled.. :ivar dao: the :class:`ramstk.dao.DAO` object used to communicate with the RAMSTK Program database."""
def __init_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RAMSTKDataModel:
"""This is the meta-class for all RAMSTK Data Models. :ivar tree: the :class:`treelib.Tree` that will contain the structure of the RAMSTK module being modeled.. :ivar dao: the :class:`ramstk.dao.DAO` object used to communicate with the RAMSTK Program database."""
def __init__(self, dao):... | the_stack_v2_python_sparse | src/ramstk/modules/RAMSTKDataModel.py | JmiXIII/ramstk | train | 0 |
5884c9d06bb9947a11e2247472b18c5c2f5c5815 | [
"global op\nop = 0\nnext = pcs.Field('next_header', 8)\nlen = pcs.Field('length', 8)\ntype = pcs.Field('type', 8)\npcs.Packet.__init__(self, [next, len, type], bytes)",
"global op\nop += 1\notype = pcs.Field('otype' + str(op), 8)\nolen = pcs.Field('olength' + str(op), 8, default=len / 8)\nif len != 0:\n odata ... | <|body_start_0|>
global op
op = 0
next = pcs.Field('next_header', 8)
len = pcs.Field('length', 8)
type = pcs.Field('type', 8)
pcs.Packet.__init__(self, [next, len, type], bytes)
<|end_body_0|>
<|body_start_1|>
global op
op += 1
otype = pcs.Field('... | A class that contains the IPv6 destination options extension-headers. | dstopts | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class dstopts:
"""A class that contains the IPv6 destination options extension-headers."""
def __init__(self, bytes=None):
"""IPv6 destination options extension header from RFC 2460"""
<|body_0|>
def option(self, len=0):
"""add option header to the destination extensio... | stack_v2_sparse_classes_36k_train_005574 | 7,919 | no_license | [
{
"docstring": "IPv6 destination options extension header from RFC 2460",
"name": "__init__",
"signature": "def __init__(self, bytes=None)"
},
{
"docstring": "add option header to the destination extension header",
"name": "option",
"signature": "def option(self, len=0)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004978 | Implement the Python class `dstopts` described below.
Class description:
A class that contains the IPv6 destination options extension-headers.
Method signatures and docstrings:
- def __init__(self, bytes=None): IPv6 destination options extension header from RFC 2460
- def option(self, len=0): add option header to the... | Implement the Python class `dstopts` described below.
Class description:
A class that contains the IPv6 destination options extension-headers.
Method signatures and docstrings:
- def __init__(self, bytes=None): IPv6 destination options extension header from RFC 2460
- def option(self, len=0): add option header to the... | a070a39586b582fbeea72abf12bbfd812955ad81 | <|skeleton|>
class dstopts:
"""A class that contains the IPv6 destination options extension-headers."""
def __init__(self, bytes=None):
"""IPv6 destination options extension header from RFC 2460"""
<|body_0|>
def option(self, len=0):
"""add option header to the destination extensio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class dstopts:
"""A class that contains the IPv6 destination options extension-headers."""
def __init__(self, bytes=None):
"""IPv6 destination options extension header from RFC 2460"""
global op
op = 0
next = pcs.Field('next_header', 8)
len = pcs.Field('length', 8)
... | the_stack_v2_python_sparse | src/pcs/packets/ipv6.py | bilouro/tcptest | train | 0 |
da983396a1e2ad8f017fd922e5bb9ba64d0f4f1f | [
"self.nums = nums\nself.size = len(nums)\nself.sums = [0] * (self.size + 1)\nfor i in range(self.size):\n j = i + 1\n while j <= self.size:\n self.sums[j] += nums[i]\n j += j & -j",
"add = val - self.nums[i]\nself.nums[i] = val\ni += 1\nwhile i <= self.size:\n self.sums[i] += add\n i += ... | <|body_start_0|>
self.nums = nums
self.size = len(nums)
self.sums = [0] * (self.size + 1)
for i in range(self.size):
j = i + 1
while j <= self.size:
self.sums[j] += nums[i]
j += j & -j
<|end_body_0|>
<|body_start_1|>
add = ... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: int"""
<|body_1|>
def sumRange(self, i, j):
"""sum of elements nums[i... | stack_v2_sparse_classes_36k_train_005575 | 1,219 | no_license | [
{
"docstring": "initialize your data structure here. :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type val: int :rtype: int",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docstring": "sum o... | 3 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): initialize your data structure here. :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: int
- def sumRange(self, i, j... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): initialize your data structure here. :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: int
- def sumRange(self, i, j... | 616a868bfa7bdd00195067b0477b0236a72d23e0 | <|skeleton|>
class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: int"""
<|body_1|>
def sumRange(self, i, j):
"""sum of elements nums[i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
self.nums = nums
self.size = len(nums)
self.sums = [0] * (self.size + 1)
for i in range(self.size):
j = i + 1
while j <= self.size:
... | the_stack_v2_python_sparse | 301-400/307.py | yanbinbi/leetcode | train | 0 | |
d9a7492c19cc4a6c78722d329adfb95edadd6199 | [
"md5obj = hashlib.md5(username.encode('utf-8'))\nmd5obj.update(password.encode('utf-8'))\nreturn md5obj.hexdigest()",
"Public.print('欢迎访问校园管理系统'.center(50, '-'), 'none')\nPublic.print('>>>请登录:', 'none')\ncount = 0\nwhile count < 3:\n username = input('>>>请输入用户名:').strip()\n password = input('>>>请输入密码:').str... | <|body_start_0|>
md5obj = hashlib.md5(username.encode('utf-8'))
md5obj.update(password.encode('utf-8'))
return md5obj.hexdigest()
<|end_body_0|>
<|body_start_1|>
Public.print('欢迎访问校园管理系统'.center(50, '-'), 'none')
Public.print('>>>请登录:', 'none')
count = 0
while co... | 用户登录类 包含登录和注册两个方法,密码进行md5加密 | MyLogin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyLogin:
"""用户登录类 包含登录和注册两个方法,密码进行md5加密"""
def __encryption_md5_salt1(username, password):
"""md5动态加盐 :return: 加密后的字符串"""
<|body_0|>
def login():
"""用户登录 :return: (用户名,用户权限)"""
<|body_1|>
def register(name, user_type):
"""创建用户登录权限 :param name... | stack_v2_sparse_classes_36k_train_005576 | 11,027 | no_license | [
{
"docstring": "md5动态加盐 :return: 加密后的字符串",
"name": "__encryption_md5_salt1",
"signature": "def __encryption_md5_salt1(username, password)"
},
{
"docstring": "用户登录 :return: (用户名,用户权限)",
"name": "login",
"signature": "def login()"
},
{
"docstring": "创建用户登录权限 :param name: 用户名 :param... | 3 | null | Implement the Python class `MyLogin` described below.
Class description:
用户登录类 包含登录和注册两个方法,密码进行md5加密
Method signatures and docstrings:
- def __encryption_md5_salt1(username, password): md5动态加盐 :return: 加密后的字符串
- def login(): 用户登录 :return: (用户名,用户权限)
- def register(name, user_type): 创建用户登录权限 :param name: 用户名 :param us... | Implement the Python class `MyLogin` described below.
Class description:
用户登录类 包含登录和注册两个方法,密码进行md5加密
Method signatures and docstrings:
- def __encryption_md5_salt1(username, password): md5动态加盐 :return: 加密后的字符串
- def login(): 用户登录 :return: (用户名,用户权限)
- def register(name, user_type): 创建用户登录权限 :param name: 用户名 :param us... | d7fc68d3d23345df5bfb09d4a84686c8b49a5ad7 | <|skeleton|>
class MyLogin:
"""用户登录类 包含登录和注册两个方法,密码进行md5加密"""
def __encryption_md5_salt1(username, password):
"""md5动态加盐 :return: 加密后的字符串"""
<|body_0|>
def login():
"""用户登录 :return: (用户名,用户权限)"""
<|body_1|>
def register(name, user_type):
"""创建用户登录权限 :param name... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyLogin:
"""用户登录类 包含登录和注册两个方法,密码进行md5加密"""
def __encryption_md5_salt1(username, password):
"""md5动态加盐 :return: 加密后的字符串"""
md5obj = hashlib.md5(username.encode('utf-8'))
md5obj.update(password.encode('utf-8'))
return md5obj.hexdigest()
def login():
"""用户登录 :ret... | the_stack_v2_python_sparse | Homework/day07/core/public.py | 214031230/Python21 | train | 0 |
c77345d5ba511683f93e85e494bf18806faf1002 | [
"C = self.COEFFS[imt]\nmag = rup.mag - 6\nd = np.sqrt(dists.rjb ** 2 + C['c7'] ** 2)\nmean = np.zeros_like(d)\nmean += C['c1'] + C['c2'] * mag + C['c3'] * mag ** 2 + C['c6']\nidx = d <= 100.0\nmean[idx] = mean[idx] + C['c5'] * np.log10(d[idx])\nidx = d > 100.0\nmean[idx] = mean[idx] + C['c5'] * np.log10(100.0) - np... | <|body_start_0|>
C = self.COEFFS[imt]
mag = rup.mag - 6
d = np.sqrt(dists.rjb ** 2 + C['c7'] ** 2)
mean = np.zeros_like(d)
mean += C['c1'] + C['c2'] * mag + C['c3'] * mag ** 2 + C['c6']
idx = d <= 100.0
mean[idx] = mean[idx] + C['c5'] * np.log10(d[idx])
id... | Implement equation used by the Geological Survey of Canada (GSC) for the 2010 Western Canada National Seismic Hazard Model. The class implements the model of David M. Boore, William B. Joyner, and Thomas E. Fumal ("Estimation of Response Spectra and Peak Accelerations from Western North American Earthquakes: An Interim... | BooreEtAl1993GSCBest | [
"BSD-3-Clause",
"AGPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BooreEtAl1993GSCBest:
"""Implement equation used by the Geological Survey of Canada (GSC) for the 2010 Western Canada National Seismic Hazard Model. The class implements the model of David M. Boore, William B. Joyner, and Thomas E. Fumal ("Estimation of Response Spectra and Peak Accelerations fro... | stack_v2_sparse_classes_36k_train_005577 | 7,227 | permissive | [
{
"docstring": "See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.",
"name": "get_mean_and_stddevs",
"signature": "def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types)"
},
{
"docstring": "Return total standa... | 2 | stack_v2_sparse_classes_30k_train_011507 | Implement the Python class `BooreEtAl1993GSCBest` described below.
Class description:
Implement equation used by the Geological Survey of Canada (GSC) for the 2010 Western Canada National Seismic Hazard Model. The class implements the model of David M. Boore, William B. Joyner, and Thomas E. Fumal ("Estimation of Resp... | Implement the Python class `BooreEtAl1993GSCBest` described below.
Class description:
Implement equation used by the Geological Survey of Canada (GSC) for the 2010 Western Canada National Seismic Hazard Model. The class implements the model of David M. Boore, William B. Joyner, and Thomas E. Fumal ("Estimation of Resp... | 0da9ba5a575360081715e8b90c71d4b16c6687c8 | <|skeleton|>
class BooreEtAl1993GSCBest:
"""Implement equation used by the Geological Survey of Canada (GSC) for the 2010 Western Canada National Seismic Hazard Model. The class implements the model of David M. Boore, William B. Joyner, and Thomas E. Fumal ("Estimation of Response Spectra and Peak Accelerations fro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BooreEtAl1993GSCBest:
"""Implement equation used by the Geological Survey of Canada (GSC) for the 2010 Western Canada National Seismic Hazard Model. The class implements the model of David M. Boore, William B. Joyner, and Thomas E. Fumal ("Estimation of Response Spectra and Peak Accelerations from Western Nor... | the_stack_v2_python_sparse | openquake/hazardlib/gsim/boore_1993.py | GFZ-Centre-for-Early-Warning/shakyground | train | 1 |
5c6d1ecab9c2806da2262d58ed9ffa15499e9708 | [
"super().__init__()\nself.args = quant_arc_interface.args\nself.q_params = nn.Parameter(self.args.q_delta * torch.randn(self.args.q_depth * self.args.n_qubits))\nself.qai = quant_arc_interface",
"q_in = torch.tanh(input_features) * np.pi / 2.0\nq_in = q_in.to(self.args.device)\nq_out = torch.Tensor(0, self.qai.se... | <|body_start_0|>
super().__init__()
self.args = quant_arc_interface.args
self.q_params = nn.Parameter(self.args.q_delta * torch.randn(self.args.q_depth * self.args.n_qubits))
self.qai = quant_arc_interface
<|end_body_0|>
<|body_start_1|>
q_in = torch.tanh(input_features) * np.pi... | Torch module implementing the *dressed* quantum net. | QNet_1 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QNet_1:
"""Torch module implementing the *dressed* quantum net."""
def __init__(self, quant_arc_interface):
"""Definition of the *dressed* layout."""
<|body_0|>
def forward(self, input_features):
"""Defining how tensors are supposed to move through the *dressed* ... | stack_v2_sparse_classes_36k_train_005578 | 2,951 | permissive | [
{
"docstring": "Definition of the *dressed* layout.",
"name": "__init__",
"signature": "def __init__(self, quant_arc_interface)"
},
{
"docstring": "Defining how tensors are supposed to move through the *dressed* quantum net.",
"name": "forward",
"signature": "def forward(self, input_feat... | 2 | stack_v2_sparse_classes_30k_train_020083 | Implement the Python class `QNet_1` described below.
Class description:
Torch module implementing the *dressed* quantum net.
Method signatures and docstrings:
- def __init__(self, quant_arc_interface): Definition of the *dressed* layout.
- def forward(self, input_features): Defining how tensors are supposed to move t... | Implement the Python class `QNet_1` described below.
Class description:
Torch module implementing the *dressed* quantum net.
Method signatures and docstrings:
- def __init__(self, quant_arc_interface): Definition of the *dressed* layout.
- def forward(self, input_features): Defining how tensors are supposed to move t... | 8126691b43bddc2b1a96f73ab35d04d1af200d7a | <|skeleton|>
class QNet_1:
"""Torch module implementing the *dressed* quantum net."""
def __init__(self, quant_arc_interface):
"""Definition of the *dressed* layout."""
<|body_0|>
def forward(self, input_features):
"""Defining how tensors are supposed to move through the *dressed* ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QNet_1:
"""Torch module implementing the *dressed* quantum net."""
def __init__(self, quant_arc_interface):
"""Definition of the *dressed* layout."""
super().__init__()
self.args = quant_arc_interface.args
self.q_params = nn.Parameter(self.args.q_delta * torch.randn(self.a... | the_stack_v2_python_sparse | model/dvqc_layers.py | zzh237/quanthmc | train | 0 |
ced7e43253b53b0452b36e351f4d14a133a31d0d | [
"Transformer.__init__(self)\nself.nbClass = nbClass\nself.transfNodeLogit = ndTrnsfLogit",
"aA = self.transfNodeLogit.transform([edge.A for edge in lEdge])\naB = self.transfNodeLogit.transform([edge.B for edge in lEdge])\na = np.hstack([aA, aB])\ndel aA, aB\nassert a.shape == (len(lEdge), 2 * 3 * self.nbClass)\nr... | <|body_start_0|>
Transformer.__init__(self)
self.nbClass = nbClass
self.transfNodeLogit = ndTrnsfLogit
<|end_body_0|>
<|body_start_1|>
aA = self.transfNodeLogit.transform([edge.A for edge in lEdge])
aB = self.transfNodeLogit.transform([edge.B for edge in lEdge])
a = np.h... | we will get a list of edges belonging to N classes. we train a logit classifier for those classes, as well as a multilabel classifier for the neighor of those classes the built feature vector is 2*N long | EdgeTransformerLogit | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EdgeTransformerLogit:
"""we will get a list of edges belonging to N classes. we train a logit classifier for those classes, as well as a multilabel classifier for the neighor of those classes the built feature vector is 2*N long"""
def __init__(self, nbClass, ndTrnsfLogit):
"""input:... | stack_v2_sparse_classes_36k_train_005579 | 8,399 | permissive | [
{
"docstring": "input: - number of classes - number of ngram - ngram min/max size - lowercase or not - njobs when fitting the logit using grid search if n_feat_edge is negative, or 0, or None, we use all possible ngrams",
"name": "__init__",
"signature": "def __init__(self, nbClass, ndTrnsfLogit)"
},
... | 2 | null | Implement the Python class `EdgeTransformerLogit` described below.
Class description:
we will get a list of edges belonging to N classes. we train a logit classifier for those classes, as well as a multilabel classifier for the neighor of those classes the built feature vector is 2*N long
Method signatures and docstr... | Implement the Python class `EdgeTransformerLogit` described below.
Class description:
we will get a list of edges belonging to N classes. we train a logit classifier for those classes, as well as a multilabel classifier for the neighor of those classes the built feature vector is 2*N long
Method signatures and docstr... | 9f2fed81672dc222ca52ee4329eac3126b500d21 | <|skeleton|>
class EdgeTransformerLogit:
"""we will get a list of edges belonging to N classes. we train a logit classifier for those classes, as well as a multilabel classifier for the neighor of those classes the built feature vector is 2*N long"""
def __init__(self, nbClass, ndTrnsfLogit):
"""input:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EdgeTransformerLogit:
"""we will get a list of edges belonging to N classes. we train a logit classifier for those classes, as well as a multilabel classifier for the neighor of those classes the built feature vector is 2*N long"""
def __init__(self, nbClass, ndTrnsfLogit):
"""input: - number of ... | the_stack_v2_python_sparse | TranskribusDU/graph/Transformer_Logit.py | Transkribus/TranskribusDU | train | 24 |
a01d95570e45f416e164031cbcfbb3bd53e1e879 | [
"try:\n return cls.doc.GetElement(cls.selection.PickObject(ObjectType.Element, Pick_by_category(built_in_category)))\nexcept OperationCanceledException:\n return",
"try:\n return cls.doc.GetElement(cls.selection.PickObject(ObjectType.Element, Pick_by_class(class_type)))\nexcept OperationCanceledException... | <|body_start_0|>
try:
return cls.doc.GetElement(cls.selection.PickObject(ObjectType.Element, Pick_by_category(built_in_category)))
except OperationCanceledException:
return
<|end_body_0|>
<|body_start_1|>
try:
return cls.doc.GetElement(cls.selection.PickObjec... | Класс с реализацией различных методов выбора элементов. | RB_selections | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RB_selections:
"""Класс с реализацией различных методов выбора элементов."""
def pick_element_by_category(cls, built_in_category):
"""Выбор одного элемента по BuiltInCategory."""
<|body_0|>
def pick_element_by_class(cls, class_type):
"""Выбор одного элемента по к... | stack_v2_sparse_classes_36k_train_005580 | 2,658 | no_license | [
{
"docstring": "Выбор одного элемента по BuiltInCategory.",
"name": "pick_element_by_category",
"signature": "def pick_element_by_category(cls, built_in_category)"
},
{
"docstring": "Выбор одного элемента по категории.",
"name": "pick_element_by_class",
"signature": "def pick_element_by_... | 3 | stack_v2_sparse_classes_30k_train_005223 | Implement the Python class `RB_selections` described below.
Class description:
Класс с реализацией различных методов выбора элементов.
Method signatures and docstrings:
- def pick_element_by_category(cls, built_in_category): Выбор одного элемента по BuiltInCategory.
- def pick_element_by_class(cls, class_type): Выбор... | Implement the Python class `RB_selections` described below.
Class description:
Класс с реализацией различных методов выбора элементов.
Method signatures and docstrings:
- def pick_element_by_category(cls, built_in_category): Выбор одного элемента по BuiltInCategory.
- def pick_element_by_class(cls, class_type): Выбор... | 520c69a2769bb3d9c91cce6da314fdcc239320c4 | <|skeleton|>
class RB_selections:
"""Класс с реализацией различных методов выбора элементов."""
def pick_element_by_category(cls, built_in_category):
"""Выбор одного элемента по BuiltInCategory."""
<|body_0|>
def pick_element_by_class(cls, class_type):
"""Выбор одного элемента по к... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RB_selections:
"""Класс с реализацией различных методов выбора элементов."""
def pick_element_by_category(cls, built_in_category):
"""Выбор одного элемента по BuiltInCategory."""
try:
return cls.doc.GetElement(cls.selection.PickObject(ObjectType.Element, Pick_by_category(built... | the_stack_v2_python_sparse | common_scripts/get_elems/RB_selections.py | NauGaika/RedBimTest | train | 0 |
aa1554d7f54f781914d9c5bbcc51e745b11468bc | [
"super().__init__()\nself.transformer_dim = transformer_dim\nself.transformer = MODELS.build(transformer)\nself.num_multimask_outputs = num_multimask_outputs\nself.iou_token = nn.Embedding(1, transformer_dim)\nself.num_mask_tokens = num_multimask_outputs + 1\nself.mask_tokens = nn.Embedding(self.num_mask_tokens, tr... | <|body_start_0|>
super().__init__()
self.transformer_dim = transformer_dim
self.transformer = MODELS.build(transformer)
self.num_multimask_outputs = num_multimask_outputs
self.iou_token = nn.Embedding(1, transformer_dim)
self.num_mask_tokens = num_multimask_outputs + 1
... | MaskDecoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaskDecoder:
def __init__(self, *, transformer_dim: int, transformer: dict, num_multimask_outputs: int=3, act_cfg: dict=dict(type='GELU'), iou_head_depth: int=3, iou_head_hidden_dim: int=256) -> None:
"""Predicts masks given an image and prompt embeddings, using a tranformer architecture... | stack_v2_sparse_classes_36k_train_005581 | 6,980 | permissive | [
{
"docstring": "Predicts masks given an image and prompt embeddings, using a tranformer architecture. Borrowed from https://github.com/facebookresearch/segment-anything Arguments: transformer_dim (int): the channel dimension of the transformer transformer (nn.Module): the transformer used to predict masks num_m... | 3 | stack_v2_sparse_classes_30k_train_004640 | Implement the Python class `MaskDecoder` described below.
Class description:
Implement the MaskDecoder class.
Method signatures and docstrings:
- def __init__(self, *, transformer_dim: int, transformer: dict, num_multimask_outputs: int=3, act_cfg: dict=dict(type='GELU'), iou_head_depth: int=3, iou_head_hidden_dim: in... | Implement the Python class `MaskDecoder` described below.
Class description:
Implement the MaskDecoder class.
Method signatures and docstrings:
- def __init__(self, *, transformer_dim: int, transformer: dict, num_multimask_outputs: int=3, act_cfg: dict=dict(type='GELU'), iou_head_depth: int=3, iou_head_hidden_dim: in... | 30a3f94f3e2916e27fa38c67cc3b8c69c1893fe8 | <|skeleton|>
class MaskDecoder:
def __init__(self, *, transformer_dim: int, transformer: dict, num_multimask_outputs: int=3, act_cfg: dict=dict(type='GELU'), iou_head_depth: int=3, iou_head_hidden_dim: int=256) -> None:
"""Predicts masks given an image and prompt embeddings, using a tranformer architecture... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MaskDecoder:
def __init__(self, *, transformer_dim: int, transformer: dict, num_multimask_outputs: int=3, act_cfg: dict=dict(type='GELU'), iou_head_depth: int=3, iou_head_hidden_dim: int=256) -> None:
"""Predicts masks given an image and prompt embeddings, using a tranformer architecture. Borrowed fro... | the_stack_v2_python_sparse | projects/sam_inference_demo/sam/modeling/mask_decoder.py | open-mmlab/mmsegmentation | train | 6,534 | |
482bc9c172c73af0f8c321e43a6db2aa9427cdc3 | [
"super(DartsCodec, self).__init__(search_space, **kwargs)\nself.darts_cfg = copy.deepcopy(search_space)\nself.super_net = {'normal': self.darts_cfg.super_network.normal.genotype, 'reduce': self.darts_cfg.super_network.reduce.genotype}\nself.super_net = Config(self.super_net)\nself.steps = self.darts_cfg.super_netwo... | <|body_start_0|>
super(DartsCodec, self).__init__(search_space, **kwargs)
self.darts_cfg = copy.deepcopy(search_space)
self.super_net = {'normal': self.darts_cfg.super_network.normal.genotype, 'reduce': self.darts_cfg.super_network.reduce.genotype}
self.super_net = Config(self.super_net)... | Class of DARTS codec. :param codec_name: this codec name :type codec_name: str :param search_space: search space :type search_space: SearchSpace | DartsCodec | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DartsCodec:
"""Class of DARTS codec. :param codec_name: this codec name :type codec_name: str :param search_space: search space :type search_space: SearchSpace"""
def __init__(self, search_space=None, **kwargs):
"""Init DartsCodec."""
<|body_0|>
def decode(self, code):
... | stack_v2_sparse_classes_36k_train_005582 | 3,854 | permissive | [
{
"docstring": "Init DartsCodec.",
"name": "__init__",
"signature": "def __init__(self, search_space=None, **kwargs)"
},
{
"docstring": "Decode the code to Network Desc. :param code: input code :type code: 2D array of float :return: network desc :rtype: NetworkDesc",
"name": "decode",
"s... | 3 | stack_v2_sparse_classes_30k_train_010721 | Implement the Python class `DartsCodec` described below.
Class description:
Class of DARTS codec. :param codec_name: this codec name :type codec_name: str :param search_space: search space :type search_space: SearchSpace
Method signatures and docstrings:
- def __init__(self, search_space=None, **kwargs): Init DartsCo... | Implement the Python class `DartsCodec` described below.
Class description:
Class of DARTS codec. :param codec_name: this codec name :type codec_name: str :param search_space: search space :type search_space: SearchSpace
Method signatures and docstrings:
- def __init__(self, search_space=None, **kwargs): Init DartsCo... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class DartsCodec:
"""Class of DARTS codec. :param codec_name: this codec name :type codec_name: str :param search_space: search space :type search_space: SearchSpace"""
def __init__(self, search_space=None, **kwargs):
"""Init DartsCodec."""
<|body_0|>
def decode(self, code):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DartsCodec:
"""Class of DARTS codec. :param codec_name: this codec name :type codec_name: str :param search_space: search space :type search_space: SearchSpace"""
def __init__(self, search_space=None, **kwargs):
"""Init DartsCodec."""
super(DartsCodec, self).__init__(search_space, **kwarg... | the_stack_v2_python_sparse | built-in/TensorFlow/Official/cv/image_classification/ResnetVariant_for_TensorFlow/automl/vega/algorithms/nas/darts_cnn/darts_codec.py | Huawei-Ascend/modelzoo | train | 1 |
f679eb629fd41c2e0b277f29881e7b17938d2c09 | [
"acl.enforce('workbooks:get', context.ctx())\nLOG.debug('Fetch workbook [name=%s, namespace=%s]', name, namespace)\nif fields and 'id' not in fields:\n fields.insert(0, 'id')\nr = rest_utils.create_db_retry_object()\ndb_model = r.call(db_api.get_workbook, name, namespace=namespace, fields=fields)\nif fields:\n ... | <|body_start_0|>
acl.enforce('workbooks:get', context.ctx())
LOG.debug('Fetch workbook [name=%s, namespace=%s]', name, namespace)
if fields and 'id' not in fields:
fields.insert(0, 'id')
r = rest_utils.create_db_retry_object()
db_model = r.call(db_api.get_workbook, na... | WorkbooksController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkbooksController:
def get(self, name, namespace='', fields=''):
"""Return the named workbook. :param name: Name of workbook to retrieve. :param namespace: Optional. Namespace of workbook to retrieve. :param fields: Optional. A specified list of fields of the resource to be returned. '... | stack_v2_sparse_classes_36k_train_005583 | 8,629 | permissive | [
{
"docstring": "Return the named workbook. :param name: Name of workbook to retrieve. :param namespace: Optional. Namespace of workbook to retrieve. :param fields: Optional. A specified list of fields of the resource to be returned. 'id' will be included automatically in fields if it's not provided.",
"name... | 5 | stack_v2_sparse_classes_30k_train_009514 | Implement the Python class `WorkbooksController` described below.
Class description:
Implement the WorkbooksController class.
Method signatures and docstrings:
- def get(self, name, namespace='', fields=''): Return the named workbook. :param name: Name of workbook to retrieve. :param namespace: Optional. Namespace of... | Implement the Python class `WorkbooksController` described below.
Class description:
Implement the WorkbooksController class.
Method signatures and docstrings:
- def get(self, name, namespace='', fields=''): Return the named workbook. :param name: Name of workbook to retrieve. :param namespace: Optional. Namespace of... | 7baff017d0cf01d19c44055ad201ca59131b9f94 | <|skeleton|>
class WorkbooksController:
def get(self, name, namespace='', fields=''):
"""Return the named workbook. :param name: Name of workbook to retrieve. :param namespace: Optional. Namespace of workbook to retrieve. :param fields: Optional. A specified list of fields of the resource to be returned. '... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkbooksController:
def get(self, name, namespace='', fields=''):
"""Return the named workbook. :param name: Name of workbook to retrieve. :param namespace: Optional. Namespace of workbook to retrieve. :param fields: Optional. A specified list of fields of the resource to be returned. 'id' will be in... | the_stack_v2_python_sparse | mistral/api/controllers/v2/workbook.py | openstack/mistral | train | 214 | |
76f32816b81a2645b48c5f143d13198f86ec11e7 | [
"try:\n return int(value)\nexcept ValueError:\n raise ValueError('Attempted to set value for an %s field which is not compatible: %s' % (self.typeName(), repr(value)))",
"if isinstance(value, int):\n return 1\nreturn 0",
"try:\n return str(int(value))\nexcept OverflowError:\n base = str(value)\n ... | <|body_start_0|>
try:
return int(value)
except ValueError:
raise ValueError('Attempted to set value for an %s field which is not compatible: %s' % (self.typeName(), repr(value)))
<|end_body_0|>
<|body_start_1|>
if isinstance(value, int):
return 1
retu... | SFInt32 field/event type base-class | _SFInt32 | [
"GPL-1.0-or-later",
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-copyleft",
"LGPL-2.1-or-later",
"GPL-3.0-only",
"LGPL-2.0-or-later",
"GPL-3.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _SFInt32:
"""SFInt32 field/event type base-class"""
def coerce(self, value):
"""Coerce the given value to our type Allowable types: any object with true/false protocol"""
<|body_0|>
def check(self, value):
"""Check that the given value is of exactly expected type... | stack_v2_sparse_classes_36k_train_005584 | 34,853 | permissive | [
{
"docstring": "Coerce the given value to our type Allowable types: any object with true/false protocol",
"name": "coerce",
"signature": "def coerce(self, value)"
},
{
"docstring": "Check that the given value is of exactly expected type",
"name": "check",
"signature": "def check(self, va... | 3 | stack_v2_sparse_classes_30k_train_003433 | Implement the Python class `_SFInt32` described below.
Class description:
SFInt32 field/event type base-class
Method signatures and docstrings:
- def coerce(self, value): Coerce the given value to our type Allowable types: any object with true/false protocol
- def check(self, value): Check that the given value is of ... | Implement the Python class `_SFInt32` described below.
Class description:
SFInt32 field/event type base-class
Method signatures and docstrings:
- def coerce(self, value): Coerce the given value to our type Allowable types: any object with true/false protocol
- def check(self, value): Check that the given value is of ... | 7f600ad153270feff12aa7aa86d7ed0a49ebc71c | <|skeleton|>
class _SFInt32:
"""SFInt32 field/event type base-class"""
def coerce(self, value):
"""Coerce the given value to our type Allowable types: any object with true/false protocol"""
<|body_0|>
def check(self, value):
"""Check that the given value is of exactly expected type... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _SFInt32:
"""SFInt32 field/event type base-class"""
def coerce(self, value):
"""Coerce the given value to our type Allowable types: any object with true/false protocol"""
try:
return int(value)
except ValueError:
raise ValueError('Attempted to set value for... | the_stack_v2_python_sparse | pythonAnimations/pyOpenGLChess/engineDirectory/oglc-env/lib/python2.7/site-packages/vrml/fieldtypes.py | alexus37/AugmentedRealityChess | train | 1 |
5848d7e327481d518f3a0b0e71e18ede93227c19 | [
"l_topic = 'house/schedule/control'\nl_obj = p_schedule_obj\np_pyhouse_obj.Core.MqttApi.MqttPublish(l_topic, l_obj)\nif p_schedule_obj.Sched.Type in ['Lighting', 'Light', 'Outlet']:\n LOG.info('Execute_one_schedule type = Lighting - \"{}\"'.format(p_schedule_obj.Sched.Name))\n lightingActionsApi().DoSchedule(... | <|body_start_0|>
l_topic = 'house/schedule/control'
l_obj = p_schedule_obj
p_pyhouse_obj.Core.MqttApi.MqttPublish(l_topic, l_obj)
if p_schedule_obj.Sched.Type in ['Lighting', 'Light', 'Outlet']:
LOG.info('Execute_one_schedule type = Lighting - "{}"'.format(p_schedule_obj.Sche... | ScheduleExecution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScheduleExecution:
def dispatch_one_schedule(self, p_pyhouse_obj, p_schedule_obj):
"""Send information to one device to execute a schedule. @param p_schedule_obj: ==> ScheduleInformation()"""
<|body_0|>
def execute_schedules_list(p_pyhouse_obj, p_key_list=[]):
"""The... | stack_v2_sparse_classes_36k_train_005585 | 25,512 | permissive | [
{
"docstring": "Send information to one device to execute a schedule. @param p_schedule_obj: ==> ScheduleInformation()",
"name": "dispatch_one_schedule",
"signature": "def dispatch_one_schedule(self, p_pyhouse_obj, p_schedule_obj)"
},
{
"docstring": "The timer calls this with a list of schedules... | 2 | null | Implement the Python class `ScheduleExecution` described below.
Class description:
Implement the ScheduleExecution class.
Method signatures and docstrings:
- def dispatch_one_schedule(self, p_pyhouse_obj, p_schedule_obj): Send information to one device to execute a schedule. @param p_schedule_obj: ==> ScheduleInforma... | Implement the Python class `ScheduleExecution` described below.
Class description:
Implement the ScheduleExecution class.
Method signatures and docstrings:
- def dispatch_one_schedule(self, p_pyhouse_obj, p_schedule_obj): Send information to one device to execute a schedule. @param p_schedule_obj: ==> ScheduleInforma... | a100fc67761a22ae47ed6f21f3c9464e2de5d54f | <|skeleton|>
class ScheduleExecution:
def dispatch_one_schedule(self, p_pyhouse_obj, p_schedule_obj):
"""Send information to one device to execute a schedule. @param p_schedule_obj: ==> ScheduleInformation()"""
<|body_0|>
def execute_schedules_list(p_pyhouse_obj, p_key_list=[]):
"""The... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScheduleExecution:
def dispatch_one_schedule(self, p_pyhouse_obj, p_schedule_obj):
"""Send information to one device to execute a schedule. @param p_schedule_obj: ==> ScheduleInformation()"""
l_topic = 'house/schedule/control'
l_obj = p_schedule_obj
p_pyhouse_obj.Core.MqttApi.M... | the_stack_v2_python_sparse | Project/src/Modules/House/Schedule/schedule.py | DBrianKimmel/PyHouse | train | 3 | |
455bf71cc6525a2be84da052715dc471d701bae6 | [
"assert isinstance(pot, NFWPotential), 'pot= must be potential.NFWPotential'\nisotropicsphericaldf.__init__(self, pot=pot, rmax=rmax, ro=ro, vo=vo)\nself._Etildemax = pot._amp / pot.a\nself._fEnorm = 0.091968 ** widrow / (4.0 * numpy.pi) / pot.a ** 1.5 / pot._amp ** 0.5\nself._widrow = widrow\nself._Etildemin = -po... | <|body_start_0|>
assert isinstance(pot, NFWPotential), 'pot= must be potential.NFWPotential'
isotropicsphericaldf.__init__(self, pot=pot, rmax=rmax, ro=ro, vo=vo)
self._Etildemax = pot._amp / pot.a
self._fEnorm = 0.091968 ** widrow / (4.0 * numpy.pi) / pot.a ** 1.5 / pot._amp ** 0.5
... | Class that implements the approximate isotropic spherical NFW DF (either `Widrow 2000 <https://ui.adsabs.harvard.edu/abs/2000ApJS..131...39W/abstract>`__ or an improved fit by Lane et al. 2021). | isotropicNFWdf | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class isotropicNFWdf:
"""Class that implements the approximate isotropic spherical NFW DF (either `Widrow 2000 <https://ui.adsabs.harvard.edu/abs/2000ApJS..131...39W/abstract>`__ or an improved fit by Lane et al. 2021)."""
def __init__(self, pot=None, widrow=False, rmax=10000.0, ro=None, vo=None):... | stack_v2_sparse_classes_36k_train_005586 | 3,353 | permissive | [
{
"docstring": "NAME: __init__ PURPOSE: Initialize an isotropic NFW distribution function INPUT: pot= (None) NFW Potential instance widrow= (False) if True, use the approximate form from Widrow (2000), otherwise use improved fit that has <~1e-5 relative density errors rmax= (1e4) maximum radius to consider (can... | 2 | stack_v2_sparse_classes_30k_train_010037 | Implement the Python class `isotropicNFWdf` described below.
Class description:
Class that implements the approximate isotropic spherical NFW DF (either `Widrow 2000 <https://ui.adsabs.harvard.edu/abs/2000ApJS..131...39W/abstract>`__ or an improved fit by Lane et al. 2021).
Method signatures and docstrings:
- def __i... | Implement the Python class `isotropicNFWdf` described below.
Class description:
Class that implements the approximate isotropic spherical NFW DF (either `Widrow 2000 <https://ui.adsabs.harvard.edu/abs/2000ApJS..131...39W/abstract>`__ or an improved fit by Lane et al. 2021).
Method signatures and docstrings:
- def __i... | a46619fd4f5979acfccad23f4d57503033f440c5 | <|skeleton|>
class isotropicNFWdf:
"""Class that implements the approximate isotropic spherical NFW DF (either `Widrow 2000 <https://ui.adsabs.harvard.edu/abs/2000ApJS..131...39W/abstract>`__ or an improved fit by Lane et al. 2021)."""
def __init__(self, pot=None, widrow=False, rmax=10000.0, ro=None, vo=None):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class isotropicNFWdf:
"""Class that implements the approximate isotropic spherical NFW DF (either `Widrow 2000 <https://ui.adsabs.harvard.edu/abs/2000ApJS..131...39W/abstract>`__ or an improved fit by Lane et al. 2021)."""
def __init__(self, pot=None, widrow=False, rmax=10000.0, ro=None, vo=None):
"""N... | the_stack_v2_python_sparse | galpy/df/isotropicNFWdf.py | jobovy/galpy | train | 182 |
08a9bb372d73c7a681974837030963b6634e078e | [
"threading.Thread.__init__(self)\nself.__port_queue = port_queue\nself.__ip = ip\nself.__timeout = timeout",
"while True:\n if self.__port_queue.empty():\n break\n OPEN_MSG = '% 6d [OPEN]\\n'\n port = self.__port_queue.get(timeout=0.5)\n ip = self.__ip\n timeout = self.__timeout\n try:\n ... | <|body_start_0|>
threading.Thread.__init__(self)
self.__port_queue = port_queue
self.__ip = ip
self.__timeout = timeout
<|end_body_0|>
<|body_start_1|>
while True:
if self.__port_queue.empty():
break
OPEN_MSG = '% 6d [OPEN]\n'
... | PortScan | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PortScan:
def __init__(self, port_queue, ip, timeout=3):
"""初始化参数"""
<|body_0|>
def run(self):
"""多线程实际调用的方法,如果端口队列不为空,循环执行"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
threading.Thread.__init__(self)
self.__port_queue = port_queue
... | stack_v2_sparse_classes_36k_train_005587 | 11,644 | no_license | [
{
"docstring": "初始化参数",
"name": "__init__",
"signature": "def __init__(self, port_queue, ip, timeout=3)"
},
{
"docstring": "多线程实际调用的方法,如果端口队列不为空,循环执行",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001528 | Implement the Python class `PortScan` described below.
Class description:
Implement the PortScan class.
Method signatures and docstrings:
- def __init__(self, port_queue, ip, timeout=3): 初始化参数
- def run(self): 多线程实际调用的方法,如果端口队列不为空,循环执行 | Implement the Python class `PortScan` described below.
Class description:
Implement the PortScan class.
Method signatures and docstrings:
- def __init__(self, port_queue, ip, timeout=3): 初始化参数
- def run(self): 多线程实际调用的方法,如果端口队列不为空,循环执行
<|skeleton|>
class PortScan:
def __init__(self, port_queue, ip, timeout=3):
... | 03ea528b0405e3602e7cdab82dc98ed4ada79e0f | <|skeleton|>
class PortScan:
def __init__(self, port_queue, ip, timeout=3):
"""初始化参数"""
<|body_0|>
def run(self):
"""多线程实际调用的方法,如果端口队列不为空,循环执行"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PortScan:
def __init__(self, port_queue, ip, timeout=3):
"""初始化参数"""
threading.Thread.__init__(self)
self.__port_queue = port_queue
self.__ip = ip
self.__timeout = timeout
def run(self):
"""多线程实际调用的方法,如果端口队列不为空,循环执行"""
while True:
if sel... | the_stack_v2_python_sparse | Python/python_saomiao/main.py | QiYi92/StudyLab | train | 3 | |
583c296d35e1f7ede97a1751569f0f752c07c074 | [
"if not email:\n raise ValueError(_('User must have an email address.'))\nemail = self.normalize_email(email)\nproj = Project.objects.all().first()\nprint('project>')\nprint(proj)\nif customer is not None:\n user = self.model(email=email, name=name, customer=customer, project=proj)\nelse:\n user = self.mod... | <|body_start_0|>
if not email:
raise ValueError(_('User must have an email address.'))
email = self.normalize_email(email)
proj = Project.objects.all().first()
print('project>')
print(proj)
if customer is not None:
user = self.model(email=email, na... | Helps Django work with custom user model | ProjectCustomUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectCustomUserManager:
"""Helps Django work with custom user model"""
def create_user(self, name, email, password=None, customer=None):
"""Create new custom user object"""
<|body_0|>
def create_superuser(self, name, email, password):
"""Create and saves new su... | stack_v2_sparse_classes_36k_train_005588 | 19,158 | no_license | [
{
"docstring": "Create new custom user object",
"name": "create_user",
"signature": "def create_user(self, name, email, password=None, customer=None)"
},
{
"docstring": "Create and saves new super custom user object",
"name": "create_superuser",
"signature": "def create_superuser(self, n... | 2 | stack_v2_sparse_classes_30k_train_019329 | Implement the Python class `ProjectCustomUserManager` described below.
Class description:
Helps Django work with custom user model
Method signatures and docstrings:
- def create_user(self, name, email, password=None, customer=None): Create new custom user object
- def create_superuser(self, name, email, password): Cr... | Implement the Python class `ProjectCustomUserManager` described below.
Class description:
Helps Django work with custom user model
Method signatures and docstrings:
- def create_user(self, name, email, password=None, customer=None): Create new custom user object
- def create_superuser(self, name, email, password): Cr... | 7686703ce5783dd4a48dc1d9600cda01aa554faa | <|skeleton|>
class ProjectCustomUserManager:
"""Helps Django work with custom user model"""
def create_user(self, name, email, password=None, customer=None):
"""Create new custom user object"""
<|body_0|>
def create_superuser(self, name, email, password):
"""Create and saves new su... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectCustomUserManager:
"""Helps Django work with custom user model"""
def create_user(self, name, email, password=None, customer=None):
"""Create new custom user object"""
if not email:
raise ValueError(_('User must have an email address.'))
email = self.normalize_e... | the_stack_v2_python_sparse | scrap_trade_proj/customers/models.py | Horac-Bouthon/scrap-trade-4 | train | 0 |
54ce79d837313ab427d49bdbf1c970bb72252d8e | [
"self.max_parallel_metadata_fetch_full_percentage = max_parallel_metadata_fetch_full_percentage\nself.max_parallel_metadata_fetch_incremental_percentage = max_parallel_metadata_fetch_incremental_percentage\nself.max_parallel_read_write_full_percentage = max_parallel_read_write_full_percentage\nself.max_parallel_rea... | <|body_start_0|>
self.max_parallel_metadata_fetch_full_percentage = max_parallel_metadata_fetch_full_percentage
self.max_parallel_metadata_fetch_incremental_percentage = max_parallel_metadata_fetch_incremental_percentage
self.max_parallel_read_write_full_percentage = max_parallel_read_write_full... | Implementation of the 'NasSourceThrottlingParams' model. Specifies the NAS specific source throttling parameters during source registration or during backup of the source. Attributes: max_parallel_metadata_fetch_full_percentage (int): Specifies the percentage value of maximum concurrent metadata to be fetched during fu... | NasSourceThrottlingParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NasSourceThrottlingParams:
"""Implementation of the 'NasSourceThrottlingParams' model. Specifies the NAS specific source throttling parameters during source registration or during backup of the source. Attributes: max_parallel_metadata_fetch_full_percentage (int): Specifies the percentage value o... | stack_v2_sparse_classes_36k_train_005589 | 3,720 | permissive | [
{
"docstring": "Constructor for the NasSourceThrottlingParams class",
"name": "__init__",
"signature": "def __init__(self, max_parallel_metadata_fetch_full_percentage=None, max_parallel_metadata_fetch_incremental_percentage=None, max_parallel_read_write_full_percentage=None, max_parallel_read_write_incr... | 2 | null | Implement the Python class `NasSourceThrottlingParams` described below.
Class description:
Implementation of the 'NasSourceThrottlingParams' model. Specifies the NAS specific source throttling parameters during source registration or during backup of the source. Attributes: max_parallel_metadata_fetch_full_percentage ... | Implement the Python class `NasSourceThrottlingParams` described below.
Class description:
Implementation of the 'NasSourceThrottlingParams' model. Specifies the NAS specific source throttling parameters during source registration or during backup of the source. Attributes: max_parallel_metadata_fetch_full_percentage ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class NasSourceThrottlingParams:
"""Implementation of the 'NasSourceThrottlingParams' model. Specifies the NAS specific source throttling parameters during source registration or during backup of the source. Attributes: max_parallel_metadata_fetch_full_percentage (int): Specifies the percentage value o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NasSourceThrottlingParams:
"""Implementation of the 'NasSourceThrottlingParams' model. Specifies the NAS specific source throttling parameters during source registration or during backup of the source. Attributes: max_parallel_metadata_fetch_full_percentage (int): Specifies the percentage value of maximum con... | the_stack_v2_python_sparse | cohesity_management_sdk/models/nas_source_throttling_params.py | cohesity/management-sdk-python | train | 24 |
e4be1aa0047dc304797bd6914941038245f5307f | [
"a = ReadModels.Distribution.Flat(10)\nfor i in a:\n self.assert_(i == 1, 'Values in Flat array are not equal to 1.')\nself.assert_(len(a) == 10, 'Flat array is not the right size ')",
"a = ReadModels.Distribution.Triangle(50, 100, 150)\nz = 1\nfor i in a:\n self.assert_(i <= z, 'Values must not rise in Tri... | <|body_start_0|>
a = ReadModels.Distribution.Flat(10)
for i in a:
self.assert_(i == 1, 'Values in Flat array are not equal to 1.')
self.assert_(len(a) == 10, 'Flat array is not the right size ')
<|end_body_0|>
<|body_start_1|>
a = ReadModels.Distribution.Triangle(50, 100, 15... | Unit tests for Read Models | Test | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test:
"""Unit tests for Read Models"""
def testFlat(self):
"""test out the flat model"""
<|body_0|>
def testTriangle(self):
"""test the triangle model"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
a = ReadModels.Distribution.Flat(10)
f... | stack_v2_sparse_classes_36k_train_005590 | 927 | no_license | [
{
"docstring": "test out the flat model",
"name": "testFlat",
"signature": "def testFlat(self)"
},
{
"docstring": "test the triangle model",
"name": "testTriangle",
"signature": "def testTriangle(self)"
}
] | 2 | null | Implement the Python class `Test` described below.
Class description:
Unit tests for Read Models
Method signatures and docstrings:
- def testFlat(self): test out the flat model
- def testTriangle(self): test the triangle model | Implement the Python class `Test` described below.
Class description:
Unit tests for Read Models
Method signatures and docstrings:
- def testFlat(self): test out the flat model
- def testTriangle(self): test the triangle model
<|skeleton|>
class Test:
"""Unit tests for Read Models"""
def testFlat(self):
... | a6db43f36afd71f7e31fd4b071f73db0878b10e3 | <|skeleton|>
class Test:
"""Unit tests for Read Models"""
def testFlat(self):
"""test out the flat model"""
<|body_0|>
def testTriangle(self):
"""test the triangle model"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test:
"""Unit tests for Read Models"""
def testFlat(self):
"""test out the flat model"""
a = ReadModels.Distribution.Flat(10)
for i in a:
self.assert_(i == 1, 'Values in Flat array are not equal to 1.')
self.assert_(len(a) == 10, 'Flat array is not the right si... | the_stack_v2_python_sparse | Epigenetics/WaveGenerator/Utilities/TestReadModels.py | jmrinaldi/epigenetics-software | train | 0 |
d9c3c4cae259d1e1385aa58aec2e53d8bb97f985 | [
"if isinstance(cache, DiskCache):\n return cache\nreturn DiskCache(directory=self.path, min_file_size=0, size_limit=self.maxsize, eviction_policy=self.eviction)",
"if self.maxsize == 0:\n return\nwith self.newcache(cache) as disk:\n if disk.get(VERSION_KEY) != VERSION:\n LOGS.info('%s version is i... | <|body_start_0|>
if isinstance(cache, DiskCache):
return cache
return DiskCache(directory=self.path, min_file_size=0, size_limit=self.maxsize, eviction_policy=self.eviction)
<|end_body_0|>
<|body_start_1|>
if self.maxsize == 0:
return
with self.newcache(cache) as... | The disk cache configuration | DiskCacheConfig | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiskCacheConfig:
"""The disk cache configuration"""
def newcache(self, cache: Optional[DiskCache]=None) -> DiskCache:
"""create new cache"""
<|body_0|>
def insert(self, items: Union[Iterable[TaskCacheList], TaskCacheList], version: int=APPVERSION, cache: Optional[DiskCac... | stack_v2_sparse_classes_36k_train_005591 | 9,735 | no_license | [
{
"docstring": "create new cache",
"name": "newcache",
"signature": "def newcache(self, cache: Optional[DiskCache]=None) -> DiskCache"
},
{
"docstring": "add items to the disk",
"name": "insert",
"signature": "def insert(self, items: Union[Iterable[TaskCacheList], TaskCacheList], version... | 6 | null | Implement the Python class `DiskCacheConfig` described below.
Class description:
The disk cache configuration
Method signatures and docstrings:
- def newcache(self, cache: Optional[DiskCache]=None) -> DiskCache: create new cache
- def insert(self, items: Union[Iterable[TaskCacheList], TaskCacheList], version: int=APP... | Implement the Python class `DiskCacheConfig` described below.
Class description:
The disk cache configuration
Method signatures and docstrings:
- def newcache(self, cache: Optional[DiskCache]=None) -> DiskCache: create new cache
- def insert(self, items: Union[Iterable[TaskCacheList], TaskCacheList], version: int=APP... | f9534e4fff9775ff45d08d401de61015d4a69e76 | <|skeleton|>
class DiskCacheConfig:
"""The disk cache configuration"""
def newcache(self, cache: Optional[DiskCache]=None) -> DiskCache:
"""create new cache"""
<|body_0|>
def insert(self, items: Union[Iterable[TaskCacheList], TaskCacheList], version: int=APPVERSION, cache: Optional[DiskCac... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiskCacheConfig:
"""The disk cache configuration"""
def newcache(self, cache: Optional[DiskCache]=None) -> DiskCache:
"""create new cache"""
if isinstance(cache, DiskCache):
return cache
return DiskCache(directory=self.path, min_file_size=0, size_limit=self.maxsize, ev... | the_stack_v2_python_sparse | src/peakcalling/model/_diskcache.py | depixusgenome/trackanalysis | train | 0 |
ad5481e9b26a8ea9f9d56a19ed369ce6fad3ce59 | [
"user = request.user\ncheck_user_status(user)\nuser_id = user.id\nvalidate(instance=request.data, schema=schemas.post_schema)\nbody = request.data\nbody['owner_user_id'] = user_id\nRestaurantPost.field_validate(body)\npost = RestaurantPost.insert(body, request)\nreturn JsonResponse(model_to_json(post))",
"user = ... | <|body_start_0|>
user = request.user
check_user_status(user)
user_id = user.id
validate(instance=request.data, schema=schemas.post_schema)
body = request.data
body['owner_user_id'] = user_id
RestaurantPost.field_validate(body)
post = RestaurantPost.insert(... | Restaurant posts view | PostView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostView:
"""Restaurant posts view"""
def post(self, request):
"""Insert a new post for a restaurant"""
<|body_0|>
def get(self, request):
"""Get all posts for a restaurant (for ROs)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
user = request... | stack_v2_sparse_classes_36k_train_005592 | 19,356 | no_license | [
{
"docstring": "Insert a new post for a restaurant",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "Get all posts for a restaurant (for ROs)",
"name": "get",
"signature": "def get(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004687 | Implement the Python class `PostView` described below.
Class description:
Restaurant posts view
Method signatures and docstrings:
- def post(self, request): Insert a new post for a restaurant
- def get(self, request): Get all posts for a restaurant (for ROs) | Implement the Python class `PostView` described below.
Class description:
Restaurant posts view
Method signatures and docstrings:
- def post(self, request): Insert a new post for a restaurant
- def get(self, request): Get all posts for a restaurant (for ROs)
<|skeleton|>
class PostView:
"""Restaurant posts view"... | 2707062c9a9a8bb4baca955e8a60ba08cc9f8953 | <|skeleton|>
class PostView:
"""Restaurant posts view"""
def post(self, request):
"""Insert a new post for a restaurant"""
<|body_0|>
def get(self, request):
"""Get all posts for a restaurant (for ROs)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PostView:
"""Restaurant posts view"""
def post(self, request):
"""Insert a new post for a restaurant"""
user = request.user
check_user_status(user)
user_id = user.id
validate(instance=request.data, schema=schemas.post_schema)
body = request.data
bod... | the_stack_v2_python_sparse | backend/restaurant/views.py | MochiTarts/Find-Dining-The-Bridge | train | 1 |
7e1c9365b4a178d5170fc4aa38124f6a35b0cc45 | [
"assert self.id\nevents = ['push', 'pull_request']\nconfig = {'url': flask.url_for('builds.hook', id=self.id, _external=True), 'content_type': 'json'}\ntry:\n gh_hook = self.project.gh.hook(self.gh_id) if self.gh_id not in (None, MISSING_ID) else None\n if gh_hook:\n if gh_hook.events != events or gh_h... | <|body_start_0|>
assert self.id
events = ['push', 'pull_request']
config = {'url': flask.url_for('builds.hook', id=self.id, _external=True), 'content_type': 'json'}
try:
gh_hook = self.project.gh.hook(self.gh_id) if self.gh_id not in (None, MISSING_ID) else None
i... | Reflects a GitHub hook. | Hook | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Hook:
"""Reflects a GitHub hook."""
def ensure(self):
"""If the corresponding GitHub hook does not exist, creates it. If it exists, but has wrong configuration, re-configures it. Returns True if there weren't GitHub API errors; False otherwise."""
<|body_0|>
def delete(s... | stack_v2_sparse_classes_36k_train_005593 | 32,822 | no_license | [
{
"docstring": "If the corresponding GitHub hook does not exist, creates it. If it exists, but has wrong configuration, re-configures it. Returns True if there weren't GitHub API errors; False otherwise.",
"name": "ensure",
"signature": "def ensure(self)"
},
{
"docstring": "Deletes the project h... | 2 | stack_v2_sparse_classes_30k_train_006220 | Implement the Python class `Hook` described below.
Class description:
Reflects a GitHub hook.
Method signatures and docstrings:
- def ensure(self): If the corresponding GitHub hook does not exist, creates it. If it exists, but has wrong configuration, re-configures it. Returns True if there weren't GitHub API errors;... | Implement the Python class `Hook` described below.
Class description:
Reflects a GitHub hook.
Method signatures and docstrings:
- def ensure(self): If the corresponding GitHub hook does not exist, creates it. If it exists, but has wrong configuration, re-configures it. Returns True if there weren't GitHub API errors;... | 368ceb992b7b9b6ceb099570f9291655cad9e96c | <|skeleton|>
class Hook:
"""Reflects a GitHub hook."""
def ensure(self):
"""If the corresponding GitHub hook does not exist, creates it. If it exists, but has wrong configuration, re-configures it. Returns True if there weren't GitHub API errors; False otherwise."""
<|body_0|>
def delete(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Hook:
"""Reflects a GitHub hook."""
def ensure(self):
"""If the corresponding GitHub hook does not exist, creates it. If it exists, but has wrong configuration, re-configures it. Returns True if there weren't GitHub API errors; False otherwise."""
assert self.id
events = ['push', ... | the_stack_v2_python_sparse | kozmic/models.py | aromanovich/kozmic-ci | train | 26 |
42410afe32690036d5cf0124bf2b888b150031b9 | [
"auth = secrets.token_hex(64)\nself.server = ServerThread(source=source, auth=auth, bundlesize=bundlesize, bundlewait=bundlewait, in_memory=in_memory, no_confirm=no_confirm, max_retries=max_retries, eager=eager, address=bind, forever_mode=forever_mode, restart_mode=restart_mode, redirect_failures=redirect_failures)... | <|body_start_0|>
auth = secrets.token_hex(64)
self.server = ServerThread(source=source, auth=auth, bundlesize=bundlesize, bundlewait=bundlewait, in_memory=in_memory, no_confirm=no_confirm, max_retries=max_retries, eager=eager, address=bind, forever_mode=forever_mode, restart_mode=restart_mode, redirect_... | Run server with remote clients via external launcher (e.g., MPI). | RemoteCluster | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RemoteCluster:
"""Run server with remote clients via external launcher (e.g., MPI)."""
def __init__(self: RemoteCluster, source: Iterable[str]=None, num_tasks: int=1, template: str=DEFAULT_TEMPLATE, bundlesize: int=DEFAULT_BUNDLESIZE, bundlewait: int=DEFAULT_BUNDLEWAIT, forever_mode: bool=Fa... | stack_v2_sparse_classes_36k_train_005594 | 18,159 | permissive | [
{
"docstring": "Initialize server and client threads with external launcher.",
"name": "__init__",
"signature": "def __init__(self: RemoteCluster, source: Iterable[str]=None, num_tasks: int=1, template: str=DEFAULT_TEMPLATE, bundlesize: int=DEFAULT_BUNDLESIZE, bundlewait: int=DEFAULT_BUNDLEWAIT, forever... | 3 | stack_v2_sparse_classes_30k_test_000374 | Implement the Python class `RemoteCluster` described below.
Class description:
Run server with remote clients via external launcher (e.g., MPI).
Method signatures and docstrings:
- def __init__(self: RemoteCluster, source: Iterable[str]=None, num_tasks: int=1, template: str=DEFAULT_TEMPLATE, bundlesize: int=DEFAULT_B... | Implement the Python class `RemoteCluster` described below.
Class description:
Run server with remote clients via external launcher (e.g., MPI).
Method signatures and docstrings:
- def __init__(self: RemoteCluster, source: Iterable[str]=None, num_tasks: int=1, template: str=DEFAULT_TEMPLATE, bundlesize: int=DEFAULT_B... | e142376249e0fe3de624790600f3c5e99022e047 | <|skeleton|>
class RemoteCluster:
"""Run server with remote clients via external launcher (e.g., MPI)."""
def __init__(self: RemoteCluster, source: Iterable[str]=None, num_tasks: int=1, template: str=DEFAULT_TEMPLATE, bundlesize: int=DEFAULT_BUNDLESIZE, bundlewait: int=DEFAULT_BUNDLEWAIT, forever_mode: bool=Fa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RemoteCluster:
"""Run server with remote clients via external launcher (e.g., MPI)."""
def __init__(self: RemoteCluster, source: Iterable[str]=None, num_tasks: int=1, template: str=DEFAULT_TEMPLATE, bundlesize: int=DEFAULT_BUNDLESIZE, bundlewait: int=DEFAULT_BUNDLEWAIT, forever_mode: bool=False, restart_... | the_stack_v2_python_sparse | src/hypershell/cluster/remote.py | glentner/hyper-shell | train | 20 |
3ed8ac44356e6851334db0d09f2395d2ed4f7d1c | [
"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... | ClaraServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClaraServicer:
def Stop(self, request, context):
"""Requests the termination of Clara Platform Server and associated resource cleanup."""
<|body_0|>
def Utilization(self, request, context):
"""Requests utilization data for all Clara Platform managed GPUs."""
... | stack_v2_sparse_classes_36k_train_005595 | 4,175 | permissive | [
{
"docstring": "Requests the termination of Clara Platform Server and associated resource cleanup.",
"name": "Stop",
"signature": "def Stop(self, request, context)"
},
{
"docstring": "Requests utilization data for all Clara Platform managed GPUs.",
"name": "Utilization",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_train_015918 | Implement the Python class `ClaraServicer` described below.
Class description:
Implement the ClaraServicer class.
Method signatures and docstrings:
- def Stop(self, request, context): Requests the termination of Clara Platform Server and associated resource cleanup.
- def Utilization(self, request, context): Requests... | Implement the Python class `ClaraServicer` described below.
Class description:
Implement the ClaraServicer class.
Method signatures and docstrings:
- def Stop(self, request, context): Requests the termination of Clara Platform Server and associated resource cleanup.
- def Utilization(self, request, context): Requests... | 0d2e328f238bbbe127023bc834e12811df6f4a27 | <|skeleton|>
class ClaraServicer:
def Stop(self, request, context):
"""Requests the termination of Clara Platform Server and associated resource cleanup."""
<|body_0|>
def Utilization(self, request, context):
"""Requests utilization data for all Clara Platform managed GPUs."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClaraServicer:
def Stop(self, request, context):
"""Requests the termination of Clara Platform Server and associated resource cleanup."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not impleme... | the_stack_v2_python_sparse | nvidia_clara/grpc/clara_pb2_grpc.py | DeepHiveMind/clara-platform-python-client | train | 2 | |
257624efba8fa3b5931dd0195ad37a78b24757a8 | [
"with self.conn:\n with self.conn.cursor() as curs:\n pextra.execute_values(curs, 'INSERT INTO KibotDailyData (trade_symbol_id, date, open, high, low, close, volume) VALUES %s ON CONFLICT DO NOTHING', df.to_dict('records'), template='(%(trade_symbol_id)s, %(date)s, %(open)s, %(high)s, %(low)s, %(close)s, ... | <|body_start_0|>
with self.conn:
with self.conn.cursor() as curs:
pextra.execute_values(curs, 'INSERT INTO KibotDailyData (trade_symbol_id, date, open, high, low, close, volume) VALUES %s ON CONFLICT DO NOTHING', df.to_dict('records'), template='(%(trade_symbol_id)s, %(date)s, %(open... | Manager of CRUD operations on a database defined in `im/db`. | KibotSqlWriterBackend | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KibotSqlWriterBackend:
"""Manager of CRUD operations on a database defined in `im/db`."""
def insert_bulk_daily_data(self, df: pd.DataFrame) -> None:
"""Insert daily data for a particular TradeSymbol entry in bulk. :param df: a dataframe from s3"""
<|body_0|>
def insert_... | stack_v2_sparse_classes_36k_train_005596 | 5,041 | permissive | [
{
"docstring": "Insert daily data for a particular TradeSymbol entry in bulk. :param df: a dataframe from s3",
"name": "insert_bulk_daily_data",
"signature": "def insert_bulk_daily_data(self, df: pd.DataFrame) -> None"
},
{
"docstring": "Insert daily data for a particular TradeSymbol entry.",
... | 5 | stack_v2_sparse_classes_30k_test_001125 | Implement the Python class `KibotSqlWriterBackend` described below.
Class description:
Manager of CRUD operations on a database defined in `im/db`.
Method signatures and docstrings:
- def insert_bulk_daily_data(self, df: pd.DataFrame) -> None: Insert daily data for a particular TradeSymbol entry in bulk. :param df: a... | Implement the Python class `KibotSqlWriterBackend` described below.
Class description:
Manager of CRUD operations on a database defined in `im/db`.
Method signatures and docstrings:
- def insert_bulk_daily_data(self, df: pd.DataFrame) -> None: Insert daily data for a particular TradeSymbol entry in bulk. :param df: a... | 363c59fa29df2ba2719cbad2f8a19ae12cc54a92 | <|skeleton|>
class KibotSqlWriterBackend:
"""Manager of CRUD operations on a database defined in `im/db`."""
def insert_bulk_daily_data(self, df: pd.DataFrame) -> None:
"""Insert daily data for a particular TradeSymbol entry in bulk. :param df: a dataframe from s3"""
<|body_0|>
def insert_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KibotSqlWriterBackend:
"""Manager of CRUD operations on a database defined in `im/db`."""
def insert_bulk_daily_data(self, df: pd.DataFrame) -> None:
"""Insert daily data for a particular TradeSymbol entry in bulk. :param df: a dataframe from s3"""
with self.conn:
with self.co... | the_stack_v2_python_sparse | im/kibot/kibot_sql_writer_backend.py | srlindemann/amp | train | 0 |
16bc8ecb17588632994166b86d86fe43af14e912 | [
"with self.settings(FEATURES={'MITXONLINE_LOGIN': True}):\n coupon = CouponFactory.create(program=True)\n next_url = f'/dashboard/?coupon={coupon.coupon_code}'\n response = self.client.get(f\"{reverse('signin')}?{urlencode({'next': next_url})}\")\n redirect_params = urlencode({'next': next_url, 'program... | <|body_start_0|>
with self.settings(FEATURES={'MITXONLINE_LOGIN': True}):
coupon = CouponFactory.create(program=True)
next_url = f'/dashboard/?coupon={coupon.coupon_code}'
response = self.client.get(f"{reverse('signin')}?{urlencode({'next': next_url})}")
redirect_... | Tests for the sign in page | TestSignIn | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSignIn:
"""Tests for the sign in page"""
def test_login_program_coupon_redirect(self):
"""Test that the login page redirects if the next url has a coupon for a program"""
<|body_0|>
def test_login_course_coupon_redirect(self):
"""Test that the login page redi... | stack_v2_sparse_classes_36k_train_005597 | 36,848 | permissive | [
{
"docstring": "Test that the login page redirects if the next url has a coupon for a program",
"name": "test_login_program_coupon_redirect",
"signature": "def test_login_program_coupon_redirect(self)"
},
{
"docstring": "Test that the login page redirects if the next url has a coupon for a cours... | 2 | null | Implement the Python class `TestSignIn` described below.
Class description:
Tests for the sign in page
Method signatures and docstrings:
- def test_login_program_coupon_redirect(self): Test that the login page redirects if the next url has a coupon for a program
- def test_login_course_coupon_redirect(self): Test tha... | Implement the Python class `TestSignIn` described below.
Class description:
Tests for the sign in page
Method signatures and docstrings:
- def test_login_program_coupon_redirect(self): Test that the login page redirects if the next url has a coupon for a program
- def test_login_course_coupon_redirect(self): Test tha... | d6564caca0b7bbfd31e67a751564107fd17d6eb0 | <|skeleton|>
class TestSignIn:
"""Tests for the sign in page"""
def test_login_program_coupon_redirect(self):
"""Test that the login page redirects if the next url has a coupon for a program"""
<|body_0|>
def test_login_course_coupon_redirect(self):
"""Test that the login page redi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestSignIn:
"""Tests for the sign in page"""
def test_login_program_coupon_redirect(self):
"""Test that the login page redirects if the next url has a coupon for a program"""
with self.settings(FEATURES={'MITXONLINE_LOGIN': True}):
coupon = CouponFactory.create(program=True)
... | the_stack_v2_python_sparse | ui/views_test.py | mitodl/micromasters | train | 35 |
fa37ba43d9881aa3a47fa4d92c9d2ca7d2dafe27 | [
"init_res = super(ResUserInherit, self).__init__(pool, cr)\nself.SELF_WRITEABLE_FIELDS = list(self.SELF_WRITEABLE_FIELDS)\nself.SELF_WRITEABLE_FIELDS.extend(['wx_user_ids'])\nself.SELF_READABLE_FIELDS = list(self.SELF_READABLE_FIELDS)\nself.SELF_READABLE_FIELDS.extend(['wx_user_ids'])\nreturn init_res",
"check_re... | <|body_start_0|>
init_res = super(ResUserInherit, self).__init__(pool, cr)
self.SELF_WRITEABLE_FIELDS = list(self.SELF_WRITEABLE_FIELDS)
self.SELF_WRITEABLE_FIELDS.extend(['wx_user_ids'])
self.SELF_READABLE_FIELDS = list(self.SELF_READABLE_FIELDS)
self.SELF_READABLE_FIELDS.extend... | ResUserInherit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResUserInherit:
def __init__(self, pool, cr):
"""Override of __init__ to add access rights on display_employees_suggestions fields. Access rights are disabled by default, but allowed on some specific fields defined in self.SELF_{READ/WRITE}ABLE_FIELDS."""
<|body_0|>
def _che... | stack_v2_sparse_classes_36k_train_005598 | 3,012 | no_license | [
{
"docstring": "Override of __init__ to add access rights on display_employees_suggestions fields. Access rights are disabled by default, but allowed on some specific fields defined in self.SELF_{READ/WRITE}ABLE_FIELDS.",
"name": "__init__",
"signature": "def __init__(self, pool, cr)"
},
{
"docs... | 4 | stack_v2_sparse_classes_30k_val_001172 | Implement the Python class `ResUserInherit` described below.
Class description:
Implement the ResUserInherit class.
Method signatures and docstrings:
- def __init__(self, pool, cr): Override of __init__ to add access rights on display_employees_suggestions fields. Access rights are disabled by default, but allowed on... | Implement the Python class `ResUserInherit` described below.
Class description:
Implement the ResUserInherit class.
Method signatures and docstrings:
- def __init__(self, pool, cr): Override of __init__ to add access rights on display_employees_suggestions fields. Access rights are disabled by default, but allowed on... | 13b428a5c4ade6278e3e5e996ef10d9fb0fea4b9 | <|skeleton|>
class ResUserInherit:
def __init__(self, pool, cr):
"""Override of __init__ to add access rights on display_employees_suggestions fields. Access rights are disabled by default, but allowed on some specific fields defined in self.SELF_{READ/WRITE}ABLE_FIELDS."""
<|body_0|>
def _che... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResUserInherit:
def __init__(self, pool, cr):
"""Override of __init__ to add access rights on display_employees_suggestions fields. Access rights are disabled by default, but allowed on some specific fields defined in self.SELF_{READ/WRITE}ABLE_FIELDS."""
init_res = super(ResUserInherit, self)... | the_stack_v2_python_sparse | mdias_addons/funenc_wechat/models/res_user.py | rezaghanimi/main_mdias | train | 0 | |
86c7a1aeeb13f4a3527cb6a2b3ac757a1b9f78dd | [
"n_samples, n_features = X.shape\nself.classes = np.unique(y)\nn_classes = len(self.classes)\nself.phi = np.zeros((n_classes, 1))\nself.means = np.zeros((n_classes, n_features))\nself.sigma = 0\nfor i in range(n_classes):\n indexes = np.flatnonzero(y == self.classes[i])\n self.phi[i] = len(indexes) / n_sample... | <|body_start_0|>
n_samples, n_features = X.shape
self.classes = np.unique(y)
n_classes = len(self.classes)
self.phi = np.zeros((n_classes, 1))
self.means = np.zeros((n_classes, n_features))
self.sigma = 0
for i in range(n_classes):
indexes = np.flatnon... | GDA | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GDA:
def fit(self, X, y):
"""Parameters ---------- X : shape (n_samples, n_features) Training data y : shape (n_samples,) Target labels"""
<|body_0|>
def predict(self, X):
"""Parameters ---------- X : shape (n_samples, n_features) Predicting data Returns ------- y : ... | stack_v2_sparse_classes_36k_train_005599 | 1,310 | permissive | [
{
"docstring": "Parameters ---------- X : shape (n_samples, n_features) Training data y : shape (n_samples,) Target labels",
"name": "fit",
"signature": "def fit(self, X, y)"
},
{
"docstring": "Parameters ---------- X : shape (n_samples, n_features) Predicting data Returns ------- y : shape (n_s... | 2 | stack_v2_sparse_classes_30k_train_016570 | Implement the Python class `GDA` described below.
Class description:
Implement the GDA class.
Method signatures and docstrings:
- def fit(self, X, y): Parameters ---------- X : shape (n_samples, n_features) Training data y : shape (n_samples,) Target labels
- def predict(self, X): Parameters ---------- X : shape (n_s... | Implement the Python class `GDA` described below.
Class description:
Implement the GDA class.
Method signatures and docstrings:
- def fit(self, X, y): Parameters ---------- X : shape (n_samples, n_features) Training data y : shape (n_samples,) Target labels
- def predict(self, X): Parameters ---------- X : shape (n_s... | 7034798a5f0b92c6b8fdfa5948d2ad78a77a1a05 | <|skeleton|>
class GDA:
def fit(self, X, y):
"""Parameters ---------- X : shape (n_samples, n_features) Training data y : shape (n_samples,) Target labels"""
<|body_0|>
def predict(self, X):
"""Parameters ---------- X : shape (n_samples, n_features) Predicting data Returns ------- y : ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GDA:
def fit(self, X, y):
"""Parameters ---------- X : shape (n_samples, n_features) Training data y : shape (n_samples,) Target labels"""
n_samples, n_features = X.shape
self.classes = np.unique(y)
n_classes = len(self.classes)
self.phi = np.zeros((n_classes, 1))
... | the_stack_v2_python_sparse | 7. Machine Learning/gaussian_discriminant_analysis.py | Nhiemth1985/Pynaissance | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.