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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
54967b4fb9fff0ce9ae44d636414f5bb23fc4cdd | [
"nums.sort()\nif nums[0] != 0:\n return 0\nfor i in range(len(nums) - 1):\n if nums[i + 1] == nums[i] + 1:\n continue\n else:\n return nums[i] + 1\nreturn nums[-1] + 1",
"sum = 0\nfor i in nums:\n sum += i\nreturn int(len(nums) * (len(nums) + 1) / 2 - sum)"
] | <|body_start_0|>
nums.sort()
if nums[0] != 0:
return 0
for i in range(len(nums) - 1):
if nums[i + 1] == nums[i] + 1:
continue
else:
return nums[i] + 1
return nums[-1] + 1
<|end_body_0|>
<|body_start_1|>
sum = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def missingNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def missingNumber1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
nums.sort()
if nums[0] != 0:
... | stack_v2_sparse_classes_36k_train_003900 | 735 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "missingNumber",
"signature": "def missingNumber(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "missingNumber1",
"signature": "def missingNumber1(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002806 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def missingNumber(self, nums): :type nums: List[int] :rtype: int
- def missingNumber1(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def missingNumber(self, nums): :type nums: List[int] :rtype: int
- def missingNumber1(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def missin... | 96dd15210bcf9efe1f8cf31ce0566a7eabb3e221 | <|skeleton|>
class Solution:
def missingNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def missingNumber1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def missingNumber(self, nums):
""":type nums: List[int] :rtype: int"""
nums.sort()
if nums[0] != 0:
return 0
for i in range(len(nums) - 1):
if nums[i + 1] == nums[i] + 1:
continue
else:
return nums[i]... | the_stack_v2_python_sparse | Python/MissingNumber.py | abhi-verma/LeetCode-Algo | train | 0 | |
8b0771d35a27548c0670094a510e88aed8c36ac2 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn IntuneBrand()",
"from .mime_content import MimeContent\nfrom .rgb_color import RgbColor\nfrom .mime_content import MimeContent\nfrom .rgb_color import RgbColor\nfields: Dict[str, Callable[[Any], None]] = {'contactITEmailAddress': lambd... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return IntuneBrand()
<|end_body_0|>
<|body_start_1|>
from .mime_content import MimeContent
from .rgb_color import RgbColor
from .mime_content import MimeContent
from .rgb_color ... | intuneBrand contains data which is used in customizing the appearance of the Company Portal applications as well as the end user web portal. | IntuneBrand | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IntuneBrand:
"""intuneBrand contains data which is used in customizing the appearance of the Company Portal applications as well as the end user web portal."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IntuneBrand:
"""Creates a new instance of the a... | stack_v2_sparse_classes_36k_train_003901 | 7,014 | 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: IntuneBrand",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(p... | 3 | stack_v2_sparse_classes_30k_train_000806 | Implement the Python class `IntuneBrand` described below.
Class description:
intuneBrand contains data which is used in customizing the appearance of the Company Portal applications as well as the end user web portal.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNo... | Implement the Python class `IntuneBrand` described below.
Class description:
intuneBrand contains data which is used in customizing the appearance of the Company Portal applications as well as the end user web portal.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNo... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class IntuneBrand:
"""intuneBrand contains data which is used in customizing the appearance of the Company Portal applications as well as the end user web portal."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IntuneBrand:
"""Creates a new instance of the a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IntuneBrand:
"""intuneBrand contains data which is used in customizing the appearance of the Company Portal applications as well as the end user web portal."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IntuneBrand:
"""Creates a new instance of the appropriate cl... | the_stack_v2_python_sparse | msgraph/generated/models/intune_brand.py | microsoftgraph/msgraph-sdk-python | train | 135 |
8e5017c6ae3e873007681c2084bcd291d371547c | [
"try:\n json.loads(self.configuration)\nexcept ValueError as e:\n raise ValidationError('Must be valid JSON string.') from e",
"instance = cls.current()\njson_data = json.loads(instance.configuration) if instance.enabled else {}\nreturn json_data"
] | <|body_start_0|>
try:
json.loads(self.configuration)
except ValueError as e:
raise ValidationError('Must be valid JSON string.') from e
<|end_body_0|>
<|body_start_1|>
instance = cls.current()
json_data = json.loads(instance.configuration) if instance.enabled els... | Static values for certificate HTML view context parameters. Default values will be applied across all certificate types (course modes) Matching 'mode' overrides will be used instead of defaults, where applicable Example configuration : { "default": { "url": "https://www.edx.org", "logo_src": "https://www.edx.org/static... | CertificateHtmlViewConfiguration | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CertificateHtmlViewConfiguration:
"""Static values for certificate HTML view context parameters. Default values will be applied across all certificate types (course modes) Matching 'mode' overrides will be used instead of defaults, where applicable Example configuration : { "default": { "url": "h... | stack_v2_sparse_classes_36k_train_003902 | 46,419 | permissive | [
{
"docstring": "Ensures configuration field contains valid JSON.",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "Retrieves the configuration field value from the database",
"name": "get_config",
"signature": "def get_config(cls)"
}
] | 2 | null | Implement the Python class `CertificateHtmlViewConfiguration` described below.
Class description:
Static values for certificate HTML view context parameters. Default values will be applied across all certificate types (course modes) Matching 'mode' overrides will be used instead of defaults, where applicable Example c... | Implement the Python class `CertificateHtmlViewConfiguration` described below.
Class description:
Static values for certificate HTML view context parameters. Default values will be applied across all certificate types (course modes) Matching 'mode' overrides will be used instead of defaults, where applicable Example c... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class CertificateHtmlViewConfiguration:
"""Static values for certificate HTML view context parameters. Default values will be applied across all certificate types (course modes) Matching 'mode' overrides will be used instead of defaults, where applicable Example configuration : { "default": { "url": "h... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CertificateHtmlViewConfiguration:
"""Static values for certificate HTML view context parameters. Default values will be applied across all certificate types (course modes) Matching 'mode' overrides will be used instead of defaults, where applicable Example configuration : { "default": { "url": "https://www.ed... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/certificates/models.py | luque/better-ways-of-thinking-about-software | train | 3 |
e24be568aa9f47113199c4a12fdce02f810c7802 | [
"begin, end = (0, len(S))\nq = (1 << 31) - 1\nanswer = ''\nwhile begin + 1 < end:\n mid = (begin + end) // 2\n found, candidate = self.RabinKarp(S, mid, q)\n if found:\n begin, answer = (mid, candidate)\n else:\n end = mid\nreturn answer",
"if M == 0:\n return True\nh = (1 << 8 * M - ... | <|body_start_0|>
begin, end = (0, len(S))
q = (1 << 31) - 1
answer = ''
while begin + 1 < end:
mid = (begin + end) // 2
found, candidate = self.RabinKarp(S, mid, q)
if found:
begin, answer = (mid, candidate)
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestDupSubstring(self, S: str) -> str:
"""https://leetcode.com/problems/longest-duplicate-substring/discuss/695029/Python-Binary-search-O(n-log-n)-average-with-Rabin-Karp-explained"""
<|body_0|>
def RabinKarp(self, S: str, M: int, q: int) -> bool:
""... | stack_v2_sparse_classes_36k_train_003903 | 2,008 | no_license | [
{
"docstring": "https://leetcode.com/problems/longest-duplicate-substring/discuss/695029/Python-Binary-search-O(n-log-n)-average-with-Rabin-Karp-explained",
"name": "longestDupSubstring",
"signature": "def longestDupSubstring(self, S: str) -> str"
},
{
"docstring": "Using rolling hash to hash th... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestDupSubstring(self, S: str) -> str: https://leetcode.com/problems/longest-duplicate-substring/discuss/695029/Python-Binary-search-O(n-log-n)-average-with-Rabin-Karp-exp... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestDupSubstring(self, S: str) -> str: https://leetcode.com/problems/longest-duplicate-substring/discuss/695029/Python-Binary-search-O(n-log-n)-average-with-Rabin-Karp-exp... | da1774fd07b7326e66d9478b3d2619e0499ac2b7 | <|skeleton|>
class Solution:
def longestDupSubstring(self, S: str) -> str:
"""https://leetcode.com/problems/longest-duplicate-substring/discuss/695029/Python-Binary-search-O(n-log-n)-average-with-Rabin-Karp-explained"""
<|body_0|>
def RabinKarp(self, S: str, M: int, q: int) -> bool:
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestDupSubstring(self, S: str) -> str:
"""https://leetcode.com/problems/longest-duplicate-substring/discuss/695029/Python-Binary-search-O(n-log-n)-average-with-Rabin-Karp-explained"""
begin, end = (0, len(S))
q = (1 << 31) - 1
answer = ''
while begin + ... | the_stack_v2_python_sparse | Python3/String/LongestDuplicateSubstring/BinarySearch_RabinKarp1044.py | daviddwlee84/LeetCode | train | 14 | |
94631fa6e27eab8386b7f78752225f34382773a2 | [
"n = len(nums)\nfor i in range(n - 1):\n smallest = nums[i]\n idx = i\n for j in range(i + 1, n):\n if nums[j] < smallest:\n smallest = nums[j]\n idx = j\n if smallest < nums[i]:\n nums[i], nums[idx] = (nums[idx], nums[i])\nreturn nums",
"n = len(nums)\nfor i in ran... | <|body_start_0|>
n = len(nums)
for i in range(n - 1):
smallest = nums[i]
idx = i
for j in range(i + 1, n):
if nums[j] < smallest:
smallest = nums[j]
idx = j
if smallest < nums[i]:
nums... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortArray(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def sortArray(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
def sortArray(self, nums):
""":type nums: List[int] :rtype: List[int... | stack_v2_sparse_classes_36k_train_003904 | 2,326 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "sortArray",
"signature": "def sortArray(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "sortArray",
"signature": "def sortArray(self, nums)"
},
{
"docstring": ":type nums: List[i... | 5 | stack_v2_sparse_classes_30k_train_007207 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortArray(self, nums): :type nums: List[int] :rtype: List[int]
- def sortArray(self, nums): :type nums: List[int] :rtype: List[int]
- def sortArray(self, nums): :type nums: L... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortArray(self, nums): :type nums: List[int] :rtype: List[int]
- def sortArray(self, nums): :type nums: List[int] :rtype: List[int]
- def sortArray(self, nums): :type nums: L... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def sortArray(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def sortArray(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
def sortArray(self, nums):
""":type nums: List[int] :rtype: List[int... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sortArray(self, nums):
""":type nums: List[int] :rtype: List[int]"""
n = len(nums)
for i in range(n - 1):
smallest = nums[i]
idx = i
for j in range(i + 1, n):
if nums[j] < smallest:
smallest = nums[j]... | the_stack_v2_python_sparse | 0912_Sort_an_Array.py | bingli8802/leetcode | train | 0 | |
b1a37b0836eef08ee1b01e67a651bc45befee2d1 | [
"parser.add_argument('system', type=str, nargs='*', default=ALL_SYSTEMS, help='lms or studio')\nparser.add_argument('--theme-dirs', dest='theme_dirs', type=str, nargs='+', default=None, help='List of dirs where given themes would be looked.')\nparser.add_argument('--themes', type=str, nargs='+', default=['all'], he... | <|body_start_0|>
parser.add_argument('system', type=str, nargs='*', default=ALL_SYSTEMS, help='lms or studio')
parser.add_argument('--theme-dirs', dest='theme_dirs', type=str, nargs='+', default=None, help='List of dirs where given themes would be looked.')
parser.add_argument('--themes', type=s... | Compile theme sass and collect theme assets. | Command | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
"""Compile theme sass and collect theme assets."""
def add_arguments(self, parser):
"""Add arguments for compile_sass command. Args: parser (django.core.management.base.CommandParser): parsed for parsing command line arguments."""
<|body_0|>
def parse_arguments(... | stack_v2_sparse_classes_36k_train_003905 | 5,336 | permissive | [
{
"docstring": "Add arguments for compile_sass command. Args: parser (django.core.management.base.CommandParser): parsed for parsing command line arguments.",
"name": "add_arguments",
"signature": "def add_arguments(self, parser)"
},
{
"docstring": "Parse and validate arguments for compile_sass ... | 3 | null | Implement the Python class `Command` described below.
Class description:
Compile theme sass and collect theme assets.
Method signatures and docstrings:
- def add_arguments(self, parser): Add arguments for compile_sass command. Args: parser (django.core.management.base.CommandParser): parsed for parsing command line a... | Implement the Python class `Command` described below.
Class description:
Compile theme sass and collect theme assets.
Method signatures and docstrings:
- def add_arguments(self, parser): Add arguments for compile_sass command. Args: parser (django.core.management.base.CommandParser): parsed for parsing command line a... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class Command:
"""Compile theme sass and collect theme assets."""
def add_arguments(self, parser):
"""Add arguments for compile_sass command. Args: parser (django.core.management.base.CommandParser): parsed for parsing command line arguments."""
<|body_0|>
def parse_arguments(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Command:
"""Compile theme sass and collect theme assets."""
def add_arguments(self, parser):
"""Add arguments for compile_sass command. Args: parser (django.core.management.base.CommandParser): parsed for parsing command line arguments."""
parser.add_argument('system', type=str, nargs='*'... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/theming/management/commands/compile_sass.py | luque/better-ways-of-thinking-about-software | train | 3 |
bfabc4812478606e9d3279c49f36f64e14a629c7 | [
"self.N = color_depth\nself.hsync = Signal(bool(1))\nself.vsync = Signal(bool(1))\ncd = color_depth\nself.red = Signal(intbv(0)[cd[0]:])\nself.green = Signal(intbv(0)[cd[1]:])\nself.blue = Signal(intbv(0)[cd[2]:])\nself.pxlen = Signal(bool(0))\nself.active = Signal(bool(0))\nself.states = enum('NONE', 'ACTIVE', 'HO... | <|body_start_0|>
self.N = color_depth
self.hsync = Signal(bool(1))
self.vsync = Signal(bool(1))
cd = color_depth
self.red = Signal(intbv(0)[cd[0]:])
self.green = Signal(intbv(0)[cd[1]:])
self.blue = Signal(intbv(0)[cd[2]:])
self.pxlen = Signal(bool(0))
... | VGA | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VGA:
def __init__(self, color_depth=(10, 10, 10)):
"""color_depth the number of bits per RGB"""
<|body_0|>
def assign(self, hsync, vsync, red, green, blue, pxlen=None, active=None):
"""in some cases discrete signals are connected"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k_train_003906 | 1,435 | permissive | [
{
"docstring": "color_depth the number of bits per RGB",
"name": "__init__",
"signature": "def __init__(self, color_depth=(10, 10, 10))"
},
{
"docstring": "in some cases discrete signals are connected",
"name": "assign",
"signature": "def assign(self, hsync, vsync, red, green, blue, pxle... | 2 | stack_v2_sparse_classes_30k_train_005535 | Implement the Python class `VGA` described below.
Class description:
Implement the VGA class.
Method signatures and docstrings:
- def __init__(self, color_depth=(10, 10, 10)): color_depth the number of bits per RGB
- def assign(self, hsync, vsync, red, green, blue, pxlen=None, active=None): in some cases discrete sig... | Implement the Python class `VGA` described below.
Class description:
Implement the VGA class.
Method signatures and docstrings:
- def __init__(self, color_depth=(10, 10, 10)): color_depth the number of bits per RGB
- def assign(self, hsync, vsync, red, green, blue, pxlen=None, active=None): in some cases discrete sig... | 083315dcb652fb2385381b441a2db6341ddf2b15 | <|skeleton|>
class VGA:
def __init__(self, color_depth=(10, 10, 10)):
"""color_depth the number of bits per RGB"""
<|body_0|>
def assign(self, hsync, vsync, red, green, blue, pxlen=None, active=None):
"""in some cases discrete signals are connected"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VGA:
def __init__(self, color_depth=(10, 10, 10)):
"""color_depth the number of bits per RGB"""
self.N = color_depth
self.hsync = Signal(bool(1))
self.vsync = Signal(bool(1))
cd = color_depth
self.red = Signal(intbv(0)[cd[0]:])
self.green = Signal(intbv(... | the_stack_v2_python_sparse | rhea/cores/video/vga/vga_intf.py | aorcajo/rhea | train | 0 | |
797379f560bc20f6f5f1f295e3476dbeee322b73 | [
"res = []\nself._distance(root, target, K, res)\nreturn res",
"if not root:\n return -1\nif root == target:\n self.collect(target, K, res)\n return 0\nl = self._distance(root.left, target, K, res)\nr = self._distance(root.right, target, K, res)\nif l >= 0:\n if l + 1 == K:\n res.append(root.val... | <|body_start_0|>
res = []
self._distance(root, target, K, res)
return res
<|end_body_0|>
<|body_start_1|>
if not root:
return -1
if root == target:
self.collect(target, K, res)
return 0
l = self._distance(root.left, target, K, res)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def distanceK(self, root, target, K):
""":type root: TreeNode :type target: TreeNode :type K: int :rtype: List[int]"""
<|body_0|>
def _distance(self, root, target, K, res):
"""return distance from root to target return -1 if target does not found from root"... | stack_v2_sparse_classes_36k_train_003907 | 1,872 | no_license | [
{
"docstring": ":type root: TreeNode :type target: TreeNode :type K: int :rtype: List[int]",
"name": "distanceK",
"signature": "def distanceK(self, root, target, K)"
},
{
"docstring": "return distance from root to target return -1 if target does not found from root",
"name": "_distance",
... | 3 | stack_v2_sparse_classes_30k_train_014277 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def distanceK(self, root, target, K): :type root: TreeNode :type target: TreeNode :type K: int :rtype: List[int]
- def _distance(self, root, target, K, res): return distance from... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def distanceK(self, root, target, K): :type root: TreeNode :type target: TreeNode :type K: int :rtype: List[int]
- def _distance(self, root, target, K, res): return distance from... | 1a3c1f4d6e9d3444039f087763b93241f4ba7892 | <|skeleton|>
class Solution:
def distanceK(self, root, target, K):
""":type root: TreeNode :type target: TreeNode :type K: int :rtype: List[int]"""
<|body_0|>
def _distance(self, root, target, K, res):
"""return distance from root to target return -1 if target does not found from root"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def distanceK(self, root, target, K):
""":type root: TreeNode :type target: TreeNode :type K: int :rtype: List[int]"""
res = []
self._distance(root, target, K, res)
return res
def _distance(self, root, target, K, res):
"""return distance from root to targ... | the_stack_v2_python_sparse | Algorithm/863_All_Nodes_Distance_K_in_BT.py | Gi1ia/TechNoteBook | train | 7 | |
2b562338440fa200677993cae60755718c664c2a | [
"expected_hamiltonian_values = ['nearest-neighbour']\nif hamiltonian not in expected_hamiltonian_values:\n raise ValueError(hamiltonian)\nself.site_energies = lattice.site_energies\nself.nn_energy = lattice.nn_energy\nself.cn_energy = lattice.cn_energies\nself.connected_site_pairs = lattice.connected_site_pairs(... | <|body_start_0|>
expected_hamiltonian_values = ['nearest-neighbour']
if hamiltonian not in expected_hamiltonian_values:
raise ValueError(hamiltonian)
self.site_energies = lattice.site_energies
self.nn_energy = lattice.nn_energy
self.cn_energy = lattice.cn_energies
... | LookupTable class | LookupTable | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LookupTable:
"""LookupTable class"""
def __init__(self, lattice, hamiltonian):
"""Initialise a LookupTable object instance. Args: lattice (lattice_mc.Lattice): The lattice object, used to define the allowed jumps. hamiltonian (Str): The model Hamiltonian used to define the jump energ... | stack_v2_sparse_classes_36k_train_003908 | 3,897 | permissive | [
{
"docstring": "Initialise a LookupTable object instance. Args: lattice (lattice_mc.Lattice): The lattice object, used to define the allowed jumps. hamiltonian (Str): The model Hamiltonian used to define the jump energies. Allowed values = `nearest-neigbour` Returns: None",
"name": "__init__",
"signatur... | 3 | stack_v2_sparse_classes_30k_train_003260 | Implement the Python class `LookupTable` described below.
Class description:
LookupTable class
Method signatures and docstrings:
- def __init__(self, lattice, hamiltonian): Initialise a LookupTable object instance. Args: lattice (lattice_mc.Lattice): The lattice object, used to define the allowed jumps. hamiltonian (... | Implement the Python class `LookupTable` described below.
Class description:
LookupTable class
Method signatures and docstrings:
- def __init__(self, lattice, hamiltonian): Initialise a LookupTable object instance. Args: lattice (lattice_mc.Lattice): The lattice object, used to define the allowed jumps. hamiltonian (... | 7fa7be85f2f23a2d8dfd0830ecdb89d0dbf2bfd5 | <|skeleton|>
class LookupTable:
"""LookupTable class"""
def __init__(self, lattice, hamiltonian):
"""Initialise a LookupTable object instance. Args: lattice (lattice_mc.Lattice): The lattice object, used to define the allowed jumps. hamiltonian (Str): The model Hamiltonian used to define the jump energ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LookupTable:
"""LookupTable class"""
def __init__(self, lattice, hamiltonian):
"""Initialise a LookupTable object instance. Args: lattice (lattice_mc.Lattice): The lattice object, used to define the allowed jumps. hamiltonian (Str): The model Hamiltonian used to define the jump energies. Allowed ... | the_stack_v2_python_sparse | lattice_mc/lookup_table.py | bjmorgan/lattice_mc | train | 28 |
bdf07c7563ae5f9f706c10346f480a344cebec90 | [
"self.abbrevs = {}\nfor word in dictionary:\n if len(word) == 0:\n continue\n abbrev = word[0] + str(len(word) - 2) + word[-1]\n if abbrev not in self.abbrevs:\n self.abbrevs[abbrev] = set()\n self.abbrevs[abbrev].add(word)",
"if word == '':\n return True\nabbrev = word[0] + str(len(w... | <|body_start_0|>
self.abbrevs = {}
for word in dictionary:
if len(word) == 0:
continue
abbrev = word[0] + str(len(word) - 2) + word[-1]
if abbrev not in self.abbrevs:
self.abbrevs[abbrev] = set()
self.abbrevs[abbrev].add(wor... | ValidWordAbbr | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
""":type dictionary: List[str]"""
<|body_0|>
def isUnique(self, word):
""":type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.abbrevs = {}
for word in dictionary:
... | stack_v2_sparse_classes_36k_train_003909 | 1,025 | permissive | [
{
"docstring": ":type dictionary: List[str]",
"name": "__init__",
"signature": "def __init__(self, dictionary)"
},
{
"docstring": ":type word: str :rtype: bool",
"name": "isUnique",
"signature": "def isUnique(self, word)"
}
] | 2 | null | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): :type dictionary: List[str]
- def isUnique(self, word): :type word: str :rtype: bool | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): :type dictionary: List[str]
- def isUnique(self, word): :type word: str :rtype: bool
<|skeleton|>
class ValidWordAbbr:
def __init_... | ba84c192fb9995dd48ddc6d81c3153488dd3c698 | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
""":type dictionary: List[str]"""
<|body_0|>
def isUnique(self, word):
""":type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValidWordAbbr:
def __init__(self, dictionary):
""":type dictionary: List[str]"""
self.abbrevs = {}
for word in dictionary:
if len(word) == 0:
continue
abbrev = word[0] + str(len(word) - 2) + word[-1]
if abbrev not in self.abbrevs:
... | the_stack_v2_python_sparse | Python/unique-word-abbreviation.py | phucle2411/LeetCode | train | 0 | |
26ede986262d119679cd0e47baa6dbfbb108f966 | [
"super().__init__()\nextension = os.path.splitext(filename)[1]\nif extension != '.ntf' and extension != '.tif':\n raise RuntimeError('{} is not a NITF or TIFF file'.format(filename))\nself.extension = extension\nif not xml_filename:\n xml_filename = filename.replace(self.extension, '.xml')\nif not os.path.isf... | <|body_start_0|>
super().__init__()
extension = os.path.splitext(filename)[1]
if extension != '.ntf' and extension != '.tif':
raise RuntimeError('{} is not a NITF or TIFF file'.format(filename))
self.extension = extension
if not xml_filename:
xml_filename ... | DGFile | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DGFile:
def __init__(self, filename, xml_filename=None, logger=None):
"""Default DGFile initializer ---------- Parameters ---------- :param filename: string refering to NITF or TIF filename :param filename: string refering to XML filename :param logger: log file ---------- Attributes ---... | stack_v2_sparse_classes_36k_train_003910 | 4,793 | permissive | [
{
"docstring": "Default DGFile initializer ---------- Parameters ---------- :param filename: string refering to NITF or TIF filename :param filename: string refering to XML filename :param logger: log file ---------- Attributes ---------- self.extension: string for raster filename extension (.nitf or .tif) self... | 2 | stack_v2_sparse_classes_30k_test_000212 | Implement the Python class `DGFile` described below.
Class description:
Implement the DGFile class.
Method signatures and docstrings:
- def __init__(self, filename, xml_filename=None, logger=None): Default DGFile initializer ---------- Parameters ---------- :param filename: string refering to NITF or TIF filename :pa... | Implement the Python class `DGFile` described below.
Class description:
Implement the DGFile class.
Method signatures and docstrings:
- def __init__(self, filename, xml_filename=None, logger=None): Default DGFile initializer ---------- Parameters ---------- :param filename: string refering to NITF or TIF filename :pa... | b559caf18ed3e12128ce4f8c9fb75e4f12df950e | <|skeleton|>
class DGFile:
def __init__(self, filename, xml_filename=None, logger=None):
"""Default DGFile initializer ---------- Parameters ---------- :param filename: string refering to NITF or TIF filename :param filename: string refering to XML filename :param logger: log file ---------- Attributes ---... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DGFile:
def __init__(self, filename, xml_filename=None, logger=None):
"""Default DGFile initializer ---------- Parameters ---------- :param filename: string refering to NITF or TIF filename :param filename: string refering to XML filename :param logger: log file ---------- Attributes ---------- self.e... | the_stack_v2_python_sparse | terragpu/metadata/dgfile.py | nasa-nccs-hpda/terragpu | train | 2 | |
e8fa410fe9d934984a89bf9da5c28131e762efbc | [
"length = 0\nfather = None\ncur = head\nwhile cur:\n length += 1\n father = cur\n cur = cur.next\nreturn (length, father)",
"length, tail = self.get_length(head)\nif length == 0 or length == 1 or k == 0:\n return head\nnum = length - k % length\nif num == length:\n return head\nnum -= 1\nif num == ... | <|body_start_0|>
length = 0
father = None
cur = head
while cur:
length += 1
father = cur
cur = cur.next
return (length, father)
<|end_body_0|>
<|body_start_1|>
length, tail = self.get_length(head)
if length == 0 or length == 1 ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def get_length(self, head):
""":type head: ListNode :rtype: int"""
<|body_0|>
def rotateRight(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
length = 0
father =... | stack_v2_sparse_classes_36k_train_003911 | 1,268 | no_license | [
{
"docstring": ":type head: ListNode :rtype: int",
"name": "get_length",
"signature": "def get_length(self, head)"
},
{
"docstring": ":type head: ListNode :type k: int :rtype: ListNode",
"name": "rotateRight",
"signature": "def rotateRight(self, head, k)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015960 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_length(self, head): :type head: ListNode :rtype: int
- def rotateRight(self, head, k): :type head: ListNode :type k: int :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_length(self, head): :type head: ListNode :rtype: int
- def rotateRight(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
<|skeleton|>
class Solution:
... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def get_length(self, head):
""":type head: ListNode :rtype: int"""
<|body_0|>
def rotateRight(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def get_length(self, head):
""":type head: ListNode :rtype: int"""
length = 0
father = None
cur = head
while cur:
length += 1
father = cur
cur = cur.next
return (length, father)
def rotateRight(self, head, k):
... | the_stack_v2_python_sparse | python/leetcode/61_Rotate_List.py | bobcaoge/my-code | train | 0 | |
550d50f0e7bdcf40411cb90b39bde9dd55ebf464 | [
"self.learning_rate = learning_rate\nself.iterations = iterations\nself.penalty = penalty\nself.logger = logging.getLogger(__name__)",
"m, n = design_matrix.shape\nif y.ndim == 1 or y.shape[1] == 1:\n y = y.reshape(-1, 1)\n w = np.zeros(n).reshape(-1, 1)\n dw = np.zeros(n).reshape(-1, 1)\n b = 0\n ... | <|body_start_0|>
self.learning_rate = learning_rate
self.iterations = iterations
self.penalty = penalty
self.logger = logging.getLogger(__name__)
<|end_body_0|>
<|body_start_1|>
m, n = design_matrix.shape
if y.ndim == 1 or y.shape[1] == 1:
y = y.reshape(-1, 1... | LassoRegression | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LassoRegression:
def __init__(self, learning_rate: float=0.01, iterations: int=1000, penalty: float=1):
"""Class to calculate the polynomial_chaos coefficients with the Least Absolute Shrinkage and Selection Operator (LASSO) method. :param learning_rate: Size of steps for the gradient de... | stack_v2_sparse_classes_36k_train_003912 | 3,015 | permissive | [
{
"docstring": "Class to calculate the polynomial_chaos coefficients with the Least Absolute Shrinkage and Selection Operator (LASSO) method. :param learning_rate: Size of steps for the gradient descent. :param iterations: Number of iterations of the optimization algorithm. :param penalty: Penalty parameter con... | 2 | null | Implement the Python class `LassoRegression` described below.
Class description:
Implement the LassoRegression class.
Method signatures and docstrings:
- def __init__(self, learning_rate: float=0.01, iterations: int=1000, penalty: float=1): Class to calculate the polynomial_chaos coefficients with the Least Absolute ... | Implement the Python class `LassoRegression` described below.
Class description:
Implement the LassoRegression class.
Method signatures and docstrings:
- def __init__(self, learning_rate: float=0.01, iterations: int=1000, penalty: float=1): Class to calculate the polynomial_chaos coefficients with the Least Absolute ... | 9e98a6279aa5a2ec2d6d4c61226c34712547bcc6 | <|skeleton|>
class LassoRegression:
def __init__(self, learning_rate: float=0.01, iterations: int=1000, penalty: float=1):
"""Class to calculate the polynomial_chaos coefficients with the Least Absolute Shrinkage and Selection Operator (LASSO) method. :param learning_rate: Size of steps for the gradient de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LassoRegression:
def __init__(self, learning_rate: float=0.01, iterations: int=1000, penalty: float=1):
"""Class to calculate the polynomial_chaos coefficients with the Least Absolute Shrinkage and Selection Operator (LASSO) method. :param learning_rate: Size of steps for the gradient descent. :param ... | the_stack_v2_python_sparse | src/UQpy/surrogates/polynomial_chaos/regressions/LassoRegression.py | SURGroup/UQpy | train | 215 | |
710a287554b368c7d08dea59c6c07d66d951f141 | [
"args = self.arguments_filter.parse_args()\nitems_per_page = 20\npage_number = args['page']\nif page_number < 1:\n return abort(HTTPStatus.BAD_REQUEST, message=\"'page' must be > 0\")\nitems_query = Argument.query.filter_by(discussion_id=discussion_id).order_by(Argument.created_at.asc())\nif args['aspects'] is n... | <|body_start_0|>
args = self.arguments_filter.parse_args()
items_per_page = 20
page_number = args['page']
if page_number < 1:
return abort(HTTPStatus.BAD_REQUEST, message="'page' must be > 0")
items_query = Argument.query.filter_by(discussion_id=discussion_id).order_b... | DiscussionArgumentList | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiscussionArgumentList:
def get(self, discussion_id):
"""Filter discussion arguments * User can view discussion arguments filtered by aspects * View with filtration and pagination"""
<|body_0|>
def post(self, discussion_id):
"""Create a new discussion argument * User... | stack_v2_sparse_classes_36k_train_003913 | 4,163 | permissive | [
{
"docstring": "Filter discussion arguments * User can view discussion arguments filtered by aspects * View with filtration and pagination",
"name": "get",
"signature": "def get(self, discussion_id)"
},
{
"docstring": "Create a new discussion argument * User with permission to **\"create theses\... | 2 | null | Implement the Python class `DiscussionArgumentList` described below.
Class description:
Implement the DiscussionArgumentList class.
Method signatures and docstrings:
- def get(self, discussion_id): Filter discussion arguments * User can view discussion arguments filtered by aspects * View with filtration and paginati... | Implement the Python class `DiscussionArgumentList` described below.
Class description:
Implement the DiscussionArgumentList class.
Method signatures and docstrings:
- def get(self, discussion_id): Filter discussion arguments * User can view discussion arguments filtered by aspects * View with filtration and paginati... | dce87ffe395ae4bd08b47f28e07594e1889da819 | <|skeleton|>
class DiscussionArgumentList:
def get(self, discussion_id):
"""Filter discussion arguments * User can view discussion arguments filtered by aspects * View with filtration and pagination"""
<|body_0|>
def post(self, discussion_id):
"""Create a new discussion argument * User... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiscussionArgumentList:
def get(self, discussion_id):
"""Filter discussion arguments * User can view discussion arguments filtered by aspects * View with filtration and pagination"""
args = self.arguments_filter.parse_args()
items_per_page = 20
page_number = args['page']
... | the_stack_v2_python_sparse | src/backend/app/api/public/discussions/discussion/discussion_arguments.py | aimanow/sft | train | 0 | |
0de177fd79e2d4f2177fca3b65bfe114eaa9c092 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn UserExperienceAnalyticsOverview()",
"from .entity import Entity\nfrom .user_experience_analytics_insight import UserExperienceAnalyticsInsight\nfrom .entity import Entity\nfrom .user_experience_analytics_insight import UserExperienceAn... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return UserExperienceAnalyticsOverview()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .user_experience_analytics_insight import UserExperienceAnalyticsInsight
from .e... | The user experience analytics overview entity contains the overall score and the scores and insights of every metric of all categories. | UserExperienceAnalyticsOverview | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserExperienceAnalyticsOverview:
"""The user experience analytics overview entity contains the overall score and the scores and insights of every metric of all categories."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsOverview:
... | stack_v2_sparse_classes_36k_train_003914 | 2,549 | 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: UserExperienceAnalyticsOverview",
"name": "create_from_discriminator_value",
"signature": "def create_from_d... | 3 | stack_v2_sparse_classes_30k_train_000962 | Implement the Python class `UserExperienceAnalyticsOverview` described below.
Class description:
The user experience analytics overview entity contains the overall score and the scores and insights of every metric of all categories.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: O... | Implement the Python class `UserExperienceAnalyticsOverview` described below.
Class description:
The user experience analytics overview entity contains the overall score and the scores and insights of every metric of all categories.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: O... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class UserExperienceAnalyticsOverview:
"""The user experience analytics overview entity contains the overall score and the scores and insights of every metric of all categories."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsOverview:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserExperienceAnalyticsOverview:
"""The user experience analytics overview entity contains the overall score and the scores and insights of every metric of all categories."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsOverview:
"""Creates a... | the_stack_v2_python_sparse | msgraph/generated/models/user_experience_analytics_overview.py | microsoftgraph/msgraph-sdk-python | train | 135 |
5097b29a2f2c3eb9e4372cb076f366a9820b00b4 | [
"LOG.info('Updating user %s', user_obj['_id'])\nupdated_user = self.user_collection.find_one_and_replace({'_id': user_obj['_id']}, user_obj, return_document=pymongo.ReturnDocument.AFTER)\nreturn updated_user",
"LOG.info('Adding user %s to the database', user_obj['email'])\nif not '_id' in user_obj:\n user_obj[... | <|body_start_0|>
LOG.info('Updating user %s', user_obj['_id'])
updated_user = self.user_collection.find_one_and_replace({'_id': user_obj['_id']}, user_obj, return_document=pymongo.ReturnDocument.AFTER)
return updated_user
<|end_body_0|>
<|body_start_1|>
LOG.info('Adding user %s to the d... | UserHandler | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserHandler:
def update_user(self, user_obj):
"""Update an existing user. Args: user_obj(dict) Returns: updated_user(dict)"""
<|body_0|>
def add_user(self, user_obj):
"""Add a user object to the database Args: user_obj(scout.models.User): A dictionary with user infor... | stack_v2_sparse_classes_36k_train_003915 | 2,569 | permissive | [
{
"docstring": "Update an existing user. Args: user_obj(dict) Returns: updated_user(dict)",
"name": "update_user",
"signature": "def update_user(self, user_obj)"
},
{
"docstring": "Add a user object to the database Args: user_obj(scout.models.User): A dictionary with user information Returns: us... | 5 | null | Implement the Python class `UserHandler` described below.
Class description:
Implement the UserHandler class.
Method signatures and docstrings:
- def update_user(self, user_obj): Update an existing user. Args: user_obj(dict) Returns: updated_user(dict)
- def add_user(self, user_obj): Add a user object to the database... | Implement the Python class `UserHandler` described below.
Class description:
Implement the UserHandler class.
Method signatures and docstrings:
- def update_user(self, user_obj): Update an existing user. Args: user_obj(dict) Returns: updated_user(dict)
- def add_user(self, user_obj): Add a user object to the database... | 1e6a633ba0a83495047ee7b66db1ebf690ee465f | <|skeleton|>
class UserHandler:
def update_user(self, user_obj):
"""Update an existing user. Args: user_obj(dict) Returns: updated_user(dict)"""
<|body_0|>
def add_user(self, user_obj):
"""Add a user object to the database Args: user_obj(scout.models.User): A dictionary with user infor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserHandler:
def update_user(self, user_obj):
"""Update an existing user. Args: user_obj(dict) Returns: updated_user(dict)"""
LOG.info('Updating user %s', user_obj['_id'])
updated_user = self.user_collection.find_one_and_replace({'_id': user_obj['_id']}, user_obj, return_document=pymon... | the_stack_v2_python_sparse | scout/adapter/mongo/user.py | Clinical-Genomics/scout | train | 143 | |
7f30f759ed3a3e4ee9c5ba7765b4193fef26e47e | [
"check_authorization, response = check_authorization_in_header(request)\nif not check_authorization:\n return response\ndata = json.loads(request.body or '{}')\ncheck_data, response = check_user_data_request(data)\nif not check_data:\n return response\nuser = check_user(request)\nif user is not None:\n ser... | <|body_start_0|>
check_authorization, response = check_authorization_in_header(request)
if not check_authorization:
return response
data = json.loads(request.body or '{}')
check_data, response = check_user_data_request(data)
if not check_data:
return respo... | Users | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Users:
def put(self, request):
"""Method updates a user"""
<|body_0|>
def post(self, request):
"""method register a new user"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
check_authorization, response = check_authorization_in_header(request)
... | stack_v2_sparse_classes_36k_train_003916 | 12,963 | permissive | [
{
"docstring": "Method updates a user",
"name": "put",
"signature": "def put(self, request)"
},
{
"docstring": "method register a new user",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020598 | Implement the Python class `Users` described below.
Class description:
Implement the Users class.
Method signatures and docstrings:
- def put(self, request): Method updates a user
- def post(self, request): method register a new user | Implement the Python class `Users` described below.
Class description:
Implement the Users class.
Method signatures and docstrings:
- def put(self, request): Method updates a user
- def post(self, request): method register a new user
<|skeleton|>
class Users:
def put(self, request):
"""Method updates a ... | 8082bb89d00d28ade774a445a1645dc07ac86127 | <|skeleton|>
class Users:
def put(self, request):
"""Method updates a user"""
<|body_0|>
def post(self, request):
"""method register a new user"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Users:
def put(self, request):
"""Method updates a user"""
check_authorization, response = check_authorization_in_header(request)
if not check_authorization:
return response
data = json.loads(request.body or '{}')
check_data, response = check_user_data_reque... | the_stack_v2_python_sparse | BettingRestAPI/user/views.py | PatrickKoss/BettingPrediction | train | 0 | |
2547fba7ef61e7bb504a8631e187c1e0c72dcd21 | [
"if isinstance(typedef, (list, tuple)):\n typedef_list = typedef\nelse:\n typedef_list = [copy.deepcopy(typedef) for x in instance]\nassert len(typedef_list) == len(instance)\nreturn [encode_type(v, typedef=t) for v, t in zip(instance, typedef_list)]",
"if isinstance(prop1, dict) and isinstance(prop2, dict)... | <|body_start_0|>
if isinstance(typedef, (list, tuple)):
typedef_list = typedef
else:
typedef_list = [copy.deepcopy(typedef) for x in instance]
assert len(typedef_list) == len(instance)
return [encode_type(v, typedef=t) for v, t in zip(instance, typedef_list)]
<|en... | Property class for 'items' property. | ItemsMetaschemaProperty | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ItemsMetaschemaProperty:
"""Property class for 'items' property."""
def encode(cls, instance, typedef=None):
"""Encoder for the 'items' container property."""
<|body_0|>
def compare(cls, prop1, prop2, root1=None, root2=None):
"""Comparison method for 'items' cont... | stack_v2_sparse_classes_36k_train_003917 | 2,027 | permissive | [
{
"docstring": "Encoder for the 'items' container property.",
"name": "encode",
"signature": "def encode(cls, instance, typedef=None)"
},
{
"docstring": "Comparison method for 'items' container property.",
"name": "compare",
"signature": "def compare(cls, prop1, prop2, root1=None, root2=... | 2 | null | Implement the Python class `ItemsMetaschemaProperty` described below.
Class description:
Property class for 'items' property.
Method signatures and docstrings:
- def encode(cls, instance, typedef=None): Encoder for the 'items' container property.
- def compare(cls, prop1, prop2, root1=None, root2=None): Comparison me... | Implement the Python class `ItemsMetaschemaProperty` described below.
Class description:
Property class for 'items' property.
Method signatures and docstrings:
- def encode(cls, instance, typedef=None): Encoder for the 'items' container property.
- def compare(cls, prop1, prop2, root1=None, root2=None): Comparison me... | dcc4d75a4d2c6aaa7e50e75095a16df1df6b2b0a | <|skeleton|>
class ItemsMetaschemaProperty:
"""Property class for 'items' property."""
def encode(cls, instance, typedef=None):
"""Encoder for the 'items' container property."""
<|body_0|>
def compare(cls, prop1, prop2, root1=None, root2=None):
"""Comparison method for 'items' cont... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ItemsMetaschemaProperty:
"""Property class for 'items' property."""
def encode(cls, instance, typedef=None):
"""Encoder for the 'items' container property."""
if isinstance(typedef, (list, tuple)):
typedef_list = typedef
else:
typedef_list = [copy.deepcopy(... | the_stack_v2_python_sparse | yggdrasil/metaschema/properties/JSONArrayMetaschemaProperties.py | leighmatth/yggdrasil | train | 0 |
ead175b3f627d0fe1ff1b5b3b9689f5a41afcb50 | [
"self.fullXRes = Tunable.fullIMGXRes\nself.fullYRes = Tunable.fullIMGYRes\nself.chunkXRes = Tunable.chunkIMGXRes\nself.chunkYRes = Tunable.chunkIMGYRes\nself.chunks = Tunable.chunks\nself.EPOCHS = Tunable.totalEPOCHS\nself.latentSize = Tunable.latentSize\nself.trainDataset = preprocessVars.trainDataset\nself.traini... | <|body_start_0|>
self.fullXRes = Tunable.fullIMGXRes
self.fullYRes = Tunable.fullIMGYRes
self.chunkXRes = Tunable.chunkIMGXRes
self.chunkYRes = Tunable.chunkIMGYRes
self.chunks = Tunable.chunks
self.EPOCHS = Tunable.totalEPOCHS
self.latentSize = Tunable.latentSize... | Combination of display functions to use in other files | Display | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Display:
"""Combination of display functions to use in other files"""
def __init__(self, preprocessVars):
"""Initialization of all variables needed"""
<|body_0|>
def stitchChunkImg(self, chunkImgList):
"""Takes the chunked images and stitches them into a full ima... | stack_v2_sparse_classes_36k_train_003918 | 3,581 | no_license | [
{
"docstring": "Initialization of all variables needed",
"name": "__init__",
"signature": "def __init__(self, preprocessVars)"
},
{
"docstring": "Takes the chunked images and stitches them into a full image",
"name": "stitchChunkImg",
"signature": "def stitchChunkImg(self, chunkImgList)"... | 3 | stack_v2_sparse_classes_30k_train_013188 | Implement the Python class `Display` described below.
Class description:
Combination of display functions to use in other files
Method signatures and docstrings:
- def __init__(self, preprocessVars): Initialization of all variables needed
- def stitchChunkImg(self, chunkImgList): Takes the chunked images and stitches... | Implement the Python class `Display` described below.
Class description:
Combination of display functions to use in other files
Method signatures and docstrings:
- def __init__(self, preprocessVars): Initialization of all variables needed
- def stitchChunkImg(self, chunkImgList): Takes the chunked images and stitches... | 41cb2b0f3998e48332ee3d86acd6fe9c9db84dd0 | <|skeleton|>
class Display:
"""Combination of display functions to use in other files"""
def __init__(self, preprocessVars):
"""Initialization of all variables needed"""
<|body_0|>
def stitchChunkImg(self, chunkImgList):
"""Takes the chunked images and stitches them into a full ima... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Display:
"""Combination of display functions to use in other files"""
def __init__(self, preprocessVars):
"""Initialization of all variables needed"""
self.fullXRes = Tunable.fullIMGXRes
self.fullYRes = Tunable.fullIMGYRes
self.chunkXRes = Tunable.chunkIMGXRes
self... | the_stack_v2_python_sparse | display.py | Noupin/ChunkGAN | train | 0 |
c120acd5af964ec3df331bad4fdbd6ba6a8889a2 | [
"super(TransposeForScores, self).__init__()\nself.attention_head_size = attention_head_size\nself.num_attention_heads = num_attention_heads\nself.transpose = ops.Transpose()\nself.reshape = ops.Reshape()",
"new_x_shape = x.shape[:-1] + (self.num_attention_heads, self.attention_head_size)\nx = x.view(new_x_shape)\... | <|body_start_0|>
super(TransposeForScores, self).__init__()
self.attention_head_size = attention_head_size
self.num_attention_heads = num_attention_heads
self.transpose = ops.Transpose()
self.reshape = ops.Reshape()
<|end_body_0|>
<|body_start_1|>
new_x_shape = x.shape[:... | transpose scores | TransposeForScores | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransposeForScores:
"""transpose scores"""
def __init__(self, num_attention_heads, attention_head_size):
"""init fun"""
<|body_0|>
def construct(self, x):
"""construct fun"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(TransposeForScores,... | stack_v2_sparse_classes_36k_train_003919 | 16,172 | permissive | [
{
"docstring": "init fun",
"name": "__init__",
"signature": "def __init__(self, num_attention_heads, attention_head_size)"
},
{
"docstring": "construct fun",
"name": "construct",
"signature": "def construct(self, x)"
}
] | 2 | null | Implement the Python class `TransposeForScores` described below.
Class description:
transpose scores
Method signatures and docstrings:
- def __init__(self, num_attention_heads, attention_head_size): init fun
- def construct(self, x): construct fun | Implement the Python class `TransposeForScores` described below.
Class description:
transpose scores
Method signatures and docstrings:
- def __init__(self, num_attention_heads, attention_head_size): init fun
- def construct(self, x): construct fun
<|skeleton|>
class TransposeForScores:
"""transpose scores"""
... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class TransposeForScores:
"""transpose scores"""
def __init__(self, num_attention_heads, attention_head_size):
"""init fun"""
<|body_0|>
def construct(self, x):
"""construct fun"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransposeForScores:
"""transpose scores"""
def __init__(self, num_attention_heads, attention_head_size):
"""init fun"""
super(TransposeForScores, self).__init__()
self.attention_head_size = attention_head_size
self.num_attention_heads = num_attention_heads
self.tra... | the_stack_v2_python_sparse | research/nlp/luke/src/luke/robert.py | mindspore-ai/models | train | 301 |
61b1f18570c10932fe8e1ac4eb6d502a50801e85 | [
"country = data['country']\nstate_abbrev = data['state_abbrev']\nif state_abbrev:\n if not use_subdivisions(country):\n raise serializers.ValidationError('State/Province should not be set for {} neighborhoods'.format(country))\n if state_abbrev not in [s['code'] for s in subdivisions_for_country(countr... | <|body_start_0|>
country = data['country']
state_abbrev = data['state_abbrev']
if state_abbrev:
if not use_subdivisions(country):
raise serializers.ValidationError('State/Province should not be set for {} neighborhoods'.format(country))
if state_abbrev not... | NeighborhoodSerializer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeighborhoodSerializer:
def validate(self, data):
"""Cross-field validation that state is set or not based on country."""
<|body_0|>
def save(self, *args, **kwargs):
"""Override the model save to convert errors raised there into serializer errors"""
<|body_1|... | stack_v2_sparse_classes_36k_train_003920 | 9,283 | permissive | [
{
"docstring": "Cross-field validation that state is set or not based on country.",
"name": "validate",
"signature": "def validate(self, data)"
},
{
"docstring": "Override the model save to convert errors raised there into serializer errors",
"name": "save",
"signature": "def save(self, ... | 2 | null | Implement the Python class `NeighborhoodSerializer` described below.
Class description:
Implement the NeighborhoodSerializer class.
Method signatures and docstrings:
- def validate(self, data): Cross-field validation that state is set or not based on country.
- def save(self, *args, **kwargs): Override the model save... | Implement the Python class `NeighborhoodSerializer` described below.
Class description:
Implement the NeighborhoodSerializer class.
Method signatures and docstrings:
- def validate(self, data): Cross-field validation that state is set or not based on country.
- def save(self, *args, **kwargs): Override the model save... | 620a5f4dc975891aa3b1266ced3f331fc17de19d | <|skeleton|>
class NeighborhoodSerializer:
def validate(self, data):
"""Cross-field validation that state is set or not based on country."""
<|body_0|>
def save(self, *args, **kwargs):
"""Override the model save to convert errors raised there into serializer errors"""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NeighborhoodSerializer:
def validate(self, data):
"""Cross-field validation that state is set or not based on country."""
country = data['country']
state_abbrev = data['state_abbrev']
if state_abbrev:
if not use_subdivisions(country):
raise serialize... | the_stack_v2_python_sparse | src/django/pfb_analysis/serializers.py | azavea/pfb-network-connectivity | train | 41 | |
41e81ac46e3924dddcb4aa47a0cb83e3f22b3925 | [
"self.type = destination_type\nself.path = path\nself.file = None\ntry:\n os.remove(path)\nexcept OSError:\n pass",
"self.file = open(self.path, 'w', encoding='utf-8')\nif self.type == FileType.XML:\n self.file.write('<?xml version=\"1W.0\" encoding=\"UTF-8\"?><items>')",
"assert self.file is not None\... | <|body_start_0|>
self.type = destination_type
self.path = path
self.file = None
try:
os.remove(path)
except OSError:
pass
<|end_body_0|>
<|body_start_1|>
self.file = open(self.path, 'w', encoding='utf-8')
if self.type == FileType.XML:
... | Запись в файл. | Writer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Writer:
"""Запись в файл."""
def __init__(self, destination_type: FileType, path: str) -> None:
"""Нужно, когда хотим записывать разметки по одной (экономия памяти). :param destination_type: тип файла. :param path: путь к файлу."""
<|body_0|>
def open(self) -> None:
... | stack_v2_sparse_classes_36k_train_003921 | 3,710 | permissive | [
{
"docstring": "Нужно, когда хотим записывать разметки по одной (экономия памяти). :param destination_type: тип файла. :param path: путь к файлу.",
"name": "__init__",
"signature": "def __init__(self, destination_type: FileType, path: str) -> None"
},
{
"docstring": "Открываем файл, вызывать до ... | 6 | stack_v2_sparse_classes_30k_train_021548 | Implement the Python class `Writer` described below.
Class description:
Запись в файл.
Method signatures and docstrings:
- def __init__(self, destination_type: FileType, path: str) -> None: Нужно, когда хотим записывать разметки по одной (экономия памяти). :param destination_type: тип файла. :param path: путь к файлу... | Implement the Python class `Writer` described below.
Class description:
Запись в файл.
Method signatures and docstrings:
- def __init__(self, destination_type: FileType, path: str) -> None: Нужно, когда хотим записывать разметки по одной (экономия памяти). :param destination_type: тип файла. :param path: путь к файлу... | 3d114f92dec08c16d28e7e5a1076cd7ea871043f | <|skeleton|>
class Writer:
"""Запись в файл."""
def __init__(self, destination_type: FileType, path: str) -> None:
"""Нужно, когда хотим записывать разметки по одной (экономия памяти). :param destination_type: тип файла. :param path: путь к файлу."""
<|body_0|>
def open(self) -> None:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Writer:
"""Запись в файл."""
def __init__(self, destination_type: FileType, path: str) -> None:
"""Нужно, когда хотим записывать разметки по одной (экономия памяти). :param destination_type: тип файла. :param path: путь к файлу."""
self.type = destination_type
self.path = path
... | the_stack_v2_python_sparse | rupo/files/writer.py | IlyaGusev/rupo | train | 185 |
54046d92f9d07e86508fd5b3071ad62b8b8383cf | [
"for operand in self.operands:\n yield from operand.expressions\nreturn",
"for operand in self.operands:\n yield from operand.expressions\nreturn",
"for operand in self.operands:\n yield from operand.mappings\nreturn",
"for operand in self.operands:\n yield from operand.references\nreturn",
"for... | <|body_start_0|>
for operand in self.operands:
yield from operand.expressions
return
<|end_body_0|>
<|body_start_1|>
for operand in self.operands:
yield from operand.expressions
return
<|end_body_1|>
<|body_start_2|>
for operand in self.operands:
... | Mix-in class that augments raph traversal for the new leaves defined in this package | Composite | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Composite:
"""Mix-in class that augments raph traversal for the new leaves defined in this package"""
def expressions(self):
"""Return a sequence over the nodes in my dependency graph that are constructed out of python expressions involving the names of other nodes"""
<|body_... | stack_v2_sparse_classes_36k_train_003922 | 2,506 | permissive | [
{
"docstring": "Return a sequence over the nodes in my dependency graph that are constructed out of python expressions involving the names of other nodes",
"name": "expressions",
"signature": "def expressions(self)"
},
{
"docstring": "Return a sequence over the nodes in my dependency graph that ... | 6 | null | Implement the Python class `Composite` described below.
Class description:
Mix-in class that augments raph traversal for the new leaves defined in this package
Method signatures and docstrings:
- def expressions(self): Return a sequence over the nodes in my dependency graph that are constructed out of python expressi... | Implement the Python class `Composite` described below.
Class description:
Mix-in class that augments raph traversal for the new leaves defined in this package
Method signatures and docstrings:
- def expressions(self): Return a sequence over the nodes in my dependency graph that are constructed out of python expressi... | d741c44ffb3e9e1f726bf492202ac8738bb4aa1c | <|skeleton|>
class Composite:
"""Mix-in class that augments raph traversal for the new leaves defined in this package"""
def expressions(self):
"""Return a sequence over the nodes in my dependency graph that are constructed out of python expressions involving the names of other nodes"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Composite:
"""Mix-in class that augments raph traversal for the new leaves defined in this package"""
def expressions(self):
"""Return a sequence over the nodes in my dependency graph that are constructed out of python expressions involving the names of other nodes"""
for operand in self.... | the_stack_v2_python_sparse | packages/pyre/calc/Composite.py | pyre/pyre | train | 27 |
6ced3c0472633753126be4992303a1f4c315f026 | [
"super(AdversarialTrainingConfig, self).__init__()\nself.attack = None\nself.objective = None\nself.fraction = None",
"super(AdversarialTrainingConfig, self).validate()\nassert isinstance(self.attack, attacks.Attack)\nassert isinstance(self.objective, attacks.objectives.Objective)\nassert self.fraction > 0 and se... | <|body_start_0|>
super(AdversarialTrainingConfig, self).__init__()
self.attack = None
self.objective = None
self.fraction = None
<|end_body_0|>
<|body_start_1|>
super(AdversarialTrainingConfig, self).validate()
assert isinstance(self.attack, attacks.Attack)
asser... | Configuration for adversarial training. | AdversarialTrainingConfig | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdversarialTrainingConfig:
"""Configuration for adversarial training."""
def __init__(self):
"""Constructor."""
<|body_0|>
def validate(self):
"""Check validity."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(AdversarialTrainingConfig, se... | stack_v2_sparse_classes_36k_train_003923 | 16,771 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Check validity.",
"name": "validate",
"signature": "def validate(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010300 | Implement the Python class `AdversarialTrainingConfig` described below.
Class description:
Configuration for adversarial training.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def validate(self): Check validity. | Implement the Python class `AdversarialTrainingConfig` described below.
Class description:
Configuration for adversarial training.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def validate(self): Check validity.
<|skeleton|>
class AdversarialTrainingConfig:
"""Configuration for adversar... | 736c99b55a77d0c650eae5ced2d8312d13af0baf | <|skeleton|>
class AdversarialTrainingConfig:
"""Configuration for adversarial training."""
def __init__(self):
"""Constructor."""
<|body_0|>
def validate(self):
"""Check validity."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdversarialTrainingConfig:
"""Configuration for adversarial training."""
def __init__(self):
"""Constructor."""
super(AdversarialTrainingConfig, self).__init__()
self.attack = None
self.objective = None
self.fraction = None
def validate(self):
"""Check... | the_stack_v2_python_sparse | common/experiments.py | Adversarial-Intelligence-Group/color-adversarial-training | train | 0 |
f34d04c6577fd8f9c685ef6b5d38dbaca3bc1c7c | [
"dicoms = []\ncompLines = []\nif otherReplaceValues:\n replaceValues.update(otherReplaceValues)\nif filename == newFilename:\n bkpFN = filename.split('.')[0] + '.BKP'\n shutil.copy(filename, bkpFN)\n os.remove(filename)\n slicer.app.processEvents()\n filename = bkpFN\nmrmlFile = codecs.open(filena... | <|body_start_0|>
dicoms = []
compLines = []
if otherReplaceValues:
replaceValues.update(otherReplaceValues)
if filename == newFilename:
bkpFN = filename.split('.')[0] + '.BKP'
shutil.copy(filename, bkpFN)
os.remove(filename)
sli... | MrmlParser handles the parsing of a MRML file (XML-based) and either changes the paths of the remotely linked files to local directories, or to relative directories. | MrmlParser | [
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MrmlParser:
"""MrmlParser handles the parsing of a MRML file (XML-based) and either changes the paths of the remotely linked files to local directories, or to relative directories."""
def changeValues(filename, newFilename, replaceValues, otherReplaceValues, removeOriginalFile=False, debug=T... | stack_v2_sparse_classes_36k_train_003924 | 9,290 | permissive | [
{
"docstring": "Changes the string values within a given file based on a provided lists 'replaceValues' and 'otherReplaceValues'.",
"name": "changeValues",
"signature": "def changeValues(filename, newFilename, replaceValues, otherReplaceValues, removeOriginalFile=False, debug=True)"
},
{
"docstr... | 2 | stack_v2_sparse_classes_30k_train_004195 | Implement the Python class `MrmlParser` described below.
Class description:
MrmlParser handles the parsing of a MRML file (XML-based) and either changes the paths of the remotely linked files to local directories, or to relative directories.
Method signatures and docstrings:
- def changeValues(filename, newFilename, ... | Implement the Python class `MrmlParser` described below.
Class description:
MrmlParser handles the parsing of a MRML file (XML-based) and either changes the paths of the remotely linked files to local directories, or to relative directories.
Method signatures and docstrings:
- def changeValues(filename, newFilename, ... | 06867037842e2a074ae5ed3b0bdf4bf016a231a5 | <|skeleton|>
class MrmlParser:
"""MrmlParser handles the parsing of a MRML file (XML-based) and either changes the paths of the remotely linked files to local directories, or to relative directories."""
def changeValues(filename, newFilename, replaceValues, otherReplaceValues, removeOriginalFile=False, debug=T... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MrmlParser:
"""MrmlParser handles the parsing of a MRML file (XML-based) and either changes the paths of the remotely linked files to local directories, or to relative directories."""
def changeValues(filename, newFilename, replaceValues, otherReplaceValues, removeOriginalFile=False, debug=True):
... | the_stack_v2_python_sparse | XNATSlicer/XnatSlicerLib/utils/SlicerUtils.py | NrgXnat/XNATSlicer | train | 4 |
cad9f78c39871bcdb802137f5fe435d44056addb | [
"dob = self.cleaned_data['date_of_birth']\ndelta = now().year - dob.year - ((now().month, now().day) < (dob.month, dob.day))\nif delta < 18:\n self.add_error('date_of_birth', forms.ValidationError('Вам должно быть более 18 лет!'))\nreturn dob",
"user = super().save(commit=False)\nuser_type = self.data.get('use... | <|body_start_0|>
dob = self.cleaned_data['date_of_birth']
delta = now().year - dob.year - ((now().month, now().day) < (dob.month, dob.day))
if delta < 18:
self.add_error('date_of_birth', forms.ValidationError('Вам должно быть более 18 лет!'))
return dob
<|end_body_0|>
<|body... | Форма регистрации пользователя. | SignupForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignupForm:
"""Форма регистрации пользователя."""
def clean_date_of_birth(self):
"""Возвращает дату рождения пользователя из формы. Передаёт в форму ошибку в случае, если пользователю меньше 18 лет."""
<|body_0|>
def save(self):
"""Сохраняет данные формы для поль... | stack_v2_sparse_classes_36k_train_003925 | 2,729 | permissive | [
{
"docstring": "Возвращает дату рождения пользователя из формы. Передаёт в форму ошибку в случае, если пользователю меньше 18 лет.",
"name": "clean_date_of_birth",
"signature": "def clean_date_of_birth(self)"
},
{
"docstring": "Сохраняет данные формы для пользователя Django. Устанавливает тип по... | 2 | stack_v2_sparse_classes_30k_train_015764 | Implement the Python class `SignupForm` described below.
Class description:
Форма регистрации пользователя.
Method signatures and docstrings:
- def clean_date_of_birth(self): Возвращает дату рождения пользователя из формы. Передаёт в форму ошибку в случае, если пользователю меньше 18 лет.
- def save(self): Сохраняет ... | Implement the Python class `SignupForm` described below.
Class description:
Форма регистрации пользователя.
Method signatures and docstrings:
- def clean_date_of_birth(self): Возвращает дату рождения пользователя из формы. Передаёт в форму ошибку в случае, если пользователю меньше 18 лет.
- def save(self): Сохраняет ... | baacb7f54a19c55854fd068d6e38b3048a03d13d | <|skeleton|>
class SignupForm:
"""Форма регистрации пользователя."""
def clean_date_of_birth(self):
"""Возвращает дату рождения пользователя из формы. Передаёт в форму ошибку в случае, если пользователю меньше 18 лет."""
<|body_0|>
def save(self):
"""Сохраняет данные формы для поль... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SignupForm:
"""Форма регистрации пользователя."""
def clean_date_of_birth(self):
"""Возвращает дату рождения пользователя из формы. Передаёт в форму ошибку в случае, если пользователю меньше 18 лет."""
dob = self.cleaned_data['date_of_birth']
delta = now().year - dob.year - ((now(... | the_stack_v2_python_sparse | authapp/forms.py | Gwellir/my-region | train | 0 |
2c3cbb18d1034f0b253f2480d6cc26ef03435c70 | [
"active_window.ActiveWindow.__init__(self, gui)\nself.challenge_label = tk.Label(self.frame)\nself.challenge_label.pack()\nself.challenge_type = selected_mode\nself.challenge_duration = duration_seconds\nself.challenge_management = challenge_management.ChallengeManagement()\nself._load_new_challenge()",
"challeng... | <|body_start_0|>
active_window.ActiveWindow.__init__(self, gui)
self.challenge_label = tk.Label(self.frame)
self.challenge_label.pack()
self.challenge_type = selected_mode
self.challenge_duration = duration_seconds
self.challenge_management = challenge_management.Challeng... | NewChallengeWindow | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewChallengeWindow:
def __init__(self, gui, selected_mode, duration_seconds):
"""Creates the challenge window given the type of challenge, the challenge duration Args: gui ([type]): [the gui that this window is attached too] selected_mode: An integer corresponding to the challenge mode, ... | stack_v2_sparse_classes_36k_train_003926 | 25,668 | no_license | [
{
"docstring": "Creates the challenge window given the type of challenge, the challenge duration Args: gui ([type]): [the gui that this window is attached too] selected_mode: An integer corresponding to the challenge mode, and prorgramming language if applicable. One of: {\"Standard\": 0, \"Dictation\": 1, \"Ja... | 2 | stack_v2_sparse_classes_30k_train_010464 | Implement the Python class `NewChallengeWindow` described below.
Class description:
Implement the NewChallengeWindow class.
Method signatures and docstrings:
- def __init__(self, gui, selected_mode, duration_seconds): Creates the challenge window given the type of challenge, the challenge duration Args: gui ([type]):... | Implement the Python class `NewChallengeWindow` described below.
Class description:
Implement the NewChallengeWindow class.
Method signatures and docstrings:
- def __init__(self, gui, selected_mode, duration_seconds): Creates the challenge window given the type of challenge, the challenge duration Args: gui ([type]):... | e26d9450b98fa0f372bcdf6eaf251a2c9dcba44e | <|skeleton|>
class NewChallengeWindow:
def __init__(self, gui, selected_mode, duration_seconds):
"""Creates the challenge window given the type of challenge, the challenge duration Args: gui ([type]): [the gui that this window is attached too] selected_mode: An integer corresponding to the challenge mode, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NewChallengeWindow:
def __init__(self, gui, selected_mode, duration_seconds):
"""Creates the challenge window given the type of challenge, the challenge duration Args: gui ([type]): [the gui that this window is attached too] selected_mode: An integer corresponding to the challenge mode, and prorgrammi... | the_stack_v2_python_sparse | user_interface/active_windows/new_challenge_window.py | pucheng-tan/WordFlow | train | 0 | |
ae029d3b2b6c6a2b25b628f95ec2ace237f09068 | [
"BaseModel.__init__(self)\nself.uid = uid\nself.ban_chat = 0\nself.ban_account = 0\nself.boss_enter_tag = 0",
"ext_info = cls(uid)\next_info.put()\nreturn cls.get(uid)"
] | <|body_start_0|>
BaseModel.__init__(self)
self.uid = uid
self.ban_chat = 0
self.ban_account = 0
self.boss_enter_tag = 0
<|end_body_0|>
<|body_start_1|>
ext_info = cls(uid)
ext_info.put()
return cls.get(uid)
<|end_body_1|>
| 角色游戏扩展信息 Attributes: uid: 角色ID str items: 扩展信息 dict | ExtInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExtInfo:
"""角色游戏扩展信息 Attributes: uid: 角色ID str items: 扩展信息 dict"""
def __init__(self, uid=None):
"""初始化角色游戏信息 Args: uid: 平台角色ID"""
<|body_0|>
def install(cls, uid):
"""为新角色初始安装游戏信息 Args: uid: 角色ID Returns: ext_info: 角色游戏扩展信息对象实例"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_003927 | 1,032 | no_license | [
{
"docstring": "初始化角色游戏信息 Args: uid: 平台角色ID",
"name": "__init__",
"signature": "def __init__(self, uid=None)"
},
{
"docstring": "为新角色初始安装游戏信息 Args: uid: 角色ID Returns: ext_info: 角色游戏扩展信息对象实例",
"name": "install",
"signature": "def install(cls, uid)"
}
] | 2 | null | Implement the Python class `ExtInfo` described below.
Class description:
角色游戏扩展信息 Attributes: uid: 角色ID str items: 扩展信息 dict
Method signatures and docstrings:
- def __init__(self, uid=None): 初始化角色游戏信息 Args: uid: 平台角色ID
- def install(cls, uid): 为新角色初始安装游戏信息 Args: uid: 角色ID Returns: ext_info: 角色游戏扩展信息对象实例 | Implement the Python class `ExtInfo` described below.
Class description:
角色游戏扩展信息 Attributes: uid: 角色ID str items: 扩展信息 dict
Method signatures and docstrings:
- def __init__(self, uid=None): 初始化角色游戏信息 Args: uid: 平台角色ID
- def install(cls, uid): 为新角色初始安装游戏信息 Args: uid: 角色ID Returns: ext_info: 角色游戏扩展信息对象实例
<|skeleton|>... | 4f430d5631b1118ad251bdaf8384bc0dbdaf07b9 | <|skeleton|>
class ExtInfo:
"""角色游戏扩展信息 Attributes: uid: 角色ID str items: 扩展信息 dict"""
def __init__(self, uid=None):
"""初始化角色游戏信息 Args: uid: 平台角色ID"""
<|body_0|>
def install(cls, uid):
"""为新角色初始安装游戏信息 Args: uid: 角色ID Returns: ext_info: 角色游戏扩展信息对象实例"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExtInfo:
"""角色游戏扩展信息 Attributes: uid: 角色ID str items: 扩展信息 dict"""
def __init__(self, uid=None):
"""初始化角色游戏信息 Args: uid: 平台角色ID"""
BaseModel.__init__(self)
self.uid = uid
self.ban_chat = 0
self.ban_account = 0
self.boss_enter_tag = 0
def install(cls, u... | the_stack_v2_python_sparse | server/apps/models/ext_info.py | wade333777/cocos-js-tips | train | 0 |
5afc3fb87ca2ef8d508ac5def58ef62b71f84e38 | [
"count_map = {}\nfor n in nums1:\n if n in count_map:\n count_map[n] += 1\n else:\n count_map[n] = 1\nresult = []\nfor n in nums2:\n if n in count_map and count_map[n] > 0:\n count_map[n] -= 1\n result.append(n)\nreturn result",
"item_set = set()\nfor n in nums1:\n item_set... | <|body_start_0|>
count_map = {}
for n in nums1:
if n in count_map:
count_map[n] += 1
else:
count_map[n] = 1
result = []
for n in nums2:
if n in count_map and count_map[n] > 0:
count_map[n] -= 1
... | Intersection | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Intersection:
def intersect_with_dup(nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_0|>
def intersect_no_dup(nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_003928 | 957 | permissive | [
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: List[int]",
"name": "intersect_with_dup",
"signature": "def intersect_with_dup(nums1, nums2)"
},
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: List[int]",
"name": "intersect_no_dup",
"signature"... | 2 | stack_v2_sparse_classes_30k_train_007304 | Implement the Python class `Intersection` described below.
Class description:
Implement the Intersection class.
Method signatures and docstrings:
- def intersect_with_dup(nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int]
- def intersect_no_dup(nums1, nums2): :type nums1: List[int] :type n... | Implement the Python class `Intersection` described below.
Class description:
Implement the Intersection class.
Method signatures and docstrings:
- def intersect_with_dup(nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int]
- def intersect_no_dup(nums1, nums2): :type nums1: List[int] :type n... | 77838c37e3fdae0f2ec628aa7ddc59f4a5949bbe | <|skeleton|>
class Intersection:
def intersect_with_dup(nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_0|>
def intersect_no_dup(nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Intersection:
def intersect_with_dup(nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
count_map = {}
for n in nums1:
if n in count_map:
count_map[n] += 1
else:
count_map[n] = 1
result = ... | the_stack_v2_python_sparse | Python/dev/maps/intersection.py | faisaldialpad/hellouniverse | train | 0 | |
660a39530aa637823311a8cc9e113bf07aeaba00 | [
"self.edges = edges\nself.t_width = t_width\nself.t_height = t_height\nwidth = t_width - 2 * border\nheight = t_height - 2 * border\nassert width >= 1\nassert height >= 1\nx_coords, y_coords = zip(*points)\nunscaled_width = max(x_coords) - min(x_coords)\nunscaled_height = max(y_coords) - min(y_coords)\nc_width = wi... | <|body_start_0|>
self.edges = edges
self.t_width = t_width
self.t_height = t_height
width = t_width - 2 * border
height = t_height - 2 * border
assert width >= 1
assert height >= 1
x_coords, y_coords = zip(*points)
unscaled_width = max(x_coords) - ... | This used to be a single function but there is too much going on in it. | ImgHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImgHelper:
"""This used to be a single function but there is too much going on in it."""
def __init__(self, points, edges, t_width, t_height, border):
"""@param points: an ordered list of (x, y) pairs @param edges: a set of point index pairs @param t_width: the image width in pixels ... | stack_v2_sparse_classes_36k_train_003929 | 13,149 | no_license | [
{
"docstring": "@param points: an ordered list of (x, y) pairs @param edges: a set of point index pairs @param t_width: the image width in pixels @param t_height: the image height in pixels @param border: the width and height of the image border in pixels",
"name": "__init__",
"signature": "def __init__... | 3 | stack_v2_sparse_classes_30k_train_003073 | Implement the Python class `ImgHelper` described below.
Class description:
This used to be a single function but there is too much going on in it.
Method signatures and docstrings:
- def __init__(self, points, edges, t_width, t_height, border): @param points: an ordered list of (x, y) pairs @param edges: a set of poi... | Implement the Python class `ImgHelper` described below.
Class description:
This used to be a single function but there is too much going on in it.
Method signatures and docstrings:
- def __init__(self, points, edges, t_width, t_height, border): @param points: an ordered list of (x, y) pairs @param edges: a set of poi... | 91c6f8331f18c914eb3dfc51bc166915998c5081 | <|skeleton|>
class ImgHelper:
"""This used to be a single function but there is too much going on in it."""
def __init__(self, points, edges, t_width, t_height, border):
"""@param points: an ordered list of (x, y) pairs @param edges: a set of point index pairs @param t_width: the image width in pixels ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImgHelper:
"""This used to be a single function but there is too much going on in it."""
def __init__(self, points, edges, t_width, t_height, border):
"""@param points: an ordered list of (x, y) pairs @param edges: a set of point index pairs @param t_width: the image width in pixels @param t_heig... | the_stack_v2_python_sparse | 20100817b.py | argriffing/xgcode | train | 1 |
4a2451b6472d220d9c590f7ed3347f0091a2f559 | [
"vals = []\n\ndef preOrder(node):\n if node:\n vals.append(node.val)\n preOrder(node.left)\n preOrder(node.right)\npreOrder(root)\nreturn ' '.join(map(str, vals))",
"values = collections.deque((int(val) for val in data.split()))\n\ndef build(min_val, max_val):\n if values and min_val < ... | <|body_start_0|>
vals = []
def preOrder(node):
if node:
vals.append(node.val)
preOrder(node.left)
preOrder(node.right)
preOrder(root)
return ' '.join(map(str, vals))
<|end_body_0|>
<|body_start_1|>
values = collections... | Codec1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec1:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str https://leetcode.com/problems/serialize-and-deserialize-bst/discuss/93171/ beats 95.29%"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data t... | stack_v2_sparse_classes_36k_train_003930 | 5,528 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str https://leetcode.com/problems/serialize-and-deserialize-bst/discuss/93171/ beats 95.29%",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type ... | 2 | null | Implement the Python class `Codec1` described below.
Class description:
Implement the Codec1 class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str https://leetcode.com/problems/serialize-and-deserialize-bst/discuss/93171/ beats 95.29%... | Implement the Python class `Codec1` described below.
Class description:
Implement the Codec1 class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str https://leetcode.com/problems/serialize-and-deserialize-bst/discuss/93171/ beats 95.29%... | 7e0e917c15d3e35f49da3a00ef395bd5ff180d79 | <|skeleton|>
class Codec1:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str https://leetcode.com/problems/serialize-and-deserialize-bst/discuss/93171/ beats 95.29%"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec1:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str https://leetcode.com/problems/serialize-and-deserialize-bst/discuss/93171/ beats 95.29%"""
vals = []
def preOrder(node):
if node:
vals.append(node.val)... | the_stack_v2_python_sparse | LeetCode/449_serialize_and_deserialize_bst.py | yao23/Machine_Learning_Playground | train | 12 | |
019acd180f9ea97c0406f9698e498a47565b3660 | [
"super().__init__()\nself.beta = nn.Parameter(torch.tensor(0.0, dtype=torch.float))\nself.score_no_click = nn.Parameter(torch.tensor(0.0, dtype=torch.float))",
"batch_size = user.shape[0]\ns = torch.einsum('be,bde->bd', user, doc)\ns = s * self.beta\ns = torch.cat([s, self.score_no_click.expand((batch_size, 1))],... | <|body_start_0|>
super().__init__()
self.beta = nn.Parameter(torch.tensor(0.0, dtype=torch.float))
self.score_no_click = nn.Parameter(torch.tensor(0.0, dtype=torch.float))
<|end_body_0|>
<|body_start_1|>
batch_size = user.shape[0]
s = torch.einsum('be,bde->bd', user, doc)
... | The user choice model for SlateQ. This class implements a multinomial logit model for predicting user clicks. Under this model, the click probability of a document is proportional to: .. math:: \\exp( ext{beta} * ext{doc_user_affinity} + ext{score_no_click}) | UserChoiceModel | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserChoiceModel:
"""The user choice model for SlateQ. This class implements a multinomial logit model for predicting user clicks. Under this model, the click probability of a document is proportional to: .. math:: \\exp( ext{beta} * ext{doc_user_affinity} + ext{score_no_click})"""
def __init... | stack_v2_sparse_classes_36k_train_003931 | 6,840 | permissive | [
{
"docstring": "Initializes a UserChoiceModel instance.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Evaluate the user choice model. This function outputs user click scores for candidate documents. The exponentials of these scores are proportional user click probabi... | 2 | stack_v2_sparse_classes_30k_train_016458 | Implement the Python class `UserChoiceModel` described below.
Class description:
The user choice model for SlateQ. This class implements a multinomial logit model for predicting user clicks. Under this model, the click probability of a document is proportional to: .. math:: \\exp( ext{beta} * ext{doc_user_affinity} + ... | Implement the Python class `UserChoiceModel` described below.
Class description:
The user choice model for SlateQ. This class implements a multinomial logit model for predicting user clicks. Under this model, the click probability of a document is proportional to: .. math:: \\exp( ext{beta} * ext{doc_user_affinity} + ... | edba68c3e7cf255d1d6479329f305adb7fa4c3ed | <|skeleton|>
class UserChoiceModel:
"""The user choice model for SlateQ. This class implements a multinomial logit model for predicting user clicks. Under this model, the click probability of a document is proportional to: .. math:: \\exp( ext{beta} * ext{doc_user_affinity} + ext{score_no_click})"""
def __init... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserChoiceModel:
"""The user choice model for SlateQ. This class implements a multinomial logit model for predicting user clicks. Under this model, the click probability of a document is proportional to: .. math:: \\exp( ext{beta} * ext{doc_user_affinity} + ext{score_no_click})"""
def __init__(self):
... | the_stack_v2_python_sparse | rllib/algorithms/slateq/slateq_torch_model.py | ray-project/ray | train | 29,482 |
1fd11d927fa29686727bdf6229280b7422c59679 | [
"try:\n answer = self.model.objects.get(user=user, question=question)\nexcept ObjectDoesNotExist:\n answer = self.model(answer=answer, question=question, user=user)\n answer.save()\nsignals.edit.send(sender=self.model, original=None, current=answer, editor=user)\nreturn answer",
"ans = data.get('answer',... | <|body_start_0|>
try:
answer = self.model.objects.get(user=user, question=question)
except ObjectDoesNotExist:
answer = self.model(answer=answer, question=question, user=user)
answer.save()
signals.edit.send(sender=self.model, original=None, current=answer, ed... | AnswerManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnswerManager:
def answer_question(self, answer, question, user):
"""Answers target @question with @answer."""
<|body_0|>
def edit(self, answer, user, data):
"""Modifies an @answer with new @data. Sends edit signal."""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_36k_train_003932 | 4,799 | permissive | [
{
"docstring": "Answers target @question with @answer.",
"name": "answer_question",
"signature": "def answer_question(self, answer, question, user)"
},
{
"docstring": "Modifies an @answer with new @data. Sends edit signal.",
"name": "edit",
"signature": "def edit(self, answer, user, data... | 2 | stack_v2_sparse_classes_30k_train_019866 | Implement the Python class `AnswerManager` described below.
Class description:
Implement the AnswerManager class.
Method signatures and docstrings:
- def answer_question(self, answer, question, user): Answers target @question with @answer.
- def edit(self, answer, user, data): Modifies an @answer with new @data. Send... | Implement the Python class `AnswerManager` described below.
Class description:
Implement the AnswerManager class.
Method signatures and docstrings:
- def answer_question(self, answer, question, user): Answers target @question with @answer.
- def edit(self, answer, user, data): Modifies an @answer with new @data. Send... | 5f8f3b682ac28fd3f464e7a993c3988c1a49eb02 | <|skeleton|>
class AnswerManager:
def answer_question(self, answer, question, user):
"""Answers target @question with @answer."""
<|body_0|>
def edit(self, answer, user, data):
"""Modifies an @answer with new @data. Sends edit signal."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnswerManager:
def answer_question(self, answer, question, user):
"""Answers target @question with @answer."""
try:
answer = self.model.objects.get(user=user, question=question)
except ObjectDoesNotExist:
answer = self.model(answer=answer, question=question, use... | the_stack_v2_python_sparse | eruditio/shared_apps/django_qa/models.py | genghisu/eruditio | train | 0 | |
0b539958e67bacb00fc2bef1b3ccb59689a34798 | [
"result = [0] * num_people\ni = 0\nwhile candies > 0:\n result[i % num_people] += min(candies, i + 1)\n candies -= i + 1\n i += 1\nreturn result",
"arr = []\ncount = 1\nwhile candies > 0:\n if candies > count:\n arr.append(count)\n else:\n arr.append(candies)\n candies = 0\n ... | <|body_start_0|>
result = [0] * num_people
i = 0
while candies > 0:
result[i % num_people] += min(candies, i + 1)
candies -= i + 1
i += 1
return result
<|end_body_0|>
<|body_start_1|>
arr = []
count = 1
while candies > 0:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def distribute_candies(self, candies: int, num_people: int) -> str:
"""分发糖果给人 Args: candies: 糖果数 num_people: 人数 Returns: 糖果数组"""
<|body_0|>
def distribute_candies(self, candies: int, num_people: int) -> str:
"""分发糖果给人(将一维数组转成二维数组形式) Args: candies: 糖果数 num_p... | stack_v2_sparse_classes_36k_train_003933 | 3,755 | permissive | [
{
"docstring": "分发糖果给人 Args: candies: 糖果数 num_people: 人数 Returns: 糖果数组",
"name": "distribute_candies",
"signature": "def distribute_candies(self, candies: int, num_people: int) -> str"
},
{
"docstring": "分发糖果给人(将一维数组转成二维数组形式) Args: candies: 糖果数 num_people: 人数 Returns: 糖果数组",
"name": "distrib... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def distribute_candies(self, candies: int, num_people: int) -> str: 分发糖果给人 Args: candies: 糖果数 num_people: 人数 Returns: 糖果数组
- def distribute_candies(self, candies: int, num_people... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def distribute_candies(self, candies: int, num_people: int) -> str: 分发糖果给人 Args: candies: 糖果数 num_people: 人数 Returns: 糖果数组
- def distribute_candies(self, candies: int, num_people... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def distribute_candies(self, candies: int, num_people: int) -> str:
"""分发糖果给人 Args: candies: 糖果数 num_people: 人数 Returns: 糖果数组"""
<|body_0|>
def distribute_candies(self, candies: int, num_people: int) -> str:
"""分发糖果给人(将一维数组转成二维数组形式) Args: candies: 糖果数 num_p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def distribute_candies(self, candies: int, num_people: int) -> str:
"""分发糖果给人 Args: candies: 糖果数 num_people: 人数 Returns: 糖果数组"""
result = [0] * num_people
i = 0
while candies > 0:
result[i % num_people] += min(candies, i + 1)
candies -= i + 1
... | the_stack_v2_python_sparse | src/leetcodepython/array/distribute_candies_people_1103.py | zhangyu345293721/leetcode | train | 101 | |
70f81b407eabad390639a895b3cf8bc32eff3efa | [
"super(BlackListResultModifier, self).__init__(order)\nself.info = 'Modify search results based on a blacklist.'\nself.terms = terms\ntry:\n self.black_list_string = ' '.join(filter(str.isalpha, terms.replace('+', ' ').lower().split()))\nexcept TypeError:\n tmp = terms.encode('utf-8').lower()\n self.black_... | <|body_start_0|>
super(BlackListResultModifier, self).__init__(order)
self.info = 'Modify search results based on a blacklist.'
self.terms = terms
try:
self.black_list_string = ' '.join(filter(str.isalpha, terms.replace('+', ' ').lower().split()))
except TypeError:
... | Modify processes result entry content and replaces blacklisted words Options: * order (int): modifier precedence * terms (str): terms that, if appearing in the result, will be replaced with *** | BlackListResultModifier | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlackListResultModifier:
"""Modify processes result entry content and replaces blacklisted words Options: * order (int): modifier precedence * terms (str): terms that, if appearing in the result, will be replaced with ***"""
def __init__(self, order=0, terms='', customFields=[]):
"""... | stack_v2_sparse_classes_36k_train_003934 | 3,589 | permissive | [
{
"docstring": "Constructor for BlackListResultModifier. Parameters: * order (int): filter precedence * terms (str): separated by + characters * customFields (list of str): extra fields in the results to modify - depedendent upon their existence in the search service results",
"name": "__init__",
"signa... | 3 | null | Implement the Python class `BlackListResultModifier` described below.
Class description:
Modify processes result entry content and replaces blacklisted words Options: * order (int): modifier precedence * terms (str): terms that, if appearing in the result, will be replaced with ***
Method signatures and docstrings:
-... | Implement the Python class `BlackListResultModifier` described below.
Class description:
Modify processes result entry content and replaces blacklisted words Options: * order (int): modifier precedence * terms (str): terms that, if appearing in the result, will be replaced with ***
Method signatures and docstrings:
-... | ed72aee466649bd834d5b4459eb6e0173df6e2ec | <|skeleton|>
class BlackListResultModifier:
"""Modify processes result entry content and replaces blacklisted words Options: * order (int): modifier precedence * terms (str): terms that, if appearing in the result, will be replaced with ***"""
def __init__(self, order=0, terms='', customFields=[]):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BlackListResultModifier:
"""Modify processes result entry content and replaces blacklisted words Options: * order (int): modifier precedence * terms (str): terms that, if appearing in the result, will be replaced with ***"""
def __init__(self, order=0, terms='', customFields=[]):
"""Constructor f... | the_stack_v2_python_sparse | reference-code/puppy/result/modifier/blacklistmodifier.py | Granvanoeli/ifind | train | 0 |
3a44b3761413c880fe481fb0de764ba1ff5b3464 | [
"user = serializer.context.get('request').user\nusername = getattr(user, 'username', 'guest')\nserializer.save(creator=username, updated_by=username)\nservice_type = serializer.data.get('service_type')\nTicketStatusConfig.update_config(service_type, user)",
"user = serializer.context.get('request').user\nusername... | <|body_start_0|>
user = serializer.context.get('request').user
username = getattr(user, 'username', 'guest')
serializer.save(creator=username, updated_by=username)
service_type = serializer.data.get('service_type')
TicketStatusConfig.update_config(service_type, user)
<|end_body_0... | 按需改造DRF默认的ModelViewSet类 | ModelViewSet | [
"MIT",
"LGPL-2.1-or-later",
"LGPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelViewSet:
"""按需改造DRF默认的ModelViewSet类"""
def perform_create(self, serializer):
"""创建时补充基础Model中的字段"""
<|body_0|>
def perform_update(self, serializer):
"""更新时补充基础Model中的字段"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
user = serializer.conte... | stack_v2_sparse_classes_36k_train_003935 | 11,791 | permissive | [
{
"docstring": "创建时补充基础Model中的字段",
"name": "perform_create",
"signature": "def perform_create(self, serializer)"
},
{
"docstring": "更新时补充基础Model中的字段",
"name": "perform_update",
"signature": "def perform_update(self, serializer)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010648 | Implement the Python class `ModelViewSet` described below.
Class description:
按需改造DRF默认的ModelViewSet类
Method signatures and docstrings:
- def perform_create(self, serializer): 创建时补充基础Model中的字段
- def perform_update(self, serializer): 更新时补充基础Model中的字段 | Implement the Python class `ModelViewSet` described below.
Class description:
按需改造DRF默认的ModelViewSet类
Method signatures and docstrings:
- def perform_create(self, serializer): 创建时补充基础Model中的字段
- def perform_update(self, serializer): 更新时补充基础Model中的字段
<|skeleton|>
class ModelViewSet:
"""按需改造DRF默认的ModelViewSet类"""
... | 2d708bd0d869d391456e0fb8d644af3b9f031acf | <|skeleton|>
class ModelViewSet:
"""按需改造DRF默认的ModelViewSet类"""
def perform_create(self, serializer):
"""创建时补充基础Model中的字段"""
<|body_0|>
def perform_update(self, serializer):
"""更新时补充基础Model中的字段"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModelViewSet:
"""按需改造DRF默认的ModelViewSet类"""
def perform_create(self, serializer):
"""创建时补充基础Model中的字段"""
user = serializer.context.get('request').user
username = getattr(user, 'username', 'guest')
serializer.save(creator=username, updated_by=username)
service_type ... | the_stack_v2_python_sparse | itsm/ticket_status/views.py | TencentBlueKing/bk-itsm | train | 100 |
daa3f6113876514e274699cd404d39b40f3807da | [
"result = []\nfor a in A:\n al, ar = (a[0], a[1])\n for b in B:\n bl, br = (b[0], b[1])\n if bl > ar:\n break\n if br < al:\n continue\n l = max(al, bl)\n r = min(ar, br)\n result.append([l, r])\nreturn result",
"i = 0\nj = 0\nresult = []\nwhil... | <|body_start_0|>
result = []
for a in A:
al, ar = (a[0], a[1])
for b in B:
bl, br = (b[0], b[1])
if bl > ar:
break
if br < al:
continue
l = max(al, bl)
r = min(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def intervalIntersection(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] O(M*N)"""
<|body_0|>
def rewrite(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] O(M+N)"""
<... | stack_v2_sparse_classes_36k_train_003936 | 2,879 | no_license | [
{
"docstring": ":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] O(M*N)",
"name": "intervalIntersection",
"signature": "def intervalIntersection(self, A, B)"
},
{
"docstring": ":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] O(M+N)",
"name":... | 2 | stack_v2_sparse_classes_30k_train_021605 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intervalIntersection(self, A, B): :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] O(M*N)
- def rewrite(self, A, B): :type A: List[List[int]] :type B... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intervalIntersection(self, A, B): :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] O(M*N)
- def rewrite(self, A, B): :type A: List[List[int]] :type B... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def intervalIntersection(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] O(M*N)"""
<|body_0|>
def rewrite(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] O(M+N)"""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def intervalIntersection(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] O(M*N)"""
result = []
for a in A:
al, ar = (a[0], a[1])
for b in B:
bl, br = (b[0], b[1])
if bl > ar:
... | the_stack_v2_python_sparse | two-pointers/986_Interval_List_Intersections.py | vsdrun/lc_public | train | 6 | |
b4b37cdd9fb0f8797a8a94956cc9291abbd9d55a | [
"result = -1\nfor index in range(len(nums)):\n if target == nums[index]:\n return index\nreturn result",
"result = -1\nleft = 0\nright = len(nums) - 1\nwhile left <= right:\n midi = int((left + right) / 2)\n mid = nums[midi]\n if mid == target:\n return midi\n if mid < target:\n ... | <|body_start_0|>
result = -1
for index in range(len(nums)):
if target == nums[index]:
return index
return result
<|end_body_0|>
<|body_start_1|>
result = -1
left = 0
right = len(nums) - 1
while left <= right:
midi = int((le... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def search1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
re... | stack_v2_sparse_classes_36k_train_003937 | 1,676 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "search",
"signature": "def search(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "search1",
"signature": "def search1(self, nums, target)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004661 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def search1(self, nums, target): :type nums: List[int] :type target: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def search1(self, nums, target): :type nums: List[int] :type target: int :rtype: int
<|skel... | f27169285db00d3751c3035f2f4dabad6135c8cc | <|skeleton|>
class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def search1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
result = -1
for index in range(len(nums)):
if target == nums[index]:
return index
return result
def search1(self, nums, target):
""":type... | the_stack_v2_python_sparse | leet_code/easy/704_binary-search.py | baofree/solve-problems-every-day | train | 0 | |
27059d86c6f839598ed403d7cb685f8b594fe5d5 | [
"visited = [0 for i in range(numCourses)]\nadjlist = [set() for i in range(numCourses)]\nresult = []\nfor edge in prerequisites:\n adjlist[edge[1]].add(edge[0])\n\ndef dfs(root):\n visited[root] = 1\n for neighbor in adjlist[root]:\n if visited[neighbor] == 1:\n return False\n elif... | <|body_start_0|>
visited = [0 for i in range(numCourses)]
adjlist = [set() for i in range(numCourses)]
result = []
for edge in prerequisites:
adjlist[edge[1]].add(edge[0])
def dfs(root):
visited[root] = 1
for neighbor in adjlist[root]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findOrder(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int]"""
<|body_0|>
def findOrder(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rtyp... | stack_v2_sparse_classes_36k_train_003938 | 1,809 | no_license | [
{
"docstring": ":type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int]",
"name": "findOrder",
"signature": "def findOrder(self, numCourses, prerequisites)"
},
{
"docstring": ":type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int]",
"name": "findOrd... | 2 | stack_v2_sparse_classes_30k_train_003400 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findOrder(self, numCourses, prerequisites): :type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int]
- def findOrder(self, numCourses, prerequisites): :ty... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findOrder(self, numCourses, prerequisites): :type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int]
- def findOrder(self, numCourses, prerequisites): :ty... | d953abe2c9680f636563e76287d2f907e90ced63 | <|skeleton|>
class Solution:
def findOrder(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int]"""
<|body_0|>
def findOrder(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rtyp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findOrder(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int]"""
visited = [0 for i in range(numCourses)]
adjlist = [set() for i in range(numCourses)]
result = []
for edge in prerequisites:
... | the_stack_v2_python_sparse | Python_leetcode/210_course_schedule_ii.py | xiangcao/Leetcode | train | 0 | |
964805d928104acf91b1f94bae1472dba5b60b6b | [
"if k == 0:\n total.append(part)\n return\nfor i, e in enumerate(options):\n self.helper(total, part + [e], options[i + 1:], k - 1)",
"res = []\nif k == 0:\n return [[]]\nself.helper(res, [], list(range(1, n + 1)), k)\nreturn res"
] | <|body_start_0|>
if k == 0:
total.append(part)
return
for i, e in enumerate(options):
self.helper(total, part + [e], options[i + 1:], k - 1)
<|end_body_0|>
<|body_start_1|>
res = []
if k == 0:
return [[]]
self.helper(res, [], list(... | Solution description | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Solution description"""
def helper(self, total, part, options, k):
"""Solution function description"""
<|body_0|>
def func(self, n, k):
"""Solution function description"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if k == 0:
... | stack_v2_sparse_classes_36k_train_003939 | 782 | permissive | [
{
"docstring": "Solution function description",
"name": "helper",
"signature": "def helper(self, total, part, options, k)"
},
{
"docstring": "Solution function description",
"name": "func",
"signature": "def func(self, n, k)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Solution description
Method signatures and docstrings:
- def helper(self, total, part, options, k): Solution function description
- def func(self, n, k): Solution function description | Implement the Python class `Solution` described below.
Class description:
Solution description
Method signatures and docstrings:
- def helper(self, total, part, options, k): Solution function description
- def func(self, n, k): Solution function description
<|skeleton|>
class Solution:
"""Solution description"""... | 869ee24c50c08403b170e8f7868699185e9dfdd1 | <|skeleton|>
class Solution:
"""Solution description"""
def helper(self, total, part, options, k):
"""Solution function description"""
<|body_0|>
def func(self, n, k):
"""Solution function description"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""Solution description"""
def helper(self, total, part, options, k):
"""Solution function description"""
if k == 0:
total.append(part)
return
for i, e in enumerate(options):
self.helper(total, part + [e], options[i + 1:], k - 1)
... | the_stack_v2_python_sparse | 77.comibnations/2.py | cerebrumaize/leetcode | train | 0 |
8c2d16e7f9f3d28690de8da155b40c8f377f801d | [
"if '_xml_ns' in kwargs:\n self._xml_ns = kwargs['_xml_ns']\nif '_xml_ns_key' in kwargs:\n self._xml_ns_key = kwargs['_xml_ns_key']\nself.PixelType = PixelType\nself.RemapInformation = RemapInformation\nself.MagnificationMethod = MagnificationMethod\nself.DecimationMethod = DecimationMethod\nself.DRAHistogram... | <|body_start_0|>
if '_xml_ns' in kwargs:
self._xml_ns = kwargs['_xml_ns']
if '_xml_ns_key' in kwargs:
self._xml_ns_key = kwargs['_xml_ns_key']
self.PixelType = PixelType
self.RemapInformation = RemapInformation
self.MagnificationMethod = MagnificationMetho... | ProductDisplayType | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductDisplayType:
def __init__(self, PixelType=None, RemapInformation=None, MagnificationMethod=None, DecimationMethod=None, DRAHistogramOverrides=None, MonitorCompensationApplied=None, DisplayExtensions=None, **kwargs):
"""Parameters ---------- PixelType : PixelTypeType RemapInformati... | stack_v2_sparse_classes_36k_train_003940 | 18,845 | permissive | [
{
"docstring": "Parameters ---------- PixelType : PixelTypeType RemapInformation : None|RemapChoiceType MagnificationMethod : None|str DecimationMethod : None|str DRAHistogramOverrides : None|DRAHistogramOverridesType MonitorCompensationApplied : None|MonitorCompensationAppliedType DisplayExtensions : None|Para... | 2 | null | Implement the Python class `ProductDisplayType` described below.
Class description:
Implement the ProductDisplayType class.
Method signatures and docstrings:
- def __init__(self, PixelType=None, RemapInformation=None, MagnificationMethod=None, DecimationMethod=None, DRAHistogramOverrides=None, MonitorCompensationAppl... | Implement the Python class `ProductDisplayType` described below.
Class description:
Implement the ProductDisplayType class.
Method signatures and docstrings:
- def __init__(self, PixelType=None, RemapInformation=None, MagnificationMethod=None, DecimationMethod=None, DRAHistogramOverrides=None, MonitorCompensationAppl... | de1b1886f161a83b6c89aadc7a2c7cfc4892ef81 | <|skeleton|>
class ProductDisplayType:
def __init__(self, PixelType=None, RemapInformation=None, MagnificationMethod=None, DecimationMethod=None, DRAHistogramOverrides=None, MonitorCompensationApplied=None, DisplayExtensions=None, **kwargs):
"""Parameters ---------- PixelType : PixelTypeType RemapInformati... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProductDisplayType:
def __init__(self, PixelType=None, RemapInformation=None, MagnificationMethod=None, DecimationMethod=None, DRAHistogramOverrides=None, MonitorCompensationApplied=None, DisplayExtensions=None, **kwargs):
"""Parameters ---------- PixelType : PixelTypeType RemapInformation : None|Rema... | the_stack_v2_python_sparse | sarpy/io/product/sidd1_elements/Display.py | ngageoint/sarpy | train | 192 | |
d05b7d479a15542f846fef1c9e5247ef2456a926 | [
"if not root:\n return 0\nelif not root.left:\n return self.minDepth(root.right) + 1\nelif not root.right:\n return self.minDepth(root.left) + 1\nelse:\n return min(self.minDepth(root.left), self.minDepth(root.right)) + 1",
"if not root:\n return 0\nd = deque([(1, root)])\nwhile d:\n height, roo... | <|body_start_0|>
if not root:
return 0
elif not root.left:
return self.minDepth(root.right) + 1
elif not root.right:
return self.minDepth(root.left) + 1
else:
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
<|end_body_0|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def minDepthBFS(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return 0
elif not... | stack_v2_sparse_classes_36k_train_003941 | 1,369 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "minDepth",
"signature": "def minDepth(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "minDepthBFS",
"signature": "def minDepthBFS(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth(self, root): :type root: TreeNode :rtype: int
- def minDepthBFS(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth(self, root): :type root: TreeNode :rtype: int
- def minDepthBFS(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def minDepth(self, r... | 1c584f4ca4cda7a3fb3148801a1ff4c73befed24 | <|skeleton|>
class Solution:
def minDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def minDepthBFS(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minDepth(self, root):
""":type root: TreeNode :rtype: int"""
if not root:
return 0
elif not root.left:
return self.minDepth(root.right) + 1
elif not root.right:
return self.minDepth(root.left) + 1
else:
retur... | the_stack_v2_python_sparse | Trees/minDepth.py | kqg13/LeetCode | train | 0 | |
0d299a109e30165ee2d53e6f5d9ea4098ab3525a | [
"message = self.stringify_record(record)\nif message is None:\n return\nif isinstance(self._logger, str):\n dirn = os.path.dirname(self._logger)\n if not os.path.isdir(dirn):\n for x in range(10):\n try:\n os.makedirs(dirn)\n except EnvironmentError:\n ... | <|body_start_0|>
message = self.stringify_record(record)
if message is None:
return
if isinstance(self._logger, str):
dirn = os.path.dirname(self._logger)
if not os.path.isdir(dirn):
for x in range(10):
try:
... | !Custom LogHandler for the jlogfile. This is a custom logging Handler class for the jlogfile. It has a higher minimum log level for messages not sent to the jlogfile domain. Also, for every log message, the log file is opened, the message is written and the file is closed. This is done to mimic the postmsg command. Exc... | JLogHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JLogHandler:
"""!Custom LogHandler for the jlogfile. This is a custom logging Handler class for the jlogfile. It has a higher minimum log level for messages not sent to the jlogfile domain. Also, for every log message, the log file is opened, the message is written and the file is closed. This is... | stack_v2_sparse_classes_36k_train_003942 | 18,293 | permissive | [
{
"docstring": "!Write a log message. @param record the log record @note See the Python logging module documentation for details.",
"name": "emit",
"signature": "def emit(self, record)"
},
{
"docstring": "!Set the location of the jlogfile @param filename The path to the jlogfile.",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_016549 | Implement the Python class `JLogHandler` described below.
Class description:
!Custom LogHandler for the jlogfile. This is a custom logging Handler class for the jlogfile. It has a higher minimum log level for messages not sent to the jlogfile domain. Also, for every log message, the log file is opened, the message is ... | Implement the Python class `JLogHandler` described below.
Class description:
!Custom LogHandler for the jlogfile. This is a custom logging Handler class for the jlogfile. It has a higher minimum log level for messages not sent to the jlogfile domain. Also, for every log message, the log file is opened, the message is ... | a666ac3b58d19f04249f76c9340f2e4a4a27939b | <|skeleton|>
class JLogHandler:
"""!Custom LogHandler for the jlogfile. This is a custom logging Handler class for the jlogfile. It has a higher minimum log level for messages not sent to the jlogfile domain. Also, for every log message, the log file is opened, the message is written and the file is closed. This is... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JLogHandler:
"""!Custom LogHandler for the jlogfile. This is a custom logging Handler class for the jlogfile. It has a higher minimum log level for messages not sent to the jlogfile domain. Also, for every log message, the log file is opened, the message is written and the file is closed. This is done to mimi... | the_stack_v2_python_sparse | produtil/log.py | dtcenter/METplus | train | 41 |
87bde3935d618a9ba8e7a9fded30397f8df64bb2 | [
"self.initial_state = self.lines[0][len('initial state: '):].strip()\nself.rules = {}\nfor line in self.lines[2:]:\n lhs, rhs = line.strip().split(' => ')\n self.rules[lhs] = rhs",
"next_gen = '..'\nfor central_plant in range(2, len(gen) - 2):\n next_gen += self.rules[gen[central_plant - 2:central_plant ... | <|body_start_0|>
self.initial_state = self.lines[0][len('initial state: '):].strip()
self.rules = {}
for line in self.lines[2:]:
lhs, rhs = line.strip().split(' => ')
self.rules[lhs] = rhs
<|end_body_0|>
<|body_start_1|>
next_gen = '..'
for central_plant ... | Day 12 challenges | Challenge | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Challenge:
"""Day 12 challenges"""
def parse_input(self):
"""Parse input data"""
<|body_0|>
def update_generation(self, gen):
"""Update generation gen based on the rules"""
<|body_1|>
def challenge1(self):
"""Day 12 challenge 1"""
<|b... | stack_v2_sparse_classes_36k_train_003943 | 2,200 | permissive | [
{
"docstring": "Parse input data",
"name": "parse_input",
"signature": "def parse_input(self)"
},
{
"docstring": "Update generation gen based on the rules",
"name": "update_generation",
"signature": "def update_generation(self, gen)"
},
{
"docstring": "Day 12 challenge 1",
"n... | 4 | stack_v2_sparse_classes_30k_train_013917 | Implement the Python class `Challenge` described below.
Class description:
Day 12 challenges
Method signatures and docstrings:
- def parse_input(self): Parse input data
- def update_generation(self, gen): Update generation gen based on the rules
- def challenge1(self): Day 12 challenge 1
- def challenge2(self): Day 1... | Implement the Python class `Challenge` described below.
Class description:
Day 12 challenges
Method signatures and docstrings:
- def parse_input(self): Parse input data
- def update_generation(self, gen): Update generation gen based on the rules
- def challenge1(self): Day 12 challenge 1
- def challenge2(self): Day 1... | 6671ef8c16a837f697bb3fb91004d1bd892814ba | <|skeleton|>
class Challenge:
"""Day 12 challenges"""
def parse_input(self):
"""Parse input data"""
<|body_0|>
def update_generation(self, gen):
"""Update generation gen based on the rules"""
<|body_1|>
def challenge1(self):
"""Day 12 challenge 1"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Challenge:
"""Day 12 challenges"""
def parse_input(self):
"""Parse input data"""
self.initial_state = self.lines[0][len('initial state: '):].strip()
self.rules = {}
for line in self.lines[2:]:
lhs, rhs = line.strip().split(' => ')
self.rules[lhs] = ... | the_stack_v2_python_sparse | 2018/day12/challenge.py | ericgreveson/adventofcode | train | 0 |
2f02667ac30e668eeb111658d80a89dbe04d37af | [
"self._df_ = df_\nself._history = history\nself._future = future",
"scaler = MinMaxScaler()\nfeatures = len(self._df_.columns)\ndf_ = pd.DataFrame(scaler.fit_transform(self._df_), columns=self._df_.columns, index=self._df_.index)\nprint(type(df_))\nprint(df_.tail())\nx_train, y_train = create_features(list(df_.cl... | <|body_start_0|>
self._df_ = df_
self._history = history
self._future = future
<|end_body_0|>
<|body_start_1|>
scaler = MinMaxScaler()
features = len(self._df_.columns)
df_ = pd.DataFrame(scaler.fit_transform(self._df_), columns=self._df_.columns, index=self._df_.index)
... | Preprocess the data for models. | PreProcessing | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreProcessing:
"""Preprocess the data for models."""
def __init__(self, df_, history=50, future=50):
"""Create feature array using historical data. Args: df_: Dataframe history: Number of features per row of the array. This is equal to the number of historical entries in each row. fu... | stack_v2_sparse_classes_36k_train_003944 | 11,672 | no_license | [
{
"docstring": "Create feature array using historical data. Args: df_: Dataframe history: Number of features per row of the array. This is equal to the number of historical entries in each row. future: Number of future entries to predict. features: Number of features in Dataframe. Returns: None",
"name": "_... | 2 | stack_v2_sparse_classes_30k_train_019474 | Implement the Python class `PreProcessing` described below.
Class description:
Preprocess the data for models.
Method signatures and docstrings:
- def __init__(self, df_, history=50, future=50): Create feature array using historical data. Args: df_: Dataframe history: Number of features per row of the array. This is ... | Implement the Python class `PreProcessing` described below.
Class description:
Preprocess the data for models.
Method signatures and docstrings:
- def __init__(self, df_, history=50, future=50): Create feature array using historical data. Args: df_: Dataframe history: Number of features per row of the array. This is ... | 36a7996b140cccb9003cba8367364645e2d65d85 | <|skeleton|>
class PreProcessing:
"""Preprocess the data for models."""
def __init__(self, df_, history=50, future=50):
"""Create feature array using historical data. Args: df_: Dataframe history: Number of features per row of the array. This is equal to the number of historical entries in each row. fu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PreProcessing:
"""Preprocess the data for models."""
def __init__(self, df_, history=50, future=50):
"""Create feature array using historical data. Args: df_: Dataframe history: Number of features per row of the array. This is equal to the number of historical entries in each row. future: Number ... | the_stack_v2_python_sparse | timeseries/obya/bin/forecast-x-period.py | palisadoes/AI | train | 1 |
db4668537fba986380da85dd1ff8daa669eeb91e | [
"def identical(s, t):\n if not s and (not t):\n return True\n if not s or not t:\n return False\n if s.val == t.val and identical(s.left, t.left) and identical(s.right, t.right):\n return True\n return False\nif identical(s, t):\n return True\nreturn self.isSubtree(s.left, t) or ... | <|body_start_0|>
def identical(s, t):
if not s and (not t):
return True
if not s or not t:
return False
if s.val == t.val and identical(s.left, t.left) and identical(s.right, t.right):
return True
return False
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSubtree(self, s, t):
""":type s: TreeNode :type t: TreeNode :rtype: bool 时间复杂度: O(m*n)"""
<|body_0|>
def isSubtreeBetter(self, s, t):
""":type s: TreeNode :type t: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_003945 | 2,027 | no_license | [
{
"docstring": ":type s: TreeNode :type t: TreeNode :rtype: bool 时间复杂度: O(m*n)",
"name": "isSubtree",
"signature": "def isSubtree(self, s, t)"
},
{
"docstring": ":type s: TreeNode :type t: TreeNode :rtype: bool",
"name": "isSubtreeBetter",
"signature": "def isSubtreeBetter(self, s, t)"
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSubtree(self, s, t): :type s: TreeNode :type t: TreeNode :rtype: bool 时间复杂度: O(m*n)
- def isSubtreeBetter(self, s, t): :type s: TreeNode :type t: TreeNode :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSubtree(self, s, t): :type s: TreeNode :type t: TreeNode :rtype: bool 时间复杂度: O(m*n)
- def isSubtreeBetter(self, s, t): :type s: TreeNode :type t: TreeNode :rtype: bool
<|s... | 8853f85214ac88db024d26e228f1848dd5acd933 | <|skeleton|>
class Solution:
def isSubtree(self, s, t):
""":type s: TreeNode :type t: TreeNode :rtype: bool 时间复杂度: O(m*n)"""
<|body_0|>
def isSubtreeBetter(self, s, t):
""":type s: TreeNode :type t: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isSubtree(self, s, t):
""":type s: TreeNode :type t: TreeNode :rtype: bool 时间复杂度: O(m*n)"""
def identical(s, t):
if not s and (not t):
return True
if not s or not t:
return False
if s.val == t.val and identical(s... | the_stack_v2_python_sparse | 572-SubtreeofAnotherTree/SubtreeofAnotherTree.py | cqxmzhc/my_leetcode_solutions | train | 2 | |
de7c16c9c2cc1b9558e3e93b39c28f11bb1ea3f1 | [
"left, right = (1, len(nums) - 1)\nwhile left <= right:\n mid = (left + right) // 2\n cnt = sum((num <= mid for num in nums))\n if cnt > mid:\n right = mid - 1\n else:\n left = mid + 1\nreturn left",
"slow = nums[0]\nfast = nums[nums[0]]\nwhile slow != fast:\n slow = nums[slow]\n f... | <|body_start_0|>
left, right = (1, len(nums) - 1)
while left <= right:
mid = (left + right) // 2
cnt = sum((num <= mid for num in nums))
if cnt > mid:
right = mid - 1
else:
left = mid + 1
return left
<|end_body_0|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDuplicate(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findDuplicate2(self, nums):
"""看做有环链表 :param nums: :return: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
left, right = (1, len(nums) - 1)
... | stack_v2_sparse_classes_36k_train_003946 | 1,567 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findDuplicate",
"signature": "def findDuplicate(self, nums)"
},
{
"docstring": "看做有环链表 :param nums: :return: int",
"name": "findDuplicate2",
"signature": "def findDuplicate2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000666 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums): :type nums: List[int] :rtype: int
- def findDuplicate2(self, nums): 看做有环链表 :param nums: :return: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums): :type nums: List[int] :rtype: int
- def findDuplicate2(self, nums): 看做有环链表 :param nums: :return: int
<|skeleton|>
class Solution:
def findDup... | 215d513b3564a7a76db3d2b29e4acc341a68e8ee | <|skeleton|>
class Solution:
def findDuplicate(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findDuplicate2(self, nums):
"""看做有环链表 :param nums: :return: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findDuplicate(self, nums):
""":type nums: List[int] :rtype: int"""
left, right = (1, len(nums) - 1)
while left <= right:
mid = (left + right) // 2
cnt = sum((num <= mid for num in nums))
if cnt > mid:
right = mid - 1
... | the_stack_v2_python_sparse | python/bin-search/find-duplicate-number.py | euxuoh/leetcode | train | 0 | |
ae929564c0ee8bb868cd44fc714185f8709db7ad | [
"if not 'image' in data:\n data['image'] = 'images/no_image.png'\nreturn data",
"group = self.Meta.model(**validated_data)\ngroup.save()\nauthor = validated_data['author']\ngroup.members.add(author)\nreturn group"
] | <|body_start_0|>
if not 'image' in data:
data['image'] = 'images/no_image.png'
return data
<|end_body_0|>
<|body_start_1|>
group = self.Meta.model(**validated_data)
group.save()
author = validated_data['author']
group.members.add(author)
return group
... | GroupRegisterSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupRegisterSerializer:
def validate(self, data):
"""Checks to be sure that the received password and confirm_password fields are exactly the same"""
<|body_0|>
def create(self, validated_data):
"""Creates the user if validation succeeds"""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k_train_003947 | 6,287 | no_license | [
{
"docstring": "Checks to be sure that the received password and confirm_password fields are exactly the same",
"name": "validate",
"signature": "def validate(self, data)"
},
{
"docstring": "Creates the user if validation succeeds",
"name": "create",
"signature": "def create(self, valida... | 2 | stack_v2_sparse_classes_30k_train_011669 | Implement the Python class `GroupRegisterSerializer` described below.
Class description:
Implement the GroupRegisterSerializer class.
Method signatures and docstrings:
- def validate(self, data): Checks to be sure that the received password and confirm_password fields are exactly the same
- def create(self, validated... | Implement the Python class `GroupRegisterSerializer` described below.
Class description:
Implement the GroupRegisterSerializer class.
Method signatures and docstrings:
- def validate(self, data): Checks to be sure that the received password and confirm_password fields are exactly the same
- def create(self, validated... | db7582b75f1a3dea4468749912cccd15c9341436 | <|skeleton|>
class GroupRegisterSerializer:
def validate(self, data):
"""Checks to be sure that the received password and confirm_password fields are exactly the same"""
<|body_0|>
def create(self, validated_data):
"""Creates the user if validation succeeds"""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupRegisterSerializer:
def validate(self, data):
"""Checks to be sure that the received password and confirm_password fields are exactly the same"""
if not 'image' in data:
data['image'] = 'images/no_image.png'
return data
def create(self, validated_data):
""... | the_stack_v2_python_sparse | django_app/group/serializer/group.py | jmnghn/chming | train | 0 | |
1873215eb93d48e28e8ddeb7b48b5a66eb4ffc25 | [
"dicts = {}\nfor index, num in enumerate(nums):\n another_num = target - num\n if another_num in dicts:\n return [dicts.get(another_num), index]\n s\n dicts[num] = index",
"ls = len(nums)\nfor i in range(ls):\n for j in range(i + 1, ls):\n if nums[i] + nums[j] == target:\n ... | <|body_start_0|>
dicts = {}
for index, num in enumerate(nums):
another_num = target - num
if another_num in dicts:
return [dicts.get(another_num), index]
s
dicts[num] = index
<|end_body_0|>
<|body_start_1|>
ls = len(nums)
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, nums, target):
"""思路:用空间换时间,利用字典+内置函数enumerate来记录遍历的传递列表 记录在字典中的是{2:0, 7:1}类似的形式 利用target=num+another_num来确定另一个数是否存在, 如果存在,则返回列表下标 :param nums:List[int] :param target:int :return:List[int]"""
<|body_0|>
def twoSum_violence(self, nums, target):
... | stack_v2_sparse_classes_36k_train_003948 | 1,569 | permissive | [
{
"docstring": "思路:用空间换时间,利用字典+内置函数enumerate来记录遍历的传递列表 记录在字典中的是{2:0, 7:1}类似的形式 利用target=num+another_num来确定另一个数是否存在, 如果存在,则返回列表下标 :param nums:List[int] :param target:int :return:List[int]",
"name": "twoSum",
"signature": "def twoSum(self, nums, target)"
},
{
"docstring": "利用暴力算法来找到答案,并返回列表的下标,用到了... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target): 思路:用空间换时间,利用字典+内置函数enumerate来记录遍历的传递列表 记录在字典中的是{2:0, 7:1}类似的形式 利用target=num+another_num来确定另一个数是否存在, 如果存在,则返回列表下标 :param nums:List[int] :param targ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target): 思路:用空间换时间,利用字典+内置函数enumerate来记录遍历的传递列表 记录在字典中的是{2:0, 7:1}类似的形式 利用target=num+another_num来确定另一个数是否存在, 如果存在,则返回列表下标 :param nums:List[int] :param targ... | 8bb3400036843975cb41cbfd85ccfe603596930b | <|skeleton|>
class Solution:
def twoSum(self, nums, target):
"""思路:用空间换时间,利用字典+内置函数enumerate来记录遍历的传递列表 记录在字典中的是{2:0, 7:1}类似的形式 利用target=num+another_num来确定另一个数是否存在, 如果存在,则返回列表下标 :param nums:List[int] :param target:int :return:List[int]"""
<|body_0|>
def twoSum_violence(self, nums, target):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum(self, nums, target):
"""思路:用空间换时间,利用字典+内置函数enumerate来记录遍历的传递列表 记录在字典中的是{2:0, 7:1}类似的形式 利用target=num+another_num来确定另一个数是否存在, 如果存在,则返回列表下标 :param nums:List[int] :param target:int :return:List[int]"""
dicts = {}
for index, num in enumerate(nums):
another_n... | the_stack_v2_python_sparse | run_leetcode/001_Two_Sum.py | Valuebai/awesome-python-io | train | 11 | |
1659677e11407eea66c0f0703d0d9fefb94c8795 | [
"context = util.DotDict()\ncontext.elasticSearchHostname = ''\ncontext.elasticSearchPort = 9200\ncontext.platforms = ({'id': 'windows', 'name': 'Windows NT'}, {'id': 'linux', 'name': 'Linux'})\nreturn context",
"context = self.get_dummy_context()\nfacets = {'signatures': {'terms': [{'term': 'hang', 'count': 145},... | <|body_start_0|>
context = util.DotDict()
context.elasticSearchHostname = ''
context.elasticSearchPort = 9200
context.platforms = ({'id': 'windows', 'name': 'Windows NT'}, {'id': 'linux', 'name': 'Linux'})
return context
<|end_body_0|>
<|body_start_1|>
context = self.get... | Test Search class implemented with ElasticSearch. | TestElasticSearchSearch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestElasticSearchSearch:
"""Test Search class implemented with ElasticSearch."""
def get_dummy_context(self):
"""Create a dummy config object to use when testing."""
<|body_0|>
def test_get_signatures_list(self):
"""Test Search.get_signatures()"""
<|body_... | stack_v2_sparse_classes_36k_train_003949 | 20,362 | no_license | [
{
"docstring": "Create a dummy config object to use when testing.",
"name": "get_dummy_context",
"signature": "def get_dummy_context(self)"
},
{
"docstring": "Test Search.get_signatures()",
"name": "test_get_signatures_list",
"signature": "def test_get_signatures_list(self)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_010829 | Implement the Python class `TestElasticSearchSearch` described below.
Class description:
Test Search class implemented with ElasticSearch.
Method signatures and docstrings:
- def get_dummy_context(self): Create a dummy config object to use when testing.
- def test_get_signatures_list(self): Test Search.get_signatures... | Implement the Python class `TestElasticSearchSearch` described below.
Class description:
Test Search class implemented with ElasticSearch.
Method signatures and docstrings:
- def get_dummy_context(self): Create a dummy config object to use when testing.
- def test_get_signatures_list(self): Test Search.get_signatures... | 9c9b7701d7ddf9f3cbba1a4d0aa65758e8b49528 | <|skeleton|>
class TestElasticSearchSearch:
"""Test Search class implemented with ElasticSearch."""
def get_dummy_context(self):
"""Create a dummy config object to use when testing."""
<|body_0|>
def test_get_signatures_list(self):
"""Test Search.get_signatures()"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestElasticSearchSearch:
"""Test Search class implemented with ElasticSearch."""
def get_dummy_context(self):
"""Create a dummy config object to use when testing."""
context = util.DotDict()
context.elasticSearchHostname = ''
context.elasticSearchPort = 9200
contex... | the_stack_v2_python_sparse | socorro/unittest/external/elasticsearch/test_search.py | v1ka5/socorro | train | 0 |
fa05c2777fdeb923d1d7313f4961efc8086c499d | [
"self.unit = unit\nself.origin = origin\nself.start = start\nself.end = end\nself.cs = ClimateState(unit=unit, origin=origin, start=start, end=end)\nself._depature = None\nself._nino = None",
"a = array_check(a, 3)\nlon = array_check(lon, 1)\nlat = array_check(lat, 1)\nself.cs(a, t, axis)\nacreage = self._nino_ar... | <|body_start_0|>
self.unit = unit
self.origin = origin
self.start = start
self.end = end
self.cs = ClimateState(unit=unit, origin=origin, start=start, end=end)
self._depature = None
self._nino = None
<|end_body_0|>
<|body_start_1|>
a = array_check(a, 3)
... | Calculate nino index. | Nino | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Nino:
"""Calculate nino index."""
def __init__(self, *, unit: Optional[str]='D', origin: Optional[str]='1800-01-01 00:00:00', start: Optional[str]=None, end: Optional[str]=None) -> None:
""":param unit: str time sequence unit, default is hour. :param origin: str time sequence origin ... | stack_v2_sparse_classes_36k_train_003950 | 7,225 | no_license | [
{
"docstring": ":param unit: str time sequence unit, default is hour. :param origin: str time sequence origin :param start: str time range start :param end: str time range end",
"name": "__init__",
"signature": "def __init__(self, *, unit: Optional[str]='D', origin: Optional[str]='1800-01-01 00:00:00', ... | 6 | stack_v2_sparse_classes_30k_train_013279 | Implement the Python class `Nino` described below.
Class description:
Calculate nino index.
Method signatures and docstrings:
- def __init__(self, *, unit: Optional[str]='D', origin: Optional[str]='1800-01-01 00:00:00', start: Optional[str]=None, end: Optional[str]=None) -> None: :param unit: str time sequence unit, ... | Implement the Python class `Nino` described below.
Class description:
Calculate nino index.
Method signatures and docstrings:
- def __init__(self, *, unit: Optional[str]='D', origin: Optional[str]='1800-01-01 00:00:00', start: Optional[str]=None, end: Optional[str]=None) -> None: :param unit: str time sequence unit, ... | 1c8d5fbf3676dc81e9f143e93ee2564359519b11 | <|skeleton|>
class Nino:
"""Calculate nino index."""
def __init__(self, *, unit: Optional[str]='D', origin: Optional[str]='1800-01-01 00:00:00', start: Optional[str]=None, end: Optional[str]=None) -> None:
""":param unit: str time sequence unit, default is hour. :param origin: str time sequence origin ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Nino:
"""Calculate nino index."""
def __init__(self, *, unit: Optional[str]='D', origin: Optional[str]='1800-01-01 00:00:00', start: Optional[str]=None, end: Optional[str]=None) -> None:
""":param unit: str time sequence unit, default is hour. :param origin: str time sequence origin :param start:... | the_stack_v2_python_sparse | statistics/average.py | qliu0/PythonInAirSeaScience | train | 0 |
3ea83523a12430699362eb30ec88df8fe7caa889 | [
"try:\n super().perform_authentication(request)\nexcept Exception as e:\n print('perform_authentication', e)",
"s = CartSerializer(data=request.data)\ns.is_valid(raise_exception=True)\nsku_id = s.validated_data.get('sku_id')\ncount = s.validated_data.get('count')\nselected = s.validated_data.get('selected')... | <|body_start_0|>
try:
super().perform_authentication(request)
except Exception as e:
print('perform_authentication', e)
<|end_body_0|>
<|body_start_1|>
s = CartSerializer(data=request.data)
s.is_valid(raise_exception=True)
sku_id = s.validated_data.get('s... | CartView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CartView:
def perform_authentication(self, request):
"""drf框架在视图执行前会调用此方法进行身份认证(jwt认证) 如果认证不通过,则会抛异常返回401状态码 问题: 抛异常会导致视图无法执行 解决: 捕获异常即可"""
<|body_0|>
def post(self, request):
"""添加商品到购物车"""
<|body_1|>
def get(self, request):
"""查询购物车中的商品"""
... | stack_v2_sparse_classes_36k_train_003951 | 12,969 | no_license | [
{
"docstring": "drf框架在视图执行前会调用此方法进行身份认证(jwt认证) 如果认证不通过,则会抛异常返回401状态码 问题: 抛异常会导致视图无法执行 解决: 捕获异常即可",
"name": "perform_authentication",
"signature": "def perform_authentication(self, request)"
},
{
"docstring": "添加商品到购物车",
"name": "post",
"signature": "def post(self, request)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_020928 | Implement the Python class `CartView` described below.
Class description:
Implement the CartView class.
Method signatures and docstrings:
- def perform_authentication(self, request): drf框架在视图执行前会调用此方法进行身份认证(jwt认证) 如果认证不通过,则会抛异常返回401状态码 问题: 抛异常会导致视图无法执行 解决: 捕获异常即可
- def post(self, request): 添加商品到购物车
- def get(self, re... | Implement the Python class `CartView` described below.
Class description:
Implement the CartView class.
Method signatures and docstrings:
- def perform_authentication(self, request): drf框架在视图执行前会调用此方法进行身份认证(jwt认证) 如果认证不通过,则会抛异常返回401状态码 问题: 抛异常会导致视图无法执行 解决: 捕获异常即可
- def post(self, request): 添加商品到购物车
- def get(self, re... | 12b52f21a4ec20b4853870468c28d2385dc185a8 | <|skeleton|>
class CartView:
def perform_authentication(self, request):
"""drf框架在视图执行前会调用此方法进行身份认证(jwt认证) 如果认证不通过,则会抛异常返回401状态码 问题: 抛异常会导致视图无法执行 解决: 捕获异常即可"""
<|body_0|>
def post(self, request):
"""添加商品到购物车"""
<|body_1|>
def get(self, request):
"""查询购物车中的商品"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CartView:
def perform_authentication(self, request):
"""drf框架在视图执行前会调用此方法进行身份认证(jwt认证) 如果认证不通过,则会抛异常返回401状态码 问题: 抛异常会导致视图无法执行 解决: 捕获异常即可"""
try:
super().perform_authentication(request)
except Exception as e:
print('perform_authentication', e)
def post(self,... | the_stack_v2_python_sparse | django_prj/meiduo/meiduo_mall/meiduo_mall/apps/carts/views.py | 123wuyu/demo_prj | train | 1 | |
6fdbd4f2ac1a5749953d0d38515d4b7fdf53b04b | [
"super().__init__(n_head, n_feat, dropout_rate)\nself.zero_triu = zero_triu\nself.linear_pos = nn.Linear(n_feat, n_feat, bias_attr=False)\nself.pos_bias_u = paddle.create_parameter(shape=(self.h, self.d_k), dtype='float32', default_initializer=paddle.nn.initializer.XavierUniform())\nself.pos_bias_v = paddle.create_... | <|body_start_0|>
super().__init__(n_head, n_feat, dropout_rate)
self.zero_triu = zero_triu
self.linear_pos = nn.Linear(n_feat, n_feat, bias_attr=False)
self.pos_bias_u = paddle.create_parameter(shape=(self.h, self.d_k), dtype='float32', default_initializer=paddle.nn.initializer.XavierUni... | Multi-Head Attention layer with relative position encoding (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): The number of heads. n_feat (int): The number of features. dropout_rate (float): Dropout rate. zero_triu (bool)... | RelPositionMultiHeadedAttention | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelPositionMultiHeadedAttention:
"""Multi-Head Attention layer with relative position encoding (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): The number of heads. n_feat (int): The number of fea... | stack_v2_sparse_classes_36k_train_003952 | 13,512 | permissive | [
{
"docstring": "Construct an RelPositionMultiHeadedAttention object.",
"name": "__init__",
"signature": "def __init__(self, n_head, n_feat, dropout_rate, zero_triu=False)"
},
{
"docstring": "Compute relative positional encoding. Args: x(Tensor): Input tensor (batch, head, time1, 2*time1-1). Retu... | 3 | null | Implement the Python class `RelPositionMultiHeadedAttention` described below.
Class description:
Multi-Head Attention layer with relative position encoding (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): The number of... | Implement the Python class `RelPositionMultiHeadedAttention` described below.
Class description:
Multi-Head Attention layer with relative position encoding (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): The number of... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class RelPositionMultiHeadedAttention:
"""Multi-Head Attention layer with relative position encoding (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): The number of heads. n_feat (int): The number of fea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RelPositionMultiHeadedAttention:
"""Multi-Head Attention layer with relative position encoding (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): The number of heads. n_feat (int): The number of features. dropou... | the_stack_v2_python_sparse | paddlespeech/t2s/modules/transformer/attention.py | anniyanvr/DeepSpeech-1 | train | 0 |
d764cb7bd2c69d7ee18c303fd60e86d5d5b505af | [
"super().__init__(**kwargs)\nself.blocks = [getattr(tf.keras.layers, nonlinear_activation)(**nonlinear_activation_params), TFReflectionPad1d((kernel_size - 1) // 2 * dilation_rate), tf.keras.layers.Conv1D(filters=filters, kernel_size=kernel_size, dilation_rate=dilation_rate, use_bias=use_bias, kernel_initializer=ge... | <|body_start_0|>
super().__init__(**kwargs)
self.blocks = [getattr(tf.keras.layers, nonlinear_activation)(**nonlinear_activation_params), TFReflectionPad1d((kernel_size - 1) // 2 * dilation_rate), tf.keras.layers.Conv1D(filters=filters, kernel_size=kernel_size, dilation_rate=dilation_rate, use_bias=use_... | Tensorflow ResidualStack module. | TFResidualStack | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TFResidualStack:
"""Tensorflow ResidualStack module."""
def __init__(self, kernel_size, filters, dilation_rate, use_bias, nonlinear_activation, nonlinear_activation_params, is_weight_norm, initializer_seed, **kwargs):
"""Initialize TFResidualStack module. Args: kernel_size (int): Ker... | stack_v2_sparse_classes_36k_train_003953 | 17,807 | permissive | [
{
"docstring": "Initialize TFResidualStack module. Args: kernel_size (int): Kernel size. filters (int): Number of filters. dilation_rate (int): Dilation rate. use_bias (bool): Whether to add bias parameter in convolution layers. nonlinear_activation (str): Activation function module name. nonlinear_activation_p... | 3 | stack_v2_sparse_classes_30k_train_019471 | Implement the Python class `TFResidualStack` described below.
Class description:
Tensorflow ResidualStack module.
Method signatures and docstrings:
- def __init__(self, kernel_size, filters, dilation_rate, use_bias, nonlinear_activation, nonlinear_activation_params, is_weight_norm, initializer_seed, **kwargs): Initia... | Implement the Python class `TFResidualStack` described below.
Class description:
Tensorflow ResidualStack module.
Method signatures and docstrings:
- def __init__(self, kernel_size, filters, dilation_rate, use_bias, nonlinear_activation, nonlinear_activation_params, is_weight_norm, initializer_seed, **kwargs): Initia... | 136877136355c82d7ba474ceb7a8f133bd84767e | <|skeleton|>
class TFResidualStack:
"""Tensorflow ResidualStack module."""
def __init__(self, kernel_size, filters, dilation_rate, use_bias, nonlinear_activation, nonlinear_activation_params, is_weight_norm, initializer_seed, **kwargs):
"""Initialize TFResidualStack module. Args: kernel_size (int): Ker... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TFResidualStack:
"""Tensorflow ResidualStack module."""
def __init__(self, kernel_size, filters, dilation_rate, use_bias, nonlinear_activation, nonlinear_activation_params, is_weight_norm, initializer_seed, **kwargs):
"""Initialize TFResidualStack module. Args: kernel_size (int): Kernel size. fil... | the_stack_v2_python_sparse | tensorflow_tts/models/melgan.py | TensorSpeech/TensorFlowTTS | train | 2,889 |
197198dd8852d5422b32fdb39f49d1c3d298eb70 | [
"super(ImageNetFeatureExtractor, self).__init__()\nself.out_layers = out_layers\nself.model_name = model_name\nself.model = MODELS_BY_NAME[model_name](pretrained=True)\nfor layer in out_layers:\n self.layer_by_name(layer).register_forward_hook(self.make_hook(layer))\nself.flatten = nn.Flatten()\nself.features_by... | <|body_start_0|>
super(ImageNetFeatureExtractor, self).__init__()
self.out_layers = out_layers
self.model_name = model_name
self.model = MODELS_BY_NAME[model_name](pretrained=True)
for layer in out_layers:
self.layer_by_name(layer).register_forward_hook(self.make_hook... | Extracts high-level image features using a network trained on ImageNet. You specify a model or model name, as well as output layer names when you initialize this. When you run `forward()` on the input data, it will store the features after each named output layer, and finally concatenate them all and return the result.... | ImageNetFeatureExtractor | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageNetFeatureExtractor:
"""Extracts high-level image features using a network trained on ImageNet. You specify a model or model name, as well as output layer names when you initialize this. When you run `forward()` on the input data, it will store the features after each named output layer, and... | stack_v2_sparse_classes_36k_train_003954 | 28,824 | permissive | [
{
"docstring": "Initialize this extractor with given list of `out_layers`. You must pass in a `model_name` (one of ['vgg16'] for now). You can optionally pass in a `projection_length`. If given, the final output (after concatenating all output layers) will be projected down to given length. This is most useful ... | 4 | stack_v2_sparse_classes_30k_train_016095 | Implement the Python class `ImageNetFeatureExtractor` described below.
Class description:
Extracts high-level image features using a network trained on ImageNet. You specify a model or model name, as well as output layer names when you initialize this. When you run `forward()` on the input data, it will store the feat... | Implement the Python class `ImageNetFeatureExtractor` described below.
Class description:
Extracts high-level image features using a network trained on ImageNet. You specify a model or model name, as well as output layer names when you initialize this. When you run `forward()` on the input data, it will store the feat... | 871312196587e21be06d65b5b085e4419cbc4cb0 | <|skeleton|>
class ImageNetFeatureExtractor:
"""Extracts high-level image features using a network trained on ImageNet. You specify a model or model name, as well as output layer names when you initialize this. When you run `forward()` on the input data, it will store the features after each named output layer, and... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageNetFeatureExtractor:
"""Extracts high-level image features using a network trained on ImageNet. You specify a model or model name, as well as output layer names when you initialize this. When you run `forward()` on the input data, it will store the features after each named output layer, and finally conc... | the_stack_v2_python_sparse | ml/image_features.py | neeraj-kumar/nkpylib | train | 0 |
2db7ed8951cad880e828dbb04b7ad6d53582d307 | [
"super(Head, self).__init__()\nself.action_dim = squeeze(action_dim)\nself.dueling = dueling\nhead_fn = partial(DuelingHead, a_layer_num=a_layer_num, v_layer_num=v_layer_num) if dueling else nn.Linear\nif isinstance(self.action_dim, tuple):\n self.pred = nn.ModuleList()\n for dim in self.action_dim:\n ... | <|body_start_0|>
super(Head, self).__init__()
self.action_dim = squeeze(action_dim)
self.dueling = dueling
head_fn = partial(DuelingHead, a_layer_num=a_layer_num, v_layer_num=v_layer_num) if dueling else nn.Linear
if isinstance(self.action_dim, tuple):
self.pred = nn.... | Overview: The Head used in DQN models. Receive encoded embedding tensor and use it to predict the action. Interfaces: __init__, forward | Head | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Head:
"""Overview: The Head used in DQN models. Receive encoded embedding tensor and use it to predict the action. Interfaces: __init__, forward"""
def __init__(self, action_dim: tuple, input_dim: int, dueling: bool=True, a_layer_num: int=1, v_layer_num: int=1) -> None:
"""Overview: ... | stack_v2_sparse_classes_36k_train_003955 | 9,851 | permissive | [
{
"docstring": "Overview: Init the Head according to arguments. Arguments: - action_dim (:obj:`tuple`): the num of action dim, \\\\ note that it can be a tuple containing more than one element - input_dim (:obj:`int`): input tensor dim of the head - dueling (:obj:`bool`): whether to use ``DuelingHead`` or ``nn.... | 2 | stack_v2_sparse_classes_30k_train_011773 | Implement the Python class `Head` described below.
Class description:
Overview: The Head used in DQN models. Receive encoded embedding tensor and use it to predict the action. Interfaces: __init__, forward
Method signatures and docstrings:
- def __init__(self, action_dim: tuple, input_dim: int, dueling: bool=True, a_... | Implement the Python class `Head` described below.
Class description:
Overview: The Head used in DQN models. Receive encoded embedding tensor and use it to predict the action. Interfaces: __init__, forward
Method signatures and docstrings:
- def __init__(self, action_dim: tuple, input_dim: int, dueling: bool=True, a_... | 09d507c412235a2f0cf9c0b3485ec9ed15fb6421 | <|skeleton|>
class Head:
"""Overview: The Head used in DQN models. Receive encoded embedding tensor and use it to predict the action. Interfaces: __init__, forward"""
def __init__(self, action_dim: tuple, input_dim: int, dueling: bool=True, a_layer_num: int=1, v_layer_num: int=1) -> None:
"""Overview: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Head:
"""Overview: The Head used in DQN models. Receive encoded embedding tensor and use it to predict the action. Interfaces: __init__, forward"""
def __init__(self, action_dim: tuple, input_dim: int, dueling: bool=True, a_layer_num: int=1, v_layer_num: int=1) -> None:
"""Overview: Init the Head... | the_stack_v2_python_sparse | ctools/model/dqn/dqn_network.py | LFhase/DI-star | train | 1 |
83eb5f987ff41eee337798b600a36d0725da34a2 | [
"try:\n to_create = []\n for item in payload:\n method = Method(name=item)\n to_create.append(method)\n db.session.bulk_save_objects(to_create)\n db.session.commit()\nexcept HandlerException as ex:\n print(ex.message)\nexcept Exception as ex:\n print(ex, 'error')",
"try:\n db.se... | <|body_start_0|>
try:
to_create = []
for item in payload:
method = Method(name=item)
to_create.append(method)
db.session.bulk_save_objects(to_create)
db.session.commit()
except HandlerException as ex:
print(ex.me... | MethodSeed | MethodSeed | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MethodSeed:
"""MethodSeed"""
def up(self):
"""up"""
<|body_0|>
def down(self):
"""down"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
to_create = []
for item in payload:
method = Method(name=item)
... | stack_v2_sparse_classes_36k_train_003956 | 1,047 | no_license | [
{
"docstring": "up",
"name": "up",
"signature": "def up(self)"
},
{
"docstring": "down",
"name": "down",
"signature": "def down(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009548 | Implement the Python class `MethodSeed` described below.
Class description:
MethodSeed
Method signatures and docstrings:
- def up(self): up
- def down(self): down | Implement the Python class `MethodSeed` described below.
Class description:
MethodSeed
Method signatures and docstrings:
- def up(self): up
- def down(self): down
<|skeleton|>
class MethodSeed:
"""MethodSeed"""
def up(self):
"""up"""
<|body_0|>
def down(self):
"""down"""
... | 828cb0109415b293a38f5c8ea6c11ce4a469a8ea | <|skeleton|>
class MethodSeed:
"""MethodSeed"""
def up(self):
"""up"""
<|body_0|>
def down(self):
"""down"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MethodSeed:
"""MethodSeed"""
def up(self):
"""up"""
try:
to_create = []
for item in payload:
method = Method(name=item)
to_create.append(method)
db.session.bulk_save_objects(to_create)
db.session.commit()
... | the_stack_v2_python_sparse | src/seeds/method.py | andresbermeoq/server | train | 0 |
0bacf5f51e1c1224f50731b39f1675c9f698119f | [
"if shape is None:\n shape = self._get_frame_shape(world, sides=sides)\nif not 'position' in kwargs:\n kwargs['position'] = (0, 0)\nsuper(FrameObject, self).__init__(world, shape=shape, **kwargs)",
"if sides is None:\n sides = ['top', 'right', 'bottom', 'left']\nshape = []\nif 'top' in sides:\n shape ... | <|body_start_0|>
if shape is None:
shape = self._get_frame_shape(world, sides=sides)
if not 'position' in kwargs:
kwargs['position'] = (0, 0)
super(FrameObject, self).__init__(world, shape=shape, **kwargs)
<|end_body_0|>
<|body_start_1|>
if sides is None:
... | a frame that surrounds the visible portion of the world. can be used to contain Objects within the visible world. | FrameObject | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FrameObject:
"""a frame that surrounds the visible portion of the world. can be used to contain Objects within the visible world."""
def __init__(self, world, sides=None, shape=None, **kwargs):
"""Parameters ---------- world : PixelWorld the host world sides : list the list of sides ... | stack_v2_sparse_classes_36k_train_003957 | 19,812 | permissive | [
{
"docstring": "Parameters ---------- world : PixelWorld the host world sides : list the list of sides ('top', 'right', 'bottom', and/or 'left') to include in the frame shape : string | array_like, optional see ShapeObject (overrides sides) **kwargs extra keyword arguments (see ShapeObject, CompoundObject)",
... | 2 | stack_v2_sparse_classes_30k_train_006012 | Implement the Python class `FrameObject` described below.
Class description:
a frame that surrounds the visible portion of the world. can be used to contain Objects within the visible world.
Method signatures and docstrings:
- def __init__(self, world, sides=None, shape=None, **kwargs): Parameters ---------- world : ... | Implement the Python class `FrameObject` described below.
Class description:
a frame that surrounds the visible portion of the world. can be used to contain Objects within the visible world.
Method signatures and docstrings:
- def __init__(self, world, sides=None, shape=None, **kwargs): Parameters ---------- world : ... | 4a287e820fbb62bfc2b3b3d08df282329df4c2b1 | <|skeleton|>
class FrameObject:
"""a frame that surrounds the visible portion of the world. can be used to contain Objects within the visible world."""
def __init__(self, world, sides=None, shape=None, **kwargs):
"""Parameters ---------- world : PixelWorld the host world sides : list the list of sides ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FrameObject:
"""a frame that surrounds the visible portion of the world. can be used to contain Objects within the visible world."""
def __init__(self, world, sides=None, shape=None, **kwargs):
"""Parameters ---------- world : PixelWorld the host world sides : list the list of sides ('top', 'righ... | the_stack_v2_python_sparse | pixelworld/envs/pixelworld/objects.py | fenfeibani/pixelworld | train | 0 |
9fd2b9ea246e21ad82b1ab8f862e3c85a908ac1c | [
"self._column_value_counts_metric_single_batch_parameter_builder_config = ParameterBuilderConfig(module_name='great_expectations.rule_based_profiler.parameter_builder', class_name='MetricSingleBatchParameterBuilder', name='column_value_counts_metric_single_batch_parameter_builder', metric_name='column.value_counts'... | <|body_start_0|>
self._column_value_counts_metric_single_batch_parameter_builder_config = ParameterBuilderConfig(module_name='great_expectations.rule_based_profiler.parameter_builder', class_name='MetricSingleBatchParameterBuilder', name='column_value_counts_metric_single_batch_parameter_builder', metric_name='... | Compute value counts using specified metric for one Batch of data. | ValueCountsSingleBatchParameterBuilder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValueCountsSingleBatchParameterBuilder:
"""Compute value counts using specified metric for one Batch of data."""
def __init__(self, name: str, evaluation_parameter_builder_configs: Optional[List[ParameterBuilderConfig]]=None, data_context: Optional[AbstractDataContext]=None) -> None:
... | stack_v2_sparse_classes_36k_train_003958 | 7,890 | permissive | [
{
"docstring": "Args: name: the name of this parameter -- this is user-specified parameter name (from configuration); it is not the fully-qualified parameter name; a fully-qualified parameter name must start with \"$parameter.\" and may contain one or more subsequent parts (e.g., \"$parameter.<my_param_from_con... | 2 | null | Implement the Python class `ValueCountsSingleBatchParameterBuilder` described below.
Class description:
Compute value counts using specified metric for one Batch of data.
Method signatures and docstrings:
- def __init__(self, name: str, evaluation_parameter_builder_configs: Optional[List[ParameterBuilderConfig]]=None... | Implement the Python class `ValueCountsSingleBatchParameterBuilder` described below.
Class description:
Compute value counts using specified metric for one Batch of data.
Method signatures and docstrings:
- def __init__(self, name: str, evaluation_parameter_builder_configs: Optional[List[ParameterBuilderConfig]]=None... | b0290e2fd2aa05aec6d7d8871b91cb4478e9501d | <|skeleton|>
class ValueCountsSingleBatchParameterBuilder:
"""Compute value counts using specified metric for one Batch of data."""
def __init__(self, name: str, evaluation_parameter_builder_configs: Optional[List[ParameterBuilderConfig]]=None, data_context: Optional[AbstractDataContext]=None) -> None:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValueCountsSingleBatchParameterBuilder:
"""Compute value counts using specified metric for one Batch of data."""
def __init__(self, name: str, evaluation_parameter_builder_configs: Optional[List[ParameterBuilderConfig]]=None, data_context: Optional[AbstractDataContext]=None) -> None:
"""Args: nam... | the_stack_v2_python_sparse | great_expectations/rule_based_profiler/parameter_builder/value_counts_single_batch_parameter_builder.py | great-expectations/great_expectations | train | 8,931 |
6d7a2eb11cf2f14d3092f0d9a0d0d4afd66740c3 | [
"super().__init__()\nself.level1 = CBR(3, 16, 3, 2)\nself.sample1 = InputProjectionA(1)\nself.sample2 = InputProjectionA(2)\nself.b1 = BR(16 + 3)\nself.level2_0 = DownSamplerB(16 + 3, 64)\nself.level2 = nn.ModuleList()\nfor i in range(0, p):\n self.level2.append(DilatedParllelResidualBlockB(64, 64))\nself.b2 = B... | <|body_start_0|>
super().__init__()
self.level1 = CBR(3, 16, 3, 2)
self.sample1 = InputProjectionA(1)
self.sample2 = InputProjectionA(2)
self.b1 = BR(16 + 3)
self.level2_0 = DownSamplerB(16 + 3, 64)
self.level2 = nn.ModuleList()
for i in range(0, p):
... | This class defines the ESPNet-C network in the paper | ESPNet_Encoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ESPNet_Encoder:
"""This class defines the ESPNet-C network in the paper"""
def __init__(self, num_classes=19, p=5, q=3):
""":param num_classes: number of classes in the dataset. Default is 20 for the cityscapes :param p: depth multiplier :param q: depth multiplier"""
<|body_0... | stack_v2_sparse_classes_36k_train_003959 | 15,567 | permissive | [
{
"docstring": ":param num_classes: number of classes in the dataset. Default is 20 for the cityscapes :param p: depth multiplier :param q: depth multiplier",
"name": "__init__",
"signature": "def __init__(self, num_classes=19, p=5, q=3)"
},
{
"docstring": ":param input: Receives the input RGB i... | 2 | null | Implement the Python class `ESPNet_Encoder` described below.
Class description:
This class defines the ESPNet-C network in the paper
Method signatures and docstrings:
- def __init__(self, num_classes=19, p=5, q=3): :param num_classes: number of classes in the dataset. Default is 20 for the cityscapes :param p: depth ... | Implement the Python class `ESPNet_Encoder` described below.
Class description:
This class defines the ESPNet-C network in the paper
Method signatures and docstrings:
- def __init__(self, num_classes=19, p=5, q=3): :param num_classes: number of classes in the dataset. Default is 20 for the cityscapes :param p: depth ... | f2993d3ce73a2f7ddba05da3891defb08547d504 | <|skeleton|>
class ESPNet_Encoder:
"""This class defines the ESPNet-C network in the paper"""
def __init__(self, num_classes=19, p=5, q=3):
""":param num_classes: number of classes in the dataset. Default is 20 for the cityscapes :param p: depth multiplier :param q: depth multiplier"""
<|body_0... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ESPNet_Encoder:
"""This class defines the ESPNet-C network in the paper"""
def __init__(self, num_classes=19, p=5, q=3):
""":param num_classes: number of classes in the dataset. Default is 20 for the cityscapes :param p: depth multiplier :param q: depth multiplier"""
super().__init__()
... | the_stack_v2_python_sparse | pytorch/pytorchcv/models/others/oth_espnet.py | osmr/imgclsmob | train | 3,017 |
ce19eec972183543148b9ab60222eb0a5357d071 | [
"if Question.objects.filter(pk=kwargs['pk']).exists():\n qu = Question.objects.get(pk=kwargs['pk'])\n if qu.user != self.request.user:\n return HttpResponseForbidden('Access Denied')\nelse:\n return HttpResponseForbidden('Access Denied')\nreturn super(EditQuestionView, self).get(*args, **kwargs)",
... | <|body_start_0|>
if Question.objects.filter(pk=kwargs['pk']).exists():
qu = Question.objects.get(pk=kwargs['pk'])
if qu.user != self.request.user:
return HttpResponseForbidden('Access Denied')
else:
return HttpResponseForbidden('Access Denied')
... | Edit Question View | EditQuestionView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditQuestionView:
"""Edit Question View"""
def get(self, *args, **kwargs):
"""user can't edit the other users question"""
<|body_0|>
def form_valid(self, form):
"""Edit the update date of question"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_003960 | 7,882 | no_license | [
{
"docstring": "user can't edit the other users question",
"name": "get",
"signature": "def get(self, *args, **kwargs)"
},
{
"docstring": "Edit the update date of question",
"name": "form_valid",
"signature": "def form_valid(self, form)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021078 | Implement the Python class `EditQuestionView` described below.
Class description:
Edit Question View
Method signatures and docstrings:
- def get(self, *args, **kwargs): user can't edit the other users question
- def form_valid(self, form): Edit the update date of question | Implement the Python class `EditQuestionView` described below.
Class description:
Edit Question View
Method signatures and docstrings:
- def get(self, *args, **kwargs): user can't edit the other users question
- def form_valid(self, form): Edit the update date of question
<|skeleton|>
class EditQuestionView:
"""... | d89a811c5c928921a6ffac9120fd1d8d14dd4ac6 | <|skeleton|>
class EditQuestionView:
"""Edit Question View"""
def get(self, *args, **kwargs):
"""user can't edit the other users question"""
<|body_0|>
def form_valid(self, form):
"""Edit the update date of question"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EditQuestionView:
"""Edit Question View"""
def get(self, *args, **kwargs):
"""user can't edit the other users question"""
if Question.objects.filter(pk=kwargs['pk']).exists():
qu = Question.objects.get(pk=kwargs['pk'])
if qu.user != self.request.user:
... | the_stack_v2_python_sparse | forum/views.py | suman1oct/stack_overflow | train | 0 |
18320e36a221f653d52092fe585cdb1ca6cb8eee | [
"try:\n from mosestokenizer import MosesPunctuationNormalizer, MosesTokenizer\nexcept ImportError:\n raise ImportError('Please install sacremoses')\nself.lang = lang\nself.punct_normalizer = MosesPunctuationNormalizer(lang=lang)\nself.tokenizer = MosesTokenizer(lang=lang)\nif self.lang == 'zh':\n import op... | <|body_start_0|>
try:
from mosestokenizer import MosesPunctuationNormalizer, MosesTokenizer
except ImportError:
raise ImportError('Please install sacremoses')
self.lang = lang
self.punct_normalizer = MosesPunctuationNormalizer(lang=lang)
self.tokenizer = M... | Tokenizer | [
"MIT",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tokenizer:
def __init__(self, lang: str='en'):
"""Create a tokenizer instance for a specific language. Take note that a caveat is that this tokenizer is not picklable. Does the following in sequence 1. Punct normalize 2. Lang specific moses tokenize 3. Lang specific addtional segmentatio... | stack_v2_sparse_classes_36k_train_003961 | 9,564 | permissive | [
{
"docstring": "Create a tokenizer instance for a specific language. Take note that a caveat is that this tokenizer is not picklable. Does the following in sequence 1. Punct normalize 2. Lang specific moses tokenize 3. Lang specific addtional segmentation Keyword Arguments: lang {str} -- Language identifier (de... | 2 | stack_v2_sparse_classes_30k_train_020329 | Implement the Python class `Tokenizer` described below.
Class description:
Implement the Tokenizer class.
Method signatures and docstrings:
- def __init__(self, lang: str='en'): Create a tokenizer instance for a specific language. Take note that a caveat is that this tokenizer is not picklable. Does the following in ... | Implement the Python class `Tokenizer` described below.
Class description:
Implement the Tokenizer class.
Method signatures and docstrings:
- def __init__(self, lang: str='en'): Create a tokenizer instance for a specific language. Take note that a caveat is that this tokenizer is not picklable. Does the following in ... | 9f06ec825d7a8aadf46f1f1c96dae2537b101b17 | <|skeleton|>
class Tokenizer:
def __init__(self, lang: str='en'):
"""Create a tokenizer instance for a specific language. Take note that a caveat is that this tokenizer is not picklable. Does the following in sequence 1. Punct normalize 2. Lang specific moses tokenize 3. Lang specific addtional segmentatio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Tokenizer:
def __init__(self, lang: str='en'):
"""Create a tokenizer instance for a specific language. Take note that a caveat is that this tokenizer is not picklable. Does the following in sequence 1. Punct normalize 2. Lang specific moses tokenize 3. Lang specific addtional segmentation Keyword Argu... | the_stack_v2_python_sparse | laser/data.py | mingruimingrui/laser-keep-alive | train | 2 | |
c91a9e9e1ece6294aa2bf693064ce84a764533d6 | [
"self.input_name = input_name\nself.binary_input = binary_input\nreturn None",
"input_io = BytesIO(self.binary_input)\noutput_string = StringIO()\nwith input_io as in_file:\n parser = PDFParser(in_file)\n doc = PDFDocument(parser)\n rsrcmgr = PDFResourceManager()\n device = TextConverter(rsrcmgr, outp... | <|body_start_0|>
self.input_name = input_name
self.binary_input = binary_input
return None
<|end_body_0|>
<|body_start_1|>
input_io = BytesIO(self.binary_input)
output_string = StringIO()
with input_io as in_file:
parser = PDFParser(in_file)
doc =... | Class to handle PDF files | PDFtoText | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"CC-BY-4.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PDFtoText:
"""Class to handle PDF files"""
def __init__(self, input_name, binary_input):
"""Set save input file name"""
<|body_0|>
def convert_to_text(self):
"""Set save input file name"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.input_... | stack_v2_sparse_classes_36k_train_003962 | 3,168 | permissive | [
{
"docstring": "Set save input file name",
"name": "__init__",
"signature": "def __init__(self, input_name, binary_input)"
},
{
"docstring": "Set save input file name",
"name": "convert_to_text",
"signature": "def convert_to_text(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001118 | Implement the Python class `PDFtoText` described below.
Class description:
Class to handle PDF files
Method signatures and docstrings:
- def __init__(self, input_name, binary_input): Set save input file name
- def convert_to_text(self): Set save input file name | Implement the Python class `PDFtoText` described below.
Class description:
Class to handle PDF files
Method signatures and docstrings:
- def __init__(self, input_name, binary_input): Set save input file name
- def convert_to_text(self): Set save input file name
<|skeleton|>
class PDFtoText:
"""Class to handle PD... | 0c49ee0f10da97ed52121d0d2eb9ee200803af5d | <|skeleton|>
class PDFtoText:
"""Class to handle PDF files"""
def __init__(self, input_name, binary_input):
"""Set save input file name"""
<|body_0|>
def convert_to_text(self):
"""Set save input file name"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PDFtoText:
"""Class to handle PDF files"""
def __init__(self, input_name, binary_input):
"""Set save input file name"""
self.input_name = input_name
self.binary_input = binary_input
return None
def convert_to_text(self):
"""Set save input file name"""
... | the_stack_v2_python_sparse | cfc_app/pdf_to_text.py | AmericanAirlines/Legit-Info | train | 1 |
a81f2b42ddac44d444ea2047f7a5d21a97d79602 | [
"self.startMessage = startMessage\nself.message = message\nself.doneMessage = doneMessage",
"self.removePreviousTrap(target)\ntarget.secondaryEffects.append(Trap(user, self.message, self.doneMessage))\nreturn [target.getHeader() + self.startMessage]",
"effect = self.hasThisTrap(pkmn)\nif effect:\n pkmn.secon... | <|body_start_0|>
self.startMessage = startMessage
self.message = message
self.doneMessage = doneMessage
<|end_body_0|>
<|body_start_1|>
self.removePreviousTrap(target)
target.secondaryEffects.append(Trap(user, self.message, self.doneMessage))
return [target.getHeader() +... | Represents an effect that traps the opponent | TrapDelegate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrapDelegate:
"""Represents an effect that traps the opponent"""
def __init__(self, startMessage, message, doneMessage):
"""Build the Trap Delegate"""
<|body_0|>
def applyEffect(self, user, target, environment):
"""Apply the trap to the opponent"""
<|body... | stack_v2_sparse_classes_36k_train_003963 | 1,226 | no_license | [
{
"docstring": "Build the Trap Delegate",
"name": "__init__",
"signature": "def __init__(self, startMessage, message, doneMessage)"
},
{
"docstring": "Apply the trap to the opponent",
"name": "applyEffect",
"signature": "def applyEffect(self, user, target, environment)"
},
{
"doc... | 4 | stack_v2_sparse_classes_30k_train_010512 | Implement the Python class `TrapDelegate` described below.
Class description:
Represents an effect that traps the opponent
Method signatures and docstrings:
- def __init__(self, startMessage, message, doneMessage): Build the Trap Delegate
- def applyEffect(self, user, target, environment): Apply the trap to the oppon... | Implement the Python class `TrapDelegate` described below.
Class description:
Represents an effect that traps the opponent
Method signatures and docstrings:
- def __init__(self, startMessage, message, doneMessage): Build the Trap Delegate
- def applyEffect(self, user, target, environment): Apply the trap to the oppon... | 3931eee5fd04e18bb1738a0b27a4c6979dc4db01 | <|skeleton|>
class TrapDelegate:
"""Represents an effect that traps the opponent"""
def __init__(self, startMessage, message, doneMessage):
"""Build the Trap Delegate"""
<|body_0|>
def applyEffect(self, user, target, environment):
"""Apply the trap to the opponent"""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TrapDelegate:
"""Represents an effect that traps the opponent"""
def __init__(self, startMessage, message, doneMessage):
"""Build the Trap Delegate"""
self.startMessage = startMessage
self.message = message
self.doneMessage = doneMessage
def applyEffect(self, user, ta... | the_stack_v2_python_sparse | src/Battle/Attack/EffectDelegates/trap_delegate.py | sgtnourry/Pokemon-Project | train | 0 |
ecf0e1889c0920e9e40c245e3381e4ab07b56dc4 | [
"self.config = config\nself.device = config['device_str']\nself.model = CollaborativeMemoryNetwork(config, user_embeddings, item_embeddings, item_user_list, self.device)\nself.regs = config['regs']\nself.batch_size = config['batch_size']\nself.optimizer = torch.optim.RMSprop(self.model.parameters(), lr=config['lr']... | <|body_start_0|>
self.config = config
self.device = config['device_str']
self.model = CollaborativeMemoryNetwork(config, user_embeddings, item_embeddings, item_user_list, self.device)
self.regs = config['regs']
self.batch_size = config['batch_size']
self.optimizer = torch... | CMN Engine. | cmnEngine | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class cmnEngine:
"""CMN Engine."""
def __init__(self, config, user_embeddings, item_embeddings, item_user_list):
"""Initialize CMN Engine."""
<|body_0|>
def train_single_batch(self, batch_data):
"""Train a single batch data. Train a single batch data. Args: batch_data ... | stack_v2_sparse_classes_36k_train_003964 | 9,498 | permissive | [
{
"docstring": "Initialize CMN Engine.",
"name": "__init__",
"signature": "def __init__(self, config, user_embeddings, item_embeddings, item_user_list)"
},
{
"docstring": "Train a single batch data. Train a single batch data. Args: batch_data (list): batch users, positive items and negative item... | 4 | null | Implement the Python class `cmnEngine` described below.
Class description:
CMN Engine.
Method signatures and docstrings:
- def __init__(self, config, user_embeddings, item_embeddings, item_user_list): Initialize CMN Engine.
- def train_single_batch(self, batch_data): Train a single batch data. Train a single batch da... | Implement the Python class `cmnEngine` described below.
Class description:
CMN Engine.
Method signatures and docstrings:
- def __init__(self, config, user_embeddings, item_embeddings, item_user_list): Initialize CMN Engine.
- def train_single_batch(self, batch_data): Train a single batch data. Train a single batch da... | 625189d5e1002a3edc27c3e3ce075fddf7ae1c92 | <|skeleton|>
class cmnEngine:
"""CMN Engine."""
def __init__(self, config, user_embeddings, item_embeddings, item_user_list):
"""Initialize CMN Engine."""
<|body_0|>
def train_single_batch(self, batch_data):
"""Train a single batch data. Train a single batch data. Args: batch_data ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class cmnEngine:
"""CMN Engine."""
def __init__(self, config, user_embeddings, item_embeddings, item_user_list):
"""Initialize CMN Engine."""
self.config = config
self.device = config['device_str']
self.model = CollaborativeMemoryNetwork(config, user_embeddings, item_embeddings,... | the_stack_v2_python_sparse | beta_rec/models/cmn.py | beta-team/beta-recsys | train | 156 |
ca85bad96c97c8755b5b30c4979d2fec5814a81a | [
"now = utcnow()\ncutoffs = {ActiveUserPeriods.twenty_four_hours: now - timedelta(hours=24), ActiveUserPeriods.seven_days: now - timedelta(days=7), ActiveUserPeriods.thirty_days: now - timedelta(days=30)}\nfor period, cutoff in cutoffs.items():\n value = self.db.query(orm.User).filter(orm.User.last_activity >= cu... | <|body_start_0|>
now = utcnow()
cutoffs = {ActiveUserPeriods.twenty_four_hours: now - timedelta(hours=24), ActiveUserPeriods.seven_days: now - timedelta(days=7), ActiveUserPeriods.thirty_days: now - timedelta(days=30)}
for period, cutoff in cutoffs.items():
value = self.db.query(orm.... | Collect metrics to be calculated periodically | PeriodicMetricsCollector | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PeriodicMetricsCollector:
"""Collect metrics to be calculated periodically"""
def update_active_users(self):
"""Update active users metrics."""
<|body_0|>
def start(self):
"""Start the periodic update process"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_003965 | 8,820 | permissive | [
{
"docstring": "Update active users metrics.",
"name": "update_active_users",
"signature": "def update_active_users(self)"
},
{
"docstring": "Start the periodic update process",
"name": "start",
"signature": "def start(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018019 | Implement the Python class `PeriodicMetricsCollector` described below.
Class description:
Collect metrics to be calculated periodically
Method signatures and docstrings:
- def update_active_users(self): Update active users metrics.
- def start(self): Start the periodic update process | Implement the Python class `PeriodicMetricsCollector` described below.
Class description:
Collect metrics to be calculated periodically
Method signatures and docstrings:
- def update_active_users(self): Update active users metrics.
- def start(self): Start the periodic update process
<|skeleton|>
class PeriodicMetri... | 7757dea8a463e75d8a540e85deee45c1635dd273 | <|skeleton|>
class PeriodicMetricsCollector:
"""Collect metrics to be calculated periodically"""
def update_active_users(self):
"""Update active users metrics."""
<|body_0|>
def start(self):
"""Start the periodic update process"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PeriodicMetricsCollector:
"""Collect metrics to be calculated periodically"""
def update_active_users(self):
"""Update active users metrics."""
now = utcnow()
cutoffs = {ActiveUserPeriods.twenty_four_hours: now - timedelta(hours=24), ActiveUserPeriods.seven_days: now - timedelta(d... | the_stack_v2_python_sparse | jupyterhub/metrics.py | jupyterhub/jupyterhub | train | 6,751 |
a5040f3a5e0e47313cc30b6e0bc1a9011ddb5779 | [
"super().__init__(sensor, name, bridge, primary_sensor)\nself.device_registry_id = None\nself.event_id = slugify(self.sensor.name)\nself._last_state = dict(self.sensor.state)\nself.bridge.reset_jobs.append(self.bridge.sensor_manager.coordinator.async_add_listener(self.async_update_callback))",
"if self.sensor.sta... | <|body_start_0|>
super().__init__(sensor, name, bridge, primary_sensor)
self.device_registry_id = None
self.event_id = slugify(self.sensor.name)
self._last_state = dict(self.sensor.state)
self.bridge.reset_jobs.append(self.bridge.sensor_manager.coordinator.async_add_listener(self... | When you want signals instead of entities. Stateless sensors such as remotes are expected to generate an event instead of a sensor entity in hass. | HueEvent | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HueEvent:
"""When you want signals instead of entities. Stateless sensors such as remotes are expected to generate an event instead of a sensor entity in hass."""
def __init__(self, sensor, name, bridge, primary_sensor=None):
"""Register callback that will be used for signals."""
... | stack_v2_sparse_classes_36k_train_003966 | 3,659 | permissive | [
{
"docstring": "Register callback that will be used for signals.",
"name": "__init__",
"signature": "def __init__(self, sensor, name, bridge, primary_sensor=None)"
},
{
"docstring": "Fire the event if reason is that state is updated.",
"name": "async_update_callback",
"signature": "def a... | 3 | stack_v2_sparse_classes_30k_train_005822 | Implement the Python class `HueEvent` described below.
Class description:
When you want signals instead of entities. Stateless sensors such as remotes are expected to generate an event instead of a sensor entity in hass.
Method signatures and docstrings:
- def __init__(self, sensor, name, bridge, primary_sensor=None)... | Implement the Python class `HueEvent` described below.
Class description:
When you want signals instead of entities. Stateless sensors such as remotes are expected to generate an event instead of a sensor entity in hass.
Method signatures and docstrings:
- def __init__(self, sensor, name, bridge, primary_sensor=None)... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class HueEvent:
"""When you want signals instead of entities. Stateless sensors such as remotes are expected to generate an event instead of a sensor entity in hass."""
def __init__(self, sensor, name, bridge, primary_sensor=None):
"""Register callback that will be used for signals."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HueEvent:
"""When you want signals instead of entities. Stateless sensors such as remotes are expected to generate an event instead of a sensor entity in hass."""
def __init__(self, sensor, name, bridge, primary_sensor=None):
"""Register callback that will be used for signals."""
super().... | the_stack_v2_python_sparse | homeassistant/components/hue/v1/hue_event.py | home-assistant/core | train | 35,501 |
571307be1e1d20222afe3cbe4527af5fcb38f445 | [
"try:\n return Member.objects.get(pk=pk)\nexcept Member.DoesNotExist:\n raise Http404",
"if pk is not None:\n member = self.get_member(int(pk))\nelse:\n member = None\nself.check_object_permissions(request, member)\nsecurity = SecurityShares.get_members_securities(member=member)\nserializer = Security... | <|body_start_0|>
try:
return Member.objects.get(pk=pk)
except Member.DoesNotExist:
raise Http404
<|end_body_0|>
<|body_start_1|>
if pk is not None:
member = self.get_member(int(pk))
else:
member = None
self.check_object_permissions... | LoanSecuritySharesView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoanSecuritySharesView:
def get_member(self, pk):
"""Get a member."""
<|body_0|>
def get(self, request, pk, format=None):
"""List Securities in form of shares --- serializer: loans.serializers.SecuritySharesSerializer"""
<|body_1|>
def post(self, request... | stack_v2_sparse_classes_36k_train_003967 | 13,511 | no_license | [
{
"docstring": "Get a member.",
"name": "get_member",
"signature": "def get_member(self, pk)"
},
{
"docstring": "List Securities in form of shares --- serializer: loans.serializers.SecuritySharesSerializer",
"name": "get",
"signature": "def get(self, request, pk, format=None)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_008707 | Implement the Python class `LoanSecuritySharesView` described below.
Class description:
Implement the LoanSecuritySharesView class.
Method signatures and docstrings:
- def get_member(self, pk): Get a member.
- def get(self, request, pk, format=None): List Securities in form of shares --- serializer: loans.serializers... | Implement the Python class `LoanSecuritySharesView` described below.
Class description:
Implement the LoanSecuritySharesView class.
Method signatures and docstrings:
- def get_member(self, pk): Get a member.
- def get(self, request, pk, format=None): List Securities in form of shares --- serializer: loans.serializers... | c5ac11e40a628c93c3865363e97b4f255a104ca8 | <|skeleton|>
class LoanSecuritySharesView:
def get_member(self, pk):
"""Get a member."""
<|body_0|>
def get(self, request, pk, format=None):
"""List Securities in form of shares --- serializer: loans.serializers.SecuritySharesSerializer"""
<|body_1|>
def post(self, request... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoanSecuritySharesView:
def get_member(self, pk):
"""Get a member."""
try:
return Member.objects.get(pk=pk)
except Member.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
"""List Securities in form of shares --- serializer: loans... | the_stack_v2_python_sparse | loans/views.py | lubegamark/gosacco | train | 2 | |
b6d646158c83d56ddc7274cf65f792388e56899f | [
"file = './FilteredData/filteredData.csv'\nhistogram = MonthlyHistogram(file)\nv = histogram.getYearCounts(2000, ['Hail'])\nself.assertEqual(len(v), 12)\nself.assertTrue(sum(v) > 0)",
"file = './FilteredData/filteredData.csv'\nhistogram = MonthlyHistogram(file)\nv = histogram.getYearCounts(1992, ['Hail', 'Tornado... | <|body_start_0|>
file = './FilteredData/filteredData.csv'
histogram = MonthlyHistogram(file)
v = histogram.getYearCounts(2000, ['Hail'])
self.assertEqual(len(v), 12)
self.assertTrue(sum(v) > 0)
<|end_body_0|>
<|body_start_1|>
file = './FilteredData/filteredData.csv'
... | HistogramTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HistogramTests:
def test_lengthHail(self):
"""Tests length valid"""
<|body_0|>
def test_lengthMulti(self):
"""Tests length valid with multiselect"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
file = './FilteredData/filteredData.csv'
histog... | stack_v2_sparse_classes_36k_train_003968 | 744 | no_license | [
{
"docstring": "Tests length valid",
"name": "test_lengthHail",
"signature": "def test_lengthHail(self)"
},
{
"docstring": "Tests length valid with multiselect",
"name": "test_lengthMulti",
"signature": "def test_lengthMulti(self)"
}
] | 2 | null | Implement the Python class `HistogramTests` described below.
Class description:
Implement the HistogramTests class.
Method signatures and docstrings:
- def test_lengthHail(self): Tests length valid
- def test_lengthMulti(self): Tests length valid with multiselect | Implement the Python class `HistogramTests` described below.
Class description:
Implement the HistogramTests class.
Method signatures and docstrings:
- def test_lengthHail(self): Tests length valid
- def test_lengthMulti(self): Tests length valid with multiselect
<|skeleton|>
class HistogramTests:
def test_leng... | dc9185cbc5e65650d985ebecf877a157c8c19a13 | <|skeleton|>
class HistogramTests:
def test_lengthHail(self):
"""Tests length valid"""
<|body_0|>
def test_lengthMulti(self):
"""Tests length valid with multiselect"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HistogramTests:
def test_lengthHail(self):
"""Tests length valid"""
file = './FilteredData/filteredData.csv'
histogram = MonthlyHistogram(file)
v = histogram.getYearCounts(2000, ['Hail'])
self.assertEqual(len(v), 12)
self.assertTrue(sum(v) > 0)
def test_len... | the_stack_v2_python_sparse | rb2540/HistogramTests.py | ds-ga-1007/final_project | train | 0 | |
babba4ccdac80cc41a7a9cdcb7491ed1ad70221e | [
"cur = 0\ncourses.sort(key=lambda c: c[1])\nq = []\nfor duration, endTime in courses:\n cur += duration\n heappush(q, -duration)\n if cur > endTime:\n cur += heappop(q)\nreturn len(q)",
"a = []\nfor t, d in courses:\n heappush(a, (d - t + 1, t))\nstart, count = (1, 0)\nwhile a:\n s, t = heap... | <|body_start_0|>
cur = 0
courses.sort(key=lambda c: c[1])
q = []
for duration, endTime in courses:
cur += duration
heappush(q, -duration)
if cur > endTime:
cur += heappop(q)
return len(q)
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def scheduleCourse(self, courses):
""":type courses: List[List[int]] :rtype: int"""
<|body_0|>
def scheduleCourse2(self, courses):
""":type courses: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cur = 0
... | stack_v2_sparse_classes_36k_train_003969 | 3,012 | no_license | [
{
"docstring": ":type courses: List[List[int]] :rtype: int",
"name": "scheduleCourse",
"signature": "def scheduleCourse(self, courses)"
},
{
"docstring": ":type courses: List[List[int]] :rtype: int",
"name": "scheduleCourse2",
"signature": "def scheduleCourse2(self, courses)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def scheduleCourse(self, courses): :type courses: List[List[int]] :rtype: int
- def scheduleCourse2(self, courses): :type courses: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def scheduleCourse(self, courses): :type courses: List[List[int]] :rtype: int
- def scheduleCourse2(self, courses): :type courses: List[List[int]] :rtype: int
<|skeleton|>
class... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def scheduleCourse(self, courses):
""":type courses: List[List[int]] :rtype: int"""
<|body_0|>
def scheduleCourse2(self, courses):
""":type courses: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def scheduleCourse(self, courses):
""":type courses: List[List[int]] :rtype: int"""
cur = 0
courses.sort(key=lambda c: c[1])
q = []
for duration, endTime in courses:
cur += duration
heappush(q, -duration)
if cur > endTime:
... | the_stack_v2_python_sparse | code630CourseScheduleIII.py | cybelewang/leetcode-python | train | 0 | |
d747529797c266d0199220879c7cdd9392d532d6 | [
"super().__init__(embed_dim, num_heads, dropout=dropout, bias=True, add_bias_kv=False, add_zero_attn=add_zero_attn, kdim=None, vdim=None)\nself.id_out_weight = torch.eye(self.head_dim)\nself.id_out_bias = torch.zeros(self.head_dim)",
"query = query.transpose(1, 0)\nkey = key.transpose(1, 0)\nvalue = value.transpo... | <|body_start_0|>
super().__init__(embed_dim, num_heads, dropout=dropout, bias=True, add_bias_kv=False, add_zero_attn=add_zero_attn, kdim=None, vdim=None)
self.id_out_weight = torch.eye(self.head_dim)
self.id_out_bias = torch.zeros(self.head_dim)
<|end_body_0|>
<|body_start_1|>
query = q... | MultiheadAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiheadAttention:
def __init__(self, embed_dim, num_heads, dropout=0.0, add_zero_attn=False):
"""Same as `torch.nn.MultiheadAttention`, but with option to return attention weights for each head separately instead of as average. Disallow specifying bias, add_bias_kv, kdim, vdim."""
... | stack_v2_sparse_classes_36k_train_003970 | 20,414 | no_license | [
{
"docstring": "Same as `torch.nn.MultiheadAttention`, but with option to return attention weights for each head separately instead of as average. Disallow specifying bias, add_bias_kv, kdim, vdim.",
"name": "__init__",
"signature": "def __init__(self, embed_dim, num_heads, dropout=0.0, add_zero_attn=Fa... | 2 | stack_v2_sparse_classes_30k_train_004312 | Implement the Python class `MultiheadAttention` described below.
Class description:
Implement the MultiheadAttention class.
Method signatures and docstrings:
- def __init__(self, embed_dim, num_heads, dropout=0.0, add_zero_attn=False): Same as `torch.nn.MultiheadAttention`, but with option to return attention weights... | Implement the Python class `MultiheadAttention` described below.
Class description:
Implement the MultiheadAttention class.
Method signatures and docstrings:
- def __init__(self, embed_dim, num_heads, dropout=0.0, add_zero_attn=False): Same as `torch.nn.MultiheadAttention`, but with option to return attention weights... | 793543ebd3e526bdd8931a269fdf17808762d9bc | <|skeleton|>
class MultiheadAttention:
def __init__(self, embed_dim, num_heads, dropout=0.0, add_zero_attn=False):
"""Same as `torch.nn.MultiheadAttention`, but with option to return attention weights for each head separately instead of as average. Disallow specifying bias, add_bias_kv, kdim, vdim."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiheadAttention:
def __init__(self, embed_dim, num_heads, dropout=0.0, add_zero_attn=False):
"""Same as `torch.nn.MultiheadAttention`, but with option to return attention weights for each head separately instead of as average. Disallow specifying bias, add_bias_kv, kdim, vdim."""
super().__... | the_stack_v2_python_sparse | seqmodel/model/transformer.py | devinkwok/seqmodelv2 | train | 0 | |
9b6dbef33286fc466c88750f7ee19c282b25a926 | [
"self._translation_directories = []\nif entry_point_group:\n self.add_entrypoint(entry_point_group)\nfor p in paths or []:\n self.add_path(p)",
"for ep in iter_entry_points(group=entry_point_group):\n if not resource_isdir(ep.module_name, 'translations'):\n continue\n dirname = resource_filenam... | <|body_start_0|>
self._translation_directories = []
if entry_point_group:
self.add_entrypoint(entry_point_group)
for p in paths or []:
self.add_path(p)
<|end_body_0|>
<|body_start_1|>
for ep in iter_entry_points(group=entry_point_group):
if not resour... | Domain supporting merging translations from many catalogs. The domain contains an internal list of paths that it loads translations from. The translations are merged in order of the list of paths, hence the last path in the list will overwrite strings set by previous paths. Entry points are added to the list of paths b... | MultidirDomain | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultidirDomain:
"""Domain supporting merging translations from many catalogs. The domain contains an internal list of paths that it loads translations from. The translations are merged in order of the list of paths, hence the last path in the list will overwrite strings set by previous paths. Ent... | stack_v2_sparse_classes_36k_train_003971 | 1,968 | permissive | [
{
"docstring": "Initialize domain. :param paths: List of paths with translations. :param entry_point_group: Name of entry point group. :param domain: Name of message catalog domain. (Default: ``'messages'``)",
"name": "__init__",
"signature": "def __init__(self, paths=None, entry_point_group=None, domai... | 3 | stack_v2_sparse_classes_30k_train_017248 | Implement the Python class `MultidirDomain` described below.
Class description:
Domain supporting merging translations from many catalogs. The domain contains an internal list of paths that it loads translations from. The translations are merged in order of the list of paths, hence the last path in the list will overw... | Implement the Python class `MultidirDomain` described below.
Class description:
Domain supporting merging translations from many catalogs. The domain contains an internal list of paths that it loads translations from. The translations are merged in order of the list of paths, hence the last path in the list will overw... | 287849c1dd52904cbb7c7da4e6da469b603a2dfe | <|skeleton|>
class MultidirDomain:
"""Domain supporting merging translations from many catalogs. The domain contains an internal list of paths that it loads translations from. The translations are merged in order of the list of paths, hence the last path in the list will overwrite strings set by previous paths. Ent... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultidirDomain:
"""Domain supporting merging translations from many catalogs. The domain contains an internal list of paths that it loads translations from. The translations are merged in order of the list of paths, hence the last path in the list will overwrite strings set by previous paths. Entry points are... | the_stack_v2_python_sparse | invenio_i18n/babel.py | inveniosoftware/invenio-i18n | train | 6 |
0eadfbfa1e83c474a949ac72b99f3851e324c0f4 | [
"queue = self.messages.Queue(name=queue_ref.RelativeName(), retryConfig=retry_config, rateLimits=rate_limits, appEngineRoutingOverride=app_engine_routing_override, stackdriverLoggingConfig=stackdriver_logging_config)\nrequest = self.messages.CloudtasksProjectsLocationsQueuesCreateRequest(parent=parent_ref.RelativeN... | <|body_start_0|>
queue = self.messages.Queue(name=queue_ref.RelativeName(), retryConfig=retry_config, rateLimits=rate_limits, appEngineRoutingOverride=app_engine_routing_override, stackdriverLoggingConfig=stackdriver_logging_config)
request = self.messages.CloudtasksProjectsLocationsQueuesCreateRequest(... | Client for queues service in the Cloud Tasks API. | Queues | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Queues:
"""Client for queues service in the Cloud Tasks API."""
def Create(self, parent_ref, queue_ref, retry_config=None, rate_limits=None, app_engine_routing_override=None, stackdriver_logging_config=None):
"""Prepares and sends a Create request for creating a queue."""
<|b... | stack_v2_sparse_classes_36k_train_003972 | 19,528 | permissive | [
{
"docstring": "Prepares and sends a Create request for creating a queue.",
"name": "Create",
"signature": "def Create(self, parent_ref, queue_ref, retry_config=None, rate_limits=None, app_engine_routing_override=None, stackdriver_logging_config=None)"
},
{
"docstring": "Prepares and sends a Pat... | 2 | stack_v2_sparse_classes_30k_train_009648 | Implement the Python class `Queues` described below.
Class description:
Client for queues service in the Cloud Tasks API.
Method signatures and docstrings:
- def Create(self, parent_ref, queue_ref, retry_config=None, rate_limits=None, app_engine_routing_override=None, stackdriver_logging_config=None): Prepares and se... | Implement the Python class `Queues` described below.
Class description:
Client for queues service in the Cloud Tasks API.
Method signatures and docstrings:
- def Create(self, parent_ref, queue_ref, retry_config=None, rate_limits=None, app_engine_routing_override=None, stackdriver_logging_config=None): Prepares and se... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class Queues:
"""Client for queues service in the Cloud Tasks API."""
def Create(self, parent_ref, queue_ref, retry_config=None, rate_limits=None, app_engine_routing_override=None, stackdriver_logging_config=None):
"""Prepares and sends a Create request for creating a queue."""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Queues:
"""Client for queues service in the Cloud Tasks API."""
def Create(self, parent_ref, queue_ref, retry_config=None, rate_limits=None, app_engine_routing_override=None, stackdriver_logging_config=None):
"""Prepares and sends a Create request for creating a queue."""
queue = self.mes... | the_stack_v2_python_sparse | lib/googlecloudsdk/api_lib/tasks/queues.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
9d46b78b8ce6d6b0a23980962b85022ac1f5ee3d | [
"soup = BeautifulSoup(''.join(data), 'lxml')\ntracks = []\nfor entry in soup.findAll(lambda tag: tag.name == 'td' and tag.get('class') == None):\n prev = entry.find_previous()\n if prev.a and 'shz.am' in prev.a['href']:\n track = entry.a.text\n for e in prev.findAll(lambda tag: tag.name == 'td' ... | <|body_start_0|>
soup = BeautifulSoup(''.join(data), 'lxml')
tracks = []
for entry in soup.findAll(lambda tag: tag.name == 'td' and tag.get('class') == None):
prev = entry.find_previous()
if prev.a and 'shz.am' in prev.a['href']:
track = entry.a.text
... | Shazam 'Download History' Library | ShazamDownloadLibrary | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShazamDownloadLibrary:
"""Shazam 'Download History' Library"""
def html_parser(data):
"""Shazam (HTML) parser using BeautifulSoup"""
<|body_0|>
def parse(self, library_file):
"""Process Shazam downloadble playlist, return items"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k_train_003973 | 1,251 | permissive | [
{
"docstring": "Shazam (HTML) parser using BeautifulSoup",
"name": "html_parser",
"signature": "def html_parser(data)"
},
{
"docstring": "Process Shazam downloadble playlist, return items",
"name": "parse",
"signature": "def parse(self, library_file)"
}
] | 2 | null | Implement the Python class `ShazamDownloadLibrary` described below.
Class description:
Shazam 'Download History' Library
Method signatures and docstrings:
- def html_parser(data): Shazam (HTML) parser using BeautifulSoup
- def parse(self, library_file): Process Shazam downloadble playlist, return items | Implement the Python class `ShazamDownloadLibrary` described below.
Class description:
Shazam 'Download History' Library
Method signatures and docstrings:
- def html_parser(data): Shazam (HTML) parser using BeautifulSoup
- def parse(self, library_file): Process Shazam downloadble playlist, return items
<|skeleton|>
... | 3e35a25cfcf982a3871cf0d819bae4374ee31ecf | <|skeleton|>
class ShazamDownloadLibrary:
"""Shazam 'Download History' Library"""
def html_parser(data):
"""Shazam (HTML) parser using BeautifulSoup"""
<|body_0|>
def parse(self, library_file):
"""Process Shazam downloadble playlist, return items"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShazamDownloadLibrary:
"""Shazam 'Download History' Library"""
def html_parser(data):
"""Shazam (HTML) parser using BeautifulSoup"""
soup = BeautifulSoup(''.join(data), 'lxml')
tracks = []
for entry in soup.findAll(lambda tag: tag.name == 'td' and tag.get('class') == None)... | the_stack_v2_python_sparse | voiceplay/datasources/playlists/libraries/shazam.py | tb0hdan/voiceplay | train | 4 |
8c358e061230b951846f8c2e7a9a3c4b9e9d9df1 | [
"try:\n if len(args) > 1:\n raise ValueError('Invalid URL')\n if not args:\n self.write_as_json(RUNTIME.ues.values())\n else:\n ue = uuid.UUID(args[0])\n self.write_as_json(RUNTIME.ues[ue])\nexcept KeyError as ex:\n self.send_error(404, message=ex)\nexcept ValueError as ex:\n... | <|body_start_0|>
try:
if len(args) > 1:
raise ValueError('Invalid URL')
if not args:
self.write_as_json(RUNTIME.ues.values())
else:
ue = uuid.UUID(args[0])
self.write_as_json(RUNTIME.ues[ue])
except KeyEr... | UE handler. Used to view UEs (controller-wide). | UEHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UEHandler:
"""UE handler. Used to view UEs (controller-wide)."""
def get(self, *args, **kwargs):
"""Get all UEs or just the specified one. Args: ue_id: the lvap address Example URLs: GET /api/v1/ues GET /api/v1/ues/123345"""
<|body_0|>
def put(self, *args, **kwargs):
... | stack_v2_sparse_classes_36k_train_003974 | 3,103 | permissive | [
{
"docstring": "Get all UEs or just the specified one. Args: ue_id: the lvap address Example URLs: GET /api/v1/ues GET /api/v1/ues/123345",
"name": "get",
"signature": "def get(self, *args, **kwargs)"
},
{
"docstring": "Set the cell for a given UE. Args: ud_id: the ue id Request: version: the pr... | 2 | null | Implement the Python class `UEHandler` described below.
Class description:
UE handler. Used to view UEs (controller-wide).
Method signatures and docstrings:
- def get(self, *args, **kwargs): Get all UEs or just the specified one. Args: ue_id: the lvap address Example URLs: GET /api/v1/ues GET /api/v1/ues/123345
- def... | Implement the Python class `UEHandler` described below.
Class description:
UE handler. Used to view UEs (controller-wide).
Method signatures and docstrings:
- def get(self, *args, **kwargs): Get all UEs or just the specified one. Args: ue_id: the lvap address Example URLs: GET /api/v1/ues GET /api/v1/ues/123345
- def... | eda52649f855722fdec1d02e25a28c61a8fbda06 | <|skeleton|>
class UEHandler:
"""UE handler. Used to view UEs (controller-wide)."""
def get(self, *args, **kwargs):
"""Get all UEs or just the specified one. Args: ue_id: the lvap address Example URLs: GET /api/v1/ues GET /api/v1/ues/123345"""
<|body_0|>
def put(self, *args, **kwargs):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UEHandler:
"""UE handler. Used to view UEs (controller-wide)."""
def get(self, *args, **kwargs):
"""Get all UEs or just the specified one. Args: ue_id: the lvap address Example URLs: GET /api/v1/ues GET /api/v1/ues/123345"""
try:
if len(args) > 1:
raise ValueEr... | the_stack_v2_python_sparse | empower/vbsp/uehandler.py | imec-idlab/sdn_wifi_manager | train | 0 |
440b712bab1597389525179d2b83d5c672273e2c | [
"super().__init__(**specs)\nself.allFilters = [{'lam': 0 * u.nm, 'bandwidth': 0 * u.nm}, {'lam': 550 * u.nm, 'bandwidth': 10 * u.nm}, {'lam': 577 * u.nm, 'bandwidth': 10 * u.nm}, {'lam': 600 * u.nm, 'bandwidth': 10 * u.nm}, {'lam': 620 * u.nm, 'bandwidth': 10 * u.nm}, {'lam': 632.8 * u.nm, 'bandwidth': 3 * u.nm}, {... | <|body_start_0|>
super().__init__(**specs)
self.allFilters = [{'lam': 0 * u.nm, 'bandwidth': 0 * u.nm}, {'lam': 550 * u.nm, 'bandwidth': 10 * u.nm}, {'lam': 577 * u.nm, 'bandwidth': 10 * u.nm}, {'lam': 600 * u.nm, 'bandwidth': 10 * u.nm}, {'lam': 620 * u.nm, 'bandwidth': 10 * u.nm}, {'lam': 632.8 * u.nm... | Controls the Thorlabs FW212b filterwheel Device Info: Dimensions (L x W x H) 5.44" x 1.85" x 4.39" (138 x 47 x 112 mm) Filters Installed (Andover Corporation, 12.5mm dia.): #1: 550FS10-12.5 (Q342-29) 550nm Bandpass, FWHM 10nm, $69 #2: 577FS10-12.5 (Q342-06) 577nm Bandpass, FWHM 10nm, (obsolete) #3: 600FS10-12.5 (Q342-1... | FW212b | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FW212b:
"""Controls the Thorlabs FW212b filterwheel Device Info: Dimensions (L x W x H) 5.44" x 1.85" x 4.39" (138 x 47 x 112 mm) Filters Installed (Andover Corporation, 12.5mm dia.): #1: 550FS10-12.5 (Q342-29) 550nm Bandpass, FWHM 10nm, $69 #2: 577FS10-12.5 (Q342-06) 577nm Bandpass, FWHM 10nm, (... | stack_v2_sparse_classes_36k_train_003975 | 4,141 | no_license | [
{
"docstring": "Constructor for the 'FW212b' class. Inputs: port: the COM port the FW212b is attached to (str) numOfFilters: number of filters on wheel (int)",
"name": "__init__",
"signature": "def __init__(self, port='COM12', numOfFilters=12, currentFilter=12, **specs)"
},
{
"docstring": "Gets ... | 3 | stack_v2_sparse_classes_30k_train_011106 | Implement the Python class `FW212b` described below.
Class description:
Controls the Thorlabs FW212b filterwheel Device Info: Dimensions (L x W x H) 5.44" x 1.85" x 4.39" (138 x 47 x 112 mm) Filters Installed (Andover Corporation, 12.5mm dia.): #1: 550FS10-12.5 (Q342-29) 550nm Bandpass, FWHM 10nm, $69 #2: 577FS10-12.5... | Implement the Python class `FW212b` described below.
Class description:
Controls the Thorlabs FW212b filterwheel Device Info: Dimensions (L x W x H) 5.44" x 1.85" x 4.39" (138 x 47 x 112 mm) Filters Installed (Andover Corporation, 12.5mm dia.): #1: 550FS10-12.5 (Q342-29) 550nm Bandpass, FWHM 10nm, $69 #2: 577FS10-12.5... | 8568c9e0558a3b76cdbe75bf851c5666dd73634b | <|skeleton|>
class FW212b:
"""Controls the Thorlabs FW212b filterwheel Device Info: Dimensions (L x W x H) 5.44" x 1.85" x 4.39" (138 x 47 x 112 mm) Filters Installed (Andover Corporation, 12.5mm dia.): #1: 550FS10-12.5 (Q342-29) 550nm Bandpass, FWHM 10nm, $69 #2: 577FS10-12.5 (Q342-06) 577nm Bandpass, FWHM 10nm, (... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FW212b:
"""Controls the Thorlabs FW212b filterwheel Device Info: Dimensions (L x W x H) 5.44" x 1.85" x 4.39" (138 x 47 x 112 mm) Filters Installed (Andover Corporation, 12.5mm dia.): #1: 550FS10-12.5 (Q342-29) 550nm Bandpass, FWHM 10nm, $69 #2: 577FS10-12.5 (Q342-06) 577nm Bandpass, FWHM 10nm, (obsolete) #3:... | the_stack_v2_python_sparse | HCIFS/Device/FilterWheel/FW212b.py | ChrisDelaX/HCIFS | train | 1 |
704706d003f1e05df39d8147592a79739121dfad | [
"organization_id = request.query_params.get('organization_id', None)\ninventory_type = request.query_params.get('inventory_type', 'property')\nonly_used = request.query_params.get('only_used', False)\ncolumns = Column.retrieve_all(organization_id, inventory_type, only_used)\nreturn JsonResponse({'status': 'success'... | <|body_start_0|>
organization_id = request.query_params.get('organization_id', None)
inventory_type = request.query_params.get('inventory_type', 'property')
only_used = request.query_params.get('only_used', False)
columns = Column.retrieve_all(organization_id, inventory_type, only_used)
... | ColumnViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColumnViewSet:
def list(self, request):
"""Retrieves all columns for the user's organization including the raw database columns. Will return all the columns across both the Property and Tax Lot tables. The related field will be true if the column came from the other table that is not the... | stack_v2_sparse_classes_36k_train_003976 | 14,162 | no_license | [
{
"docstring": "Retrieves all columns for the user's organization including the raw database columns. Will return all the columns across both the Property and Tax Lot tables. The related field will be true if the column came from the other table that is not the \"inventory_type\" (which defaults to Property) No... | 4 | null | Implement the Python class `ColumnViewSet` described below.
Class description:
Implement the ColumnViewSet class.
Method signatures and docstrings:
- def list(self, request): Retrieves all columns for the user's organization including the raw database columns. Will return all the columns across both the Property and ... | Implement the Python class `ColumnViewSet` described below.
Class description:
Implement the ColumnViewSet class.
Method signatures and docstrings:
- def list(self, request): Retrieves all columns for the user's organization including the raw database columns. Will return all the columns across both the Property and ... | 9e003b344d0c89f416d23651d1e1ce2a624dc599 | <|skeleton|>
class ColumnViewSet:
def list(self, request):
"""Retrieves all columns for the user's organization including the raw database columns. Will return all the columns across both the Property and Tax Lot tables. The related field will be true if the column came from the other table that is not the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ColumnViewSet:
def list(self, request):
"""Retrieves all columns for the user's organization including the raw database columns. Will return all the columns across both the Property and Tax Lot tables. The related field will be true if the column came from the other table that is not the "inventory_ty... | the_stack_v2_python_sparse | seed/views/columns.py | 353388947/seed | train | 1 | |
c2a4af0a2511deffd1afc708170ab0c0d396a864 | [
"user = request.user\ntry:\n address = Address.objects.get(user=user, is_default=True)\nexcept Address.DoesNotExist:\n address = None\ncontext = {'page': '3', 'address': address}\nreturn render(request, 'user_center_site.html', context)",
"receiver = request.POST.get('receiver')\naddr = request.POST.get('ad... | <|body_start_0|>
user = request.user
try:
address = Address.objects.get(user=user, is_default=True)
except Address.DoesNotExist:
address = None
context = {'page': '3', 'address': address}
return render(request, 'user_center_site.html', context)
<|end_body_... | 用户中心-信息页 | UserAddressView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserAddressView:
"""用户中心-信息页"""
def get(self, request):
"""显示"""
<|body_0|>
def post(self, request):
"""地址的添加"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
user = request.user
try:
address = Address.objects.get(user=user, i... | stack_v2_sparse_classes_36k_train_003977 | 10,797 | no_license | [
{
"docstring": "显示",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "地址的添加",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015638 | Implement the Python class `UserAddressView` described below.
Class description:
用户中心-信息页
Method signatures and docstrings:
- def get(self, request): 显示
- def post(self, request): 地址的添加 | Implement the Python class `UserAddressView` described below.
Class description:
用户中心-信息页
Method signatures and docstrings:
- def get(self, request): 显示
- def post(self, request): 地址的添加
<|skeleton|>
class UserAddressView:
"""用户中心-信息页"""
def get(self, request):
"""显示"""
<|body_0|>
def po... | 02eeb9bb293d6c3cf3d9882855f558de40238e10 | <|skeleton|>
class UserAddressView:
"""用户中心-信息页"""
def get(self, request):
"""显示"""
<|body_0|>
def post(self, request):
"""地址的添加"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserAddressView:
"""用户中心-信息页"""
def get(self, request):
"""显示"""
user = request.user
try:
address = Address.objects.get(user=user, is_default=True)
except Address.DoesNotExist:
address = None
context = {'page': '3', 'address': address}
... | the_stack_v2_python_sparse | dailyfresh/user/views.py | pythonfeiji/djangoproject_1803 | train | 0 |
5b8a2569de01e7fc8270151c7035b46d129fda4b | [
"class GoAwayError(Exception):\n\n def __init__(self, name, reason):\n self.name = name\n self.reason = reason\n\nclass MyHandler(BaseHandler):\n \"\"\"\n Handler which raises a custom exception \n \"\"\"\n allowed_methods = ('GET',)\n\n def read(self, request):\n ... | <|body_start_0|>
class GoAwayError(Exception):
def __init__(self, name, reason):
self.name = name
self.reason = reason
class MyHandler(BaseHandler):
"""
Handler which raises a custom exception
"""
... | ErrorHandlerTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ErrorHandlerTest:
def test_customized_error_handler(self):
"""Throw a custom error from a handler method and catch (and format) it in an overridden error_handler method on the associated Resource object"""
<|body_0|>
def test_type_error(self):
"""Verify that type err... | stack_v2_sparse_classes_36k_train_003978 | 7,124 | permissive | [
{
"docstring": "Throw a custom error from a handler method and catch (and format) it in an overridden error_handler method on the associated Resource object",
"name": "test_customized_error_handler",
"signature": "def test_customized_error_handler(self)"
},
{
"docstring": "Verify that type error... | 3 | null | Implement the Python class `ErrorHandlerTest` described below.
Class description:
Implement the ErrorHandlerTest class.
Method signatures and docstrings:
- def test_customized_error_handler(self): Throw a custom error from a handler method and catch (and format) it in an overridden error_handler method on the associa... | Implement the Python class `ErrorHandlerTest` described below.
Class description:
Implement the ErrorHandlerTest class.
Method signatures and docstrings:
- def test_customized_error_handler(self): Throw a custom error from a handler method and catch (and format) it in an overridden error_handler method on the associa... | 1d4724e1d69fae2bb3bbb1bdd3640b253f3f63d3 | <|skeleton|>
class ErrorHandlerTest:
def test_customized_error_handler(self):
"""Throw a custom error from a handler method and catch (and format) it in an overridden error_handler method on the associated Resource object"""
<|body_0|>
def test_type_error(self):
"""Verify that type err... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ErrorHandlerTest:
def test_customized_error_handler(self):
"""Throw a custom error from a handler method and catch (and format) it in an overridden error_handler method on the associated Resource object"""
class GoAwayError(Exception):
def __init__(self, name, reason):
... | the_stack_v2_python_sparse | vendor-local/src/django-piston/piston/tests.py | rtucker-mozilla/minventory | train | 0 | |
ae9a8f0bb32df5471b28635dd3f324a8914f0761 | [
"KratosMultiphysics.Process.__init__(self)\ndefault_settings = KratosMultiphysics.Parameters('\\n {\\n \"help\" : \"This process replaces the properties in a given instant\",\\n \"model_part_name\" : \"\",\\n \"materials_filename\" ... | <|body_start_0|>
KratosMultiphysics.Process.__init__(self)
default_settings = KratosMultiphysics.Parameters('\n {\n "help" : "This process replaces the properties in a given instant",\n "model_part_name" : "",\n "materials_filena... | This process replaces the properties in a given instant Only the member variables listed below should be accessed directly. Public member variables: Model -- the container of the different model parts. settings -- Kratos parameters containing solver settings. | ReplacePropertiesProcess | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReplacePropertiesProcess:
"""This process replaces the properties in a given instant Only the member variables listed below should be accessed directly. Public member variables: Model -- the container of the different model parts. settings -- Kratos parameters containing solver settings."""
... | stack_v2_sparse_classes_36k_train_003979 | 3,806 | permissive | [
{
"docstring": "The default constructor of the class Keyword arguments: self -- It signifies an instance of a class. Model -- the container of the different model parts. settings -- Kratos parameters containing solver settings.",
"name": "__init__",
"signature": "def __init__(self, Model, settings)"
}... | 2 | stack_v2_sparse_classes_30k_train_007699 | Implement the Python class `ReplacePropertiesProcess` described below.
Class description:
This process replaces the properties in a given instant Only the member variables listed below should be accessed directly. Public member variables: Model -- the container of the different model parts. settings -- Kratos paramete... | Implement the Python class `ReplacePropertiesProcess` described below.
Class description:
This process replaces the properties in a given instant Only the member variables listed below should be accessed directly. Public member variables: Model -- the container of the different model parts. settings -- Kratos paramete... | 366949ec4e3651702edc6ac3061d2988f10dd271 | <|skeleton|>
class ReplacePropertiesProcess:
"""This process replaces the properties in a given instant Only the member variables listed below should be accessed directly. Public member variables: Model -- the container of the different model parts. settings -- Kratos parameters containing solver settings."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReplacePropertiesProcess:
"""This process replaces the properties in a given instant Only the member variables listed below should be accessed directly. Public member variables: Model -- the container of the different model parts. settings -- Kratos parameters containing solver settings."""
def __init__(... | the_stack_v2_python_sparse | applications/ContactStructuralMechanicsApplication/python_scripts/replace_properties_process.py | KratosMultiphysics/Kratos | train | 994 |
0980c384b69ae5becc6907d91c08b01ea0750f64 | [
"url = reverse('signup')\nresponse = self.client.get(url)\nlogger.info(response)\nself.assertEqual(response.status_code, 200)",
"url = reverse('signup')\nresponse = self.client.post(url, {'username': 'user', 'password1': 'Word9876', 'password2': 'Word9876'})\nlogger.info(response)\nself.assertRedirects(response, ... | <|body_start_0|>
url = reverse('signup')
response = self.client.get(url)
logger.info(response)
self.assertEqual(response.status_code, 200)
<|end_body_0|>
<|body_start_1|>
url = reverse('signup')
response = self.client.post(url, {'username': 'user', 'password1': 'Word9876... | Test register page. | RegisterPageTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegisterPageTestCase:
"""Test register page."""
def test_register_page_get_request(self):
"""Test get request to Register Page."""
<|body_0|>
def test_register_new_user(self):
"""Test registering new user."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_003980 | 3,223 | no_license | [
{
"docstring": "Test get request to Register Page.",
"name": "test_register_page_get_request",
"signature": "def test_register_page_get_request(self)"
},
{
"docstring": "Test registering new user.",
"name": "test_register_new_user",
"signature": "def test_register_new_user(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008793 | Implement the Python class `RegisterPageTestCase` described below.
Class description:
Test register page.
Method signatures and docstrings:
- def test_register_page_get_request(self): Test get request to Register Page.
- def test_register_new_user(self): Test registering new user. | Implement the Python class `RegisterPageTestCase` described below.
Class description:
Test register page.
Method signatures and docstrings:
- def test_register_page_get_request(self): Test get request to Register Page.
- def test_register_new_user(self): Test registering new user.
<|skeleton|>
class RegisterPageTest... | 5d303bfb6f8729d73a34020bbec494ddb8099450 | <|skeleton|>
class RegisterPageTestCase:
"""Test register page."""
def test_register_page_get_request(self):
"""Test get request to Register Page."""
<|body_0|>
def test_register_new_user(self):
"""Test registering new user."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegisterPageTestCase:
"""Test register page."""
def test_register_page_get_request(self):
"""Test get request to Register Page."""
url = reverse('signup')
response = self.client.get(url)
logger.info(response)
self.assertEqual(response.status_code, 200)
def tes... | the_stack_v2_python_sparse | accounts/tests.py | ghrust/cs50w-finalProject-CRM | train | 1 |
74be59a8e03fc7a35a40f074566866535665bcb8 | [
"matrix = [[0] * n for _ in range(n)]\nfor i, e in enumerate(edges):\n matrix[e[0]][e[1]] = succProb[i]\n matrix[e[1]][e[0]] = succProb[i]\nres = 0\n\ndef dfs(cur, matrix, end, cursp, havedone):\n if cur == end:\n nonlocal res\n res = max(res, cursp)\n for i, sp in enumerate(matrix[cur]):\... | <|body_start_0|>
matrix = [[0] * n for _ in range(n)]
for i, e in enumerate(edges):
matrix[e[0]][e[1]] = succProb[i]
matrix[e[1]][e[0]] = succProb[i]
res = 0
def dfs(cur, matrix, end, cursp, havedone):
if cur == end:
nonlocal res
... | 给你一个由 n 个节点(下标从 0 开始)组成的无向加权图,该图由一个描述边的列表组成, 其中 edges[i] = [a, b] 表示连接节点 a 和 b 的一条无向边,且该边遍历成功的概率为 succProb[i] 。 指定两个节点分别作为起点 start 和终点 end ,请你找出从起点到终点成功概率最大的路径,并返回其成功概率。 | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""给你一个由 n 个节点(下标从 0 开始)组成的无向加权图,该图由一个描述边的列表组成, 其中 edges[i] = [a, b] 表示连接节点 a 和 b 的一条无向边,且该边遍历成功的概率为 succProb[i] 。 指定两个节点分别作为起点 start 和终点 end ,请你找出从起点到终点成功概率最大的路径,并返回其成功概率。"""
def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> f... | stack_v2_sparse_classes_36k_train_003981 | 3,148 | no_license | [
{
"docstring": "我用的方法就是直接dfs用邻接矩阵储存连接信息 但是会超时在有1000个节点的时候 :param n: :param edges: :param succProb: :param start: :param end: :return:",
"name": "maxProbability",
"signature": "def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float"
},
{
"do... | 2 | stack_v2_sparse_classes_30k_test_000653 | Implement the Python class `Solution` described below.
Class description:
给你一个由 n 个节点(下标从 0 开始)组成的无向加权图,该图由一个描述边的列表组成, 其中 edges[i] = [a, b] 表示连接节点 a 和 b 的一条无向边,且该边遍历成功的概率为 succProb[i] 。 指定两个节点分别作为起点 start 和终点 end ,请你找出从起点到终点成功概率最大的路径,并返回其成功概率。
Method signatures and docstrings:
- def maxProbability(self, n: int, edges... | Implement the Python class `Solution` described below.
Class description:
给你一个由 n 个节点(下标从 0 开始)组成的无向加权图,该图由一个描述边的列表组成, 其中 edges[i] = [a, b] 表示连接节点 a 和 b 的一条无向边,且该边遍历成功的概率为 succProb[i] 。 指定两个节点分别作为起点 start 和终点 end ,请你找出从起点到终点成功概率最大的路径,并返回其成功概率。
Method signatures and docstrings:
- def maxProbability(self, n: int, edges... | e7a7b7537edbbb8fa35c2dddf2b122cf863e479d | <|skeleton|>
class Solution:
"""给你一个由 n 个节点(下标从 0 开始)组成的无向加权图,该图由一个描述边的列表组成, 其中 edges[i] = [a, b] 表示连接节点 a 和 b 的一条无向边,且该边遍历成功的概率为 succProb[i] 。 指定两个节点分别作为起点 start 和终点 end ,请你找出从起点到终点成功概率最大的路径,并返回其成功概率。"""
def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""给你一个由 n 个节点(下标从 0 开始)组成的无向加权图,该图由一个描述边的列表组成, 其中 edges[i] = [a, b] 表示连接节点 a 和 b 的一条无向边,且该边遍历成功的概率为 succProb[i] 。 指定两个节点分别作为起点 start 和终点 end ,请你找出从起点到终点成功概率最大的路径,并返回其成功概率。"""
def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float:
... | the_stack_v2_python_sparse | Graph/概率最大路径(Dijkstra)L1514.py | QiuHongHao123/Algorithm-Practise | train | 0 |
22ad13c8c39e01c29b718dafc8ac53932ea36b6a | [
"self.capacity = capacity\nself.keyToNode = dict()\nself.countToKeyNode = defaultdict(OrderedDict)\nself.min_cnt = 1",
"if key not in self.keyToNode:\n return -1\nnode = self.keyToNode[key]\nself.countToKeyNode[node.cnt].pop(key)\nif not self.countToKeyNode[node.cnt]:\n self.countToKeyNode.pop(node.cnt)\n ... | <|body_start_0|>
self.capacity = capacity
self.keyToNode = dict()
self.countToKeyNode = defaultdict(OrderedDict)
self.min_cnt = 1
<|end_body_0|>
<|body_start_1|>
if key not in self.keyToNode:
return -1
node = self.keyToNode[key]
self.countToKeyNode[no... | LFUCache2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LFUCache2:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_... | stack_v2_sparse_classes_36k_train_003982 | 5,409 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_013262 | Implement the Python class `LFUCache2` described below.
Class description:
Implement the LFUCache2 class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LFUCache2` described below.
Class description:
Implement the LFUCache2 class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|... | 11d6bf2ba7b50c07e048df37c4e05c8f46b92241 | <|skeleton|>
class LFUCache2:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LFUCache2:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.keyToNode = dict()
self.countToKeyNode = defaultdict(OrderedDict)
self.min_cnt = 1
def get(self, key):
""":type key: int :rtype: int"""
if key not in se... | the_stack_v2_python_sparse | LeetCodes/Amazon/LFUCache.py | chutianwen/LeetCodes | train | 0 | |
f59a6a7ec6b58b1134d5eebedacb7f6168f69e57 | [
"parser = parser.add_argument_group('RandomCandidateAgent Arguments')\nparser.add_argument('--label_candidates_file', type=str, default=None, help='file of candidate responses to choose from')\nreturn parser",
"super().__init__(opt)\nself.id = 'RandomCandidateAgent'\nrandom.seed(42)\nif opt.get('label_candidates_... | <|body_start_0|>
parser = parser.add_argument_group('RandomCandidateAgent Arguments')
parser.add_argument('--label_candidates_file', type=str, default=None, help='file of candidate responses to choose from')
return parser
<|end_body_0|>
<|body_start_1|>
super().__init__(opt)
sel... | Agent returns random candidate if available or repeats the label. | RandomCandidateAgent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomCandidateAgent:
"""Agent returns random candidate if available or repeats the label."""
def add_cmdline_args(cls, parser: ParlaiParser, partial_opt: Optional[Opt]=None) -> ParlaiParser:
"""Add command line arguments for this agent."""
<|body_0|>
def __init__(self, ... | stack_v2_sparse_classes_36k_train_003983 | 2,698 | permissive | [
{
"docstring": "Add command line arguments for this agent.",
"name": "add_cmdline_args",
"signature": "def add_cmdline_args(cls, parser: ParlaiParser, partial_opt: Optional[Opt]=None) -> ParlaiParser"
},
{
"docstring": "Initialize this agent.",
"name": "__init__",
"signature": "def __ini... | 3 | null | Implement the Python class `RandomCandidateAgent` described below.
Class description:
Agent returns random candidate if available or repeats the label.
Method signatures and docstrings:
- def add_cmdline_args(cls, parser: ParlaiParser, partial_opt: Optional[Opt]=None) -> ParlaiParser: Add command line arguments for t... | Implement the Python class `RandomCandidateAgent` described below.
Class description:
Agent returns random candidate if available or repeats the label.
Method signatures and docstrings:
- def add_cmdline_args(cls, parser: ParlaiParser, partial_opt: Optional[Opt]=None) -> ParlaiParser: Add command line arguments for t... | e1d899edfb92471552bae153f59ad30aa7fca468 | <|skeleton|>
class RandomCandidateAgent:
"""Agent returns random candidate if available or repeats the label."""
def add_cmdline_args(cls, parser: ParlaiParser, partial_opt: Optional[Opt]=None) -> ParlaiParser:
"""Add command line arguments for this agent."""
<|body_0|>
def __init__(self, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomCandidateAgent:
"""Agent returns random candidate if available or repeats the label."""
def add_cmdline_args(cls, parser: ParlaiParser, partial_opt: Optional[Opt]=None) -> ParlaiParser:
"""Add command line arguments for this agent."""
parser = parser.add_argument_group('RandomCandid... | the_stack_v2_python_sparse | parlai/agents/random_candidate/random_candidate.py | facebookresearch/ParlAI | train | 10,943 |
2e82115a19076bd3b22ea26cea5c7078b3aa0738 | [
"res, tmp = (0, 0)\nfor i in nums:\n if i == 1:\n tmp += 1\n if i == 0:\n tmp = 0\n if tmp > res:\n res = tmp\nreturn res",
"import re\nif 1 not in nums:\n return 0\nnums_str = ''.join([str(x) for x in nums])\nreturn max([len(x) for x in re.findall('1+', nums_str)])",
"nums_str ... | <|body_start_0|>
res, tmp = (0, 0)
for i in nums:
if i == 1:
tmp += 1
if i == 0:
tmp = 0
if tmp > res:
res = tmp
return res
<|end_body_0|>
<|body_start_1|>
import re
if 1 not in nums:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMaxConsecutiveOnes(self, nums):
"""计数 :type nums: List[int] :rtype: int"""
<|body_0|>
def findMaxConsecutiveOnes2(self, nums):
"""使用re :type nums: List[int] :rtype: int"""
<|body_1|>
def findMaxConsecutiveOnes3(self, nums):
"""以... | stack_v2_sparse_classes_36k_train_003984 | 1,314 | no_license | [
{
"docstring": "计数 :type nums: List[int] :rtype: int",
"name": "findMaxConsecutiveOnes",
"signature": "def findMaxConsecutiveOnes(self, nums)"
},
{
"docstring": "使用re :type nums: List[int] :rtype: int",
"name": "findMaxConsecutiveOnes2",
"signature": "def findMaxConsecutiveOnes2(self, nu... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMaxConsecutiveOnes(self, nums): 计数 :type nums: List[int] :rtype: int
- def findMaxConsecutiveOnes2(self, nums): 使用re :type nums: List[int] :rtype: int
- def findMaxConsec... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMaxConsecutiveOnes(self, nums): 计数 :type nums: List[int] :rtype: int
- def findMaxConsecutiveOnes2(self, nums): 使用re :type nums: List[int] :rtype: int
- def findMaxConsec... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def findMaxConsecutiveOnes(self, nums):
"""计数 :type nums: List[int] :rtype: int"""
<|body_0|>
def findMaxConsecutiveOnes2(self, nums):
"""使用re :type nums: List[int] :rtype: int"""
<|body_1|>
def findMaxConsecutiveOnes3(self, nums):
"""以... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findMaxConsecutiveOnes(self, nums):
"""计数 :type nums: List[int] :rtype: int"""
res, tmp = (0, 0)
for i in nums:
if i == 1:
tmp += 1
if i == 0:
tmp = 0
if tmp > res:
res = tmp
retur... | the_stack_v2_python_sparse | 485_最大连续1的个数.py | lovehhf/LeetCode | train | 0 | |
47380fb45734916b7e577d83b8f3a7a050543fdd | [
"index = Index(self.id)\nif not index.exists():\n try:\n if analyzer:\n index.analyzer(analyzer)\n if document:\n index.document(document)\n index.create()\n if not index.exists():\n raise IndexNotCreatedException\n except es_exceptions.RequestError... | <|body_start_0|>
index = Index(self.id)
if not index.exists():
try:
if analyzer:
index.analyzer(analyzer)
if document:
index.document(document)
index.create()
if not index.exists():
... | Add necessary operations for saving and deleting a model from elastic search | ElasticSearchModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElasticSearchModel:
"""Add necessary operations for saving and deleting a model from elastic search"""
def save(self, analyzer=None, document=None, *args, **kwargs):
"""Create the model and create an index in ES"""
<|body_0|>
def delete(self, *args, **kwargs):
""... | stack_v2_sparse_classes_36k_train_003985 | 48,912 | permissive | [
{
"docstring": "Create the model and create an index in ES",
"name": "save",
"signature": "def save(self, analyzer=None, document=None, *args, **kwargs)"
},
{
"docstring": "Delete the model and delete the index in ES",
"name": "delete",
"signature": "def delete(self, *args, **kwargs)"
... | 3 | stack_v2_sparse_classes_30k_train_012982 | Implement the Python class `ElasticSearchModel` described below.
Class description:
Add necessary operations for saving and deleting a model from elastic search
Method signatures and docstrings:
- def save(self, analyzer=None, document=None, *args, **kwargs): Create the model and create an index in ES
- def delete(se... | Implement the Python class `ElasticSearchModel` described below.
Class description:
Add necessary operations for saving and deleting a model from elastic search
Method signatures and docstrings:
- def save(self, analyzer=None, document=None, *args, **kwargs): Create the model and create an index in ES
- def delete(se... | 6db6794fd1811b316dee6f6661986e027d8a594b | <|skeleton|>
class ElasticSearchModel:
"""Add necessary operations for saving and deleting a model from elastic search"""
def save(self, analyzer=None, document=None, *args, **kwargs):
"""Create the model and create an index in ES"""
<|body_0|>
def delete(self, *args, **kwargs):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ElasticSearchModel:
"""Add necessary operations for saving and deleting a model from elastic search"""
def save(self, analyzer=None, document=None, *args, **kwargs):
"""Create the model and create an index in ES"""
index = Index(self.id)
if not index.exists():
try:
... | the_stack_v2_python_sparse | api/radiam/api/models.py | usask-rc/radiam | train | 2 |
3244bf8ea0d56d10eea595fbe67aa8ccbe21fafd | [
"super(ReachedRegionTest, self).__init__(name, actor, 0)\nself.logger.debug('%s.__init__()' % self.__class__.__name__)\nself._actor = actor\nself._min_x = min_x\nself._max_x = max_x\nself._min_y = min_y\nself._max_y = max_y",
"new_status = py_trees.common.Status.RUNNING\nlocation = CarlaDataProvider.get_location(... | <|body_start_0|>
super(ReachedRegionTest, self).__init__(name, actor, 0)
self.logger.debug('%s.__init__()' % self.__class__.__name__)
self._actor = actor
self._min_x = min_x
self._max_x = max_x
self._min_y = min_y
self._max_y = max_y
<|end_body_0|>
<|body_start_1... | This class contains the reached region test The test is a success if the actor reaches a specified region Important parameters: - actor: CARLA actor to be used for this test - min_x, max_x, min_y, max_y: Bounding box of the checked region | ReachedRegionTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReachedRegionTest:
"""This class contains the reached region test The test is a success if the actor reaches a specified region Important parameters: - actor: CARLA actor to be used for this test - min_x, max_x, min_y, max_y: Bounding box of the checked region"""
def __init__(self, actor, mi... | stack_v2_sparse_classes_36k_train_003986 | 44,616 | permissive | [
{
"docstring": "Setup trigger region (rectangle provided by [min_x,min_y] and [max_x,max_y]",
"name": "__init__",
"signature": "def __init__(self, actor, min_x, max_x, min_y, max_y, name='ReachedRegionTest')"
},
{
"docstring": "Check if the actor location is within trigger region",
"name": "... | 2 | null | Implement the Python class `ReachedRegionTest` described below.
Class description:
This class contains the reached region test The test is a success if the actor reaches a specified region Important parameters: - actor: CARLA actor to be used for this test - min_x, max_x, min_y, max_y: Bounding box of the checked regi... | Implement the Python class `ReachedRegionTest` described below.
Class description:
This class contains the reached region test The test is a success if the actor reaches a specified region Important parameters: - actor: CARLA actor to be used for this test - min_x, max_x, min_y, max_y: Bounding box of the checked regi... | 8ab0894b92e1f994802a218002021ee075c405bf | <|skeleton|>
class ReachedRegionTest:
"""This class contains the reached region test The test is a success if the actor reaches a specified region Important parameters: - actor: CARLA actor to be used for this test - min_x, max_x, min_y, max_y: Bounding box of the checked region"""
def __init__(self, actor, mi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReachedRegionTest:
"""This class contains the reached region test The test is a success if the actor reaches a specified region Important parameters: - actor: CARLA actor to be used for this test - min_x, max_x, min_y, max_y: Bounding box of the checked region"""
def __init__(self, actor, min_x, max_x, m... | the_stack_v2_python_sparse | carla_rllib/carla_rllib-prak_evaluator-carla_rllib-prak_evaluator/carla_rllib/prak_evaluator/srunner/scenarioconfigs/scenariomanager/scenarioatomics/atomic_criteria.py | TinaMenke/Deep-Reinforcement-Learning | train | 9 |
419e4b405dadef0750c4e33c5bba58c4480eb286 | [
"import collections\nwordList = set(wordList)\nres = []\nlayer = {}\nlayer[beginWord] = [[beginWord]]\nwhile layer:\n newlayer = collections.defaultdict(list)\n for w in layer:\n if w == endWord:\n res.extend((k for k in layer[w]))\n else:\n for i in range(len(w)):\n ... | <|body_start_0|>
import collections
wordList = set(wordList)
res = []
layer = {}
layer[beginWord] = [[beginWord]]
while layer:
newlayer = collections.defaultdict(list)
for w in layer:
if w == endWord:
res.extend(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findLadders(self, beginWord, endWord, wordList):
""":type beginWord: str :type endWord: str :type wordList: List[str] :rtype: List[List[str]]"""
<|body_0|>
def rewrite(self, beginWord, endWord, wordList):
""":type beginWord: str :type endWord: str :type... | stack_v2_sparse_classes_36k_train_003987 | 3,718 | no_license | [
{
"docstring": ":type beginWord: str :type endWord: str :type wordList: List[str] :rtype: List[List[str]]",
"name": "findLadders",
"signature": "def findLadders(self, beginWord, endWord, wordList)"
},
{
"docstring": ":type beginWord: str :type endWord: str :type wordList: List[str] :rtype: List[... | 2 | stack_v2_sparse_classes_30k_train_009610 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLadders(self, beginWord, endWord, wordList): :type beginWord: str :type endWord: str :type wordList: List[str] :rtype: List[List[str]]
- def rewrite(self, beginWord, endW... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLadders(self, beginWord, endWord, wordList): :type beginWord: str :type endWord: str :type wordList: List[str] :rtype: List[List[str]]
- def rewrite(self, beginWord, endW... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def findLadders(self, beginWord, endWord, wordList):
""":type beginWord: str :type endWord: str :type wordList: List[str] :rtype: List[List[str]]"""
<|body_0|>
def rewrite(self, beginWord, endWord, wordList):
""":type beginWord: str :type endWord: str :type... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findLadders(self, beginWord, endWord, wordList):
""":type beginWord: str :type endWord: str :type wordList: List[str] :rtype: List[List[str]]"""
import collections
wordList = set(wordList)
res = []
layer = {}
layer[beginWord] = [[beginWord]]
... | the_stack_v2_python_sparse | co_uber/126_Word_Ladder_II.py | vsdrun/lc_public | train | 6 | |
c0296f9f9c855fc4b5c0e53fbbb615c4111fd2af | [
"self.hand = []\nself.hand_value = 0\nself.playing_hand = True",
"for i in range(2):\n card = deck.deal_card()\n self.hand.append(card)",
"input(\"\\nPress enter to reveal the dealer's hand. \")\nfor card in self.hand:\n card.display_card()\n time.sleep(1)",
"self.get_hand_value()\nwhile self.hand... | <|body_start_0|>
self.hand = []
self.hand_value = 0
self.playing_hand = True
<|end_body_0|>
<|body_start_1|>
for i in range(2):
card = deck.deal_card()
self.hand.append(card)
<|end_body_1|>
<|body_start_2|>
input("\nPress enter to reveal the dealer's han... | A class simulating the black jack dealer. They must hit up to 17 and they must reveal their first card. | Dealer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dealer:
"""A class simulating the black jack dealer. They must hit up to 17 and they must reveal their first card."""
def __init__(self):
"""Initialize the dealer"""
<|body_0|>
def draw_hand(self, deck):
"""Deal the dealers starting hand"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_003988 | 9,795 | permissive | [
{
"docstring": "Initialize the dealer",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Deal the dealers starting hand",
"name": "draw_hand",
"signature": "def draw_hand(self, deck)"
},
{
"docstring": "Show the dealers hand one card at a time.",
"name... | 5 | stack_v2_sparse_classes_30k_train_005465 | Implement the Python class `Dealer` described below.
Class description:
A class simulating the black jack dealer. They must hit up to 17 and they must reveal their first card.
Method signatures and docstrings:
- def __init__(self): Initialize the dealer
- def draw_hand(self, deck): Deal the dealers starting hand
- de... | Implement the Python class `Dealer` described below.
Class description:
A class simulating the black jack dealer. They must hit up to 17 and they must reveal their first card.
Method signatures and docstrings:
- def __init__(self): Initialize the dealer
- def draw_hand(self, deck): Deal the dealers starting hand
- de... | a9f44d20ae212b5cbc190ac49ca7acc638ff4228 | <|skeleton|>
class Dealer:
"""A class simulating the black jack dealer. They must hit up to 17 and they must reveal their first card."""
def __init__(self):
"""Initialize the dealer"""
<|body_0|>
def draw_hand(self, deck):
"""Deal the dealers starting hand"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dealer:
"""A class simulating the black jack dealer. They must hit up to 17 and they must reveal their first card."""
def __init__(self):
"""Initialize the dealer"""
self.hand = []
self.hand_value = 0
self.playing_hand = True
def draw_hand(self, deck):
"""Deal... | the_stack_v2_python_sparse | 9_Classes/challenge_37_code.py | demoanddemo/The-Art-of-Doing-Code-40-Challenging-Python-Programs-Today | train | 0 |
be3ef39a100787c28ef1f7579f7aa2352d42a905 | [
"self.name = name\nself.rect = pg.Rect(rect)\nself.command = command\nself.color = (128, 128, 128)\nself.select_rect = self.rect.inflate(-10, -10)\nself.checked = checked",
"if event.type == pg.MOUSEBUTTONDOWN and event.button == 1:\n if self.rect.collidepoint(event.pos):\n self.toggle()",
"self.check... | <|body_start_0|>
self.name = name
self.rect = pg.Rect(rect)
self.command = command
self.color = (128, 128, 128)
self.select_rect = self.rect.inflate(-10, -10)
self.checked = checked
<|end_body_0|>
<|body_start_1|>
if event.type == pg.MOUSEBUTTONDOWN and event.but... | A simple checkbox class. Size and appearance are currently hardcoded. | CheckBox | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckBox:
"""A simple checkbox class. Size and appearance are currently hardcoded."""
def __init__(self, name, rect, checked=False, command=None):
"""The argument name is a string used to refer to the box; rect is a pygame.Rect for the area of the box (inclusive of the border); check... | stack_v2_sparse_classes_36k_train_003989 | 14,532 | no_license | [
{
"docstring": "The argument name is a string used to refer to the box; rect is a pygame.Rect for the area of the box (inclusive of the border); checked is a boolean indicating whether or not the button is currently checked; command is the function that is called when the box is checked or unchecked.",
"nam... | 4 | stack_v2_sparse_classes_30k_train_017458 | Implement the Python class `CheckBox` described below.
Class description:
A simple checkbox class. Size and appearance are currently hardcoded.
Method signatures and docstrings:
- def __init__(self, name, rect, checked=False, command=None): The argument name is a string used to refer to the box; rect is a pygame.Rect... | Implement the Python class `CheckBox` described below.
Class description:
A simple checkbox class. Size and appearance are currently hardcoded.
Method signatures and docstrings:
- def __init__(self, name, rect, checked=False, command=None): The argument name is a string used to refer to the box; rect is a pygame.Rect... | cee7e4b5dc28c57a6c912852827652b5f51005ae | <|skeleton|>
class CheckBox:
"""A simple checkbox class. Size and appearance are currently hardcoded."""
def __init__(self, name, rect, checked=False, command=None):
"""The argument name is a string used to refer to the box; rect is a pygame.Rect for the area of the box (inclusive of the border); check... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CheckBox:
"""A simple checkbox class. Size and appearance are currently hardcoded."""
def __init__(self, name, rect, checked=False, command=None):
"""The argument name is a string used to refer to the box; rect is a pygame.Rect for the area of the box (inclusive of the border); checked is a boole... | the_stack_v2_python_sparse | IE_games_3/cabbages-and-kings-master/data/map_components/map_gui_widgets.py | IndexErrorCoders/PygamesCompilation | train | 2 |
840464221f9705d2cd52d868d9c09fea1fe7389b | [
"try:\n self.log = models.Log()\n self.parse(request=request)\n self.authorise()\n self.validate()\n data = self.execute()\nexcept Exception as e:\n resp = JsonResponse(**self.handle_error(e))\n if settings.DEBUG:\n raise e\nelse:\n self.log.event = events.EVENT_QUERY_ACCEPT\n resp... | <|body_start_0|>
try:
self.log = models.Log()
self.parse(request=request)
self.authorise()
self.validate()
data = self.execute()
except Exception as e:
resp = JsonResponse(**self.handle_error(e))
if settings.DEBUG:
... | LookingGlass view class for djangolg. | LookingGlassJsonView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LookingGlassJsonView:
"""LookingGlass view class for djangolg."""
def get(self, request):
"""Handle GET request."""
<|body_0|>
def parse(self, request=None):
"""Parse the HttpRequest."""
<|body_1|>
def authorise(self):
"""Check AuthKey validi... | stack_v2_sparse_classes_36k_train_003990 | 7,717 | permissive | [
{
"docstring": "Handle GET request.",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Parse the HttpRequest.",
"name": "parse",
"signature": "def parse(self, request=None)"
},
{
"docstring": "Check AuthKey validity.",
"name": "authorise",
"signatur... | 6 | stack_v2_sparse_classes_30k_test_000911 | Implement the Python class `LookingGlassJsonView` described below.
Class description:
LookingGlass view class for djangolg.
Method signatures and docstrings:
- def get(self, request): Handle GET request.
- def parse(self, request=None): Parse the HttpRequest.
- def authorise(self): Check AuthKey validity.
- def valid... | Implement the Python class `LookingGlassJsonView` described below.
Class description:
LookingGlass view class for djangolg.
Method signatures and docstrings:
- def get(self, request): Handle GET request.
- def parse(self, request=None): Parse the HttpRequest.
- def authorise(self): Check AuthKey validity.
- def valid... | 724dbb631da3c61d42f62024f9d7826423624191 | <|skeleton|>
class LookingGlassJsonView:
"""LookingGlass view class for djangolg."""
def get(self, request):
"""Handle GET request."""
<|body_0|>
def parse(self, request=None):
"""Parse the HttpRequest."""
<|body_1|>
def authorise(self):
"""Check AuthKey validi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LookingGlassJsonView:
"""LookingGlass view class for djangolg."""
def get(self, request):
"""Handle GET request."""
try:
self.log = models.Log()
self.parse(request=request)
self.authorise()
self.validate()
data = self.execute()
... | the_stack_v2_python_sparse | djangolg/views/lg.py | jafo2128/djangolg | train | 0 |
3bb30b9a29328d3da01c7fe3b8222364ed71b393 | [
"pq = []\nfor a in nums:\n d = a\n while d % 2 == 0:\n d //= 2\n heapq.heappush(pq, [d, a])\nres = float('inf')\nma = max((a for a, a0 in pq))\nwhile len(pq) == len(nums):\n a, a0 = heapq.heappop(pq)\n res = min(res, ma - a)\n if a % 2 == 1 or a < a0:\n ma = max(ma, a * 2)\n h... | <|body_start_0|>
pq = []
for a in nums:
d = a
while d % 2 == 0:
d //= 2
heapq.heappush(pq, [d, a])
res = float('inf')
ma = max((a for a, a0 in pq))
while len(pq) == len(nums):
a, a0 = heapq.heappop(pq)
re... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minimumDeviation(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def minimumDeviationFlip(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pq = []
for a in nums:
... | stack_v2_sparse_classes_36k_train_003991 | 3,520 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "minimumDeviation",
"signature": "def minimumDeviation(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "minimumDeviationFlip",
"signature": "def minimumDeviationFlip(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumDeviation(self, nums): :type nums: List[int] :rtype: int
- def minimumDeviationFlip(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumDeviation(self, nums): :type nums: List[int] :rtype: int
- def minimumDeviationFlip(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
d... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def minimumDeviation(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def minimumDeviationFlip(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minimumDeviation(self, nums):
""":type nums: List[int] :rtype: int"""
pq = []
for a in nums:
d = a
while d % 2 == 0:
d //= 2
heapq.heappush(pq, [d, a])
res = float('inf')
ma = max((a for a, a0 in pq))
... | the_stack_v2_python_sparse | M/MinimizeDeviationinArray.py | bssrdf/pyleet | train | 2 | |
a2aea9ea335bd280d0d037a8b224e9c58ecc3bde | [
"self.fixed_size = fixed_size\nself.classifier_pkl = classifier_pkl\nself.feature_method = feature_method\nself.feature_options = feature_options\nself.image_processing_options = image_processing_options\nself.raw_image_path = raw_image_path\nself.solver = solver\nself.alpha = alpha\nself.tol = tol\nself.max_iter =... | <|body_start_0|>
self.fixed_size = fixed_size
self.classifier_pkl = classifier_pkl
self.feature_method = feature_method
self.feature_options = feature_options
self.image_processing_options = image_processing_options
self.raw_image_path = raw_image_path
self.solver... | train_classifier | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class train_classifier:
def __init__(self, df_path, image_col_name, category_col_name, fixed_size, classifier_pkl, feature_method, feature_options, image_processing_options, raw_image_path, solver='lbfgs', alpha=0.0001, tol=1e-05, max_iter=200, hidden_layer_sizes=(100,), random_state=1):
"""Th... | stack_v2_sparse_classes_36k_train_003992 | 7,481 | no_license | [
{
"docstring": "The class constructor :param df_path: full path to the input roi DataFrame file (e.g. ../data/roi/roidf.h5) :param image_col_name: column name for the image data column :param category_col_name: column name for the image category (negative or positive) column :param fixed_size: 2x1 matrix contai... | 3 | stack_v2_sparse_classes_30k_train_014929 | Implement the Python class `train_classifier` described below.
Class description:
Implement the train_classifier class.
Method signatures and docstrings:
- def __init__(self, df_path, image_col_name, category_col_name, fixed_size, classifier_pkl, feature_method, feature_options, image_processing_options, raw_image_pa... | Implement the Python class `train_classifier` described below.
Class description:
Implement the train_classifier class.
Method signatures and docstrings:
- def __init__(self, df_path, image_col_name, category_col_name, fixed_size, classifier_pkl, feature_method, feature_options, image_processing_options, raw_image_pa... | bbe858777fa043add1290adf56f213597bf7e44b | <|skeleton|>
class train_classifier:
def __init__(self, df_path, image_col_name, category_col_name, fixed_size, classifier_pkl, feature_method, feature_options, image_processing_options, raw_image_path, solver='lbfgs', alpha=0.0001, tol=1e-05, max_iter=200, hidden_layer_sizes=(100,), random_state=1):
"""Th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class train_classifier:
def __init__(self, df_path, image_col_name, category_col_name, fixed_size, classifier_pkl, feature_method, feature_options, image_processing_options, raw_image_path, solver='lbfgs', alpha=0.0001, tol=1e-05, max_iter=200, hidden_layer_sizes=(100,), random_state=1):
"""The class constr... | the_stack_v2_python_sparse | 2018_data_science_bowl/scripts/train_nn_classifier.py | laijasonk/kaggle | train | 1 | |
91fdacb3c856743643ffced2e2963efbb77224da | [
"if not root:\n return None\nhead, tail = self.helper(root)\nreturn head",
"head, tail = (root, root)\nif root.left:\n left_head, left_tail = self.helper(root.left)\n left_tail.right = root\n root.left = left_tail\n head = left_head\nif root.right:\n right_head, right_tail = self.helper(root.rig... | <|body_start_0|>
if not root:
return None
head, tail = self.helper(root)
return head
<|end_body_0|>
<|body_start_1|>
head, tail = (root, root)
if root.left:
left_head, left_tail = self.helper(root.left)
left_tail.right = root
root.... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def treeToDoublyList(self, root):
""":type root: Node :rtype: Node"""
<|body_0|>
def helper(self, root):
"""construct a doubly-linked list, return the head and tail"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
r... | stack_v2_sparse_classes_36k_train_003993 | 4,401 | no_license | [
{
"docstring": ":type root: Node :rtype: Node",
"name": "treeToDoublyList",
"signature": "def treeToDoublyList(self, root)"
},
{
"docstring": "construct a doubly-linked list, return the head and tail",
"name": "helper",
"signature": "def helper(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def treeToDoublyList(self, root): :type root: Node :rtype: Node
- def helper(self, root): construct a doubly-linked list, return the head and tail | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def treeToDoublyList(self, root): :type root: Node :rtype: Node
- def helper(self, root): construct a doubly-linked list, return the head and tail
<|skeleton|>
class Solution:
... | 9b38a7742a819ac3795ea295e371e26bb5bfc28c | <|skeleton|>
class Solution:
def treeToDoublyList(self, root):
""":type root: Node :rtype: Node"""
<|body_0|>
def helper(self, root):
"""construct a doubly-linked list, return the head and tail"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def treeToDoublyList(self, root):
""":type root: Node :rtype: Node"""
if not root:
return None
head, tail = self.helper(root)
return head
def helper(self, root):
"""construct a doubly-linked list, return the head and tail"""
head, tail... | the_stack_v2_python_sparse | 426. Convert BST to Sorted Doubly Linked List.py | dundunmao/LeetCode2019 | train | 0 | |
4333062a6cf3982e3d7f743d897822d7cbd9a762 | [
"def wrapped(*args, **kwargs):\n return self.wrangler.fit_transform(*args, **kwargs).count()\nreturn wrapped",
"for df in dfs:\n df.persist()\n df.count()",
"for df in dfs:\n df.unpersist()\n if df.is_cached:\n warnings.warn('Spark dataframe could not be unpersisted.', ResourceWarning)"
] | <|body_start_0|>
def wrapped(*args, **kwargs):
return self.wrangler.fit_transform(*args, **kwargs).count()
return wrapped
<|end_body_0|>
<|body_start_1|>
for df in dfs:
df.persist()
df.count()
<|end_body_1|>
<|body_start_2|>
for df in dfs:
... | Define common methods for pyspark profiler. | PySparkBaseProfiler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PySparkBaseProfiler:
"""Define common methods for pyspark profiler."""
def _wrap_fit_transform(self) -> Callable:
"""Wrapper function to call `count()` on wrangler's `fit_transform` to enforce computation on lazily evaluated pyspark dataframes. Returns ------- wrapped: callable Wrapp... | stack_v2_sparse_classes_36k_train_003994 | 4,189 | permissive | [
{
"docstring": "Wrapper function to call `count()` on wrangler's `fit_transform` to enforce computation on lazily evaluated pyspark dataframes. Returns ------- wrapped: callable Wrapped `fit_transform` method as a function.",
"name": "_wrap_fit_transform",
"signature": "def _wrap_fit_transform(self) -> ... | 3 | stack_v2_sparse_classes_30k_train_016810 | Implement the Python class `PySparkBaseProfiler` described below.
Class description:
Define common methods for pyspark profiler.
Method signatures and docstrings:
- def _wrap_fit_transform(self) -> Callable: Wrapper function to call `count()` on wrangler's `fit_transform` to enforce computation on lazily evaluated py... | Implement the Python class `PySparkBaseProfiler` described below.
Class description:
Define common methods for pyspark profiler.
Method signatures and docstrings:
- def _wrap_fit_transform(self) -> Callable: Wrapper function to call `count()` on wrangler's `fit_transform` to enforce computation on lazily evaluated py... | 8561f5f267303e664487ae67095085fcea4308c9 | <|skeleton|>
class PySparkBaseProfiler:
"""Define common methods for pyspark profiler."""
def _wrap_fit_transform(self) -> Callable:
"""Wrapper function to call `count()` on wrangler's `fit_transform` to enforce computation on lazily evaluated pyspark dataframes. Returns ------- wrapped: callable Wrapp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PySparkBaseProfiler:
"""Define common methods for pyspark profiler."""
def _wrap_fit_transform(self) -> Callable:
"""Wrapper function to call `count()` on wrangler's `fit_transform` to enforce computation on lazily evaluated pyspark dataframes. Returns ------- wrapped: callable Wrapped `fit_trans... | the_stack_v2_python_sparse | src/pywrangler/pyspark/benchmark.py | mansenfranzen/pywrangler | train | 15 |
15a52e613ca529ef39b8b96e2ad9ef34659bd067 | [
"self.cluster_dir = cluster_dir\nself.year_id = year_id\nself.input_me = input_me\nself.output_me = output_me\nself.conn_def = 'cod'\nself.gbd_round = 4",
"query = 'SELECT location_id, most_detailed FROM shared.location_hierarchy_history WHERE location_set_version_id=(SELECT location_set_version_id FROM {DATABASE... | <|body_start_0|>
self.cluster_dir = cluster_dir
self.year_id = year_id
self.input_me = input_me
self.output_me = output_me
self.conn_def = 'cod'
self.gbd_round = 4
<|end_body_0|>
<|body_start_1|>
query = 'SELECT location_id, most_detailed FROM shared.location_hie... | Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base:
def __init__(self, cluster_dir, year_id, input_me, output_me):
"""This class incorporates all the functions that all the specific causes use, but all in different sequence"""
<|body_0|>
def get_locations(self, location_set_id):
"""Pulls the location hierarchy u... | stack_v2_sparse_classes_36k_train_003995 | 4,519 | no_license | [
{
"docstring": "This class incorporates all the functions that all the specific causes use, but all in different sequence",
"name": "__init__",
"signature": "def __init__(self, cluster_dir, year_id, input_me, output_me)"
},
{
"docstring": "Pulls the location hierarchy upon which this code is to ... | 6 | stack_v2_sparse_classes_30k_train_002024 | Implement the Python class `Base` described below.
Class description:
Implement the Base class.
Method signatures and docstrings:
- def __init__(self, cluster_dir, year_id, input_me, output_me): This class incorporates all the functions that all the specific causes use, but all in different sequence
- def get_locatio... | Implement the Python class `Base` described below.
Class description:
Implement the Base class.
Method signatures and docstrings:
- def __init__(self, cluster_dir, year_id, input_me, output_me): This class incorporates all the functions that all the specific causes use, but all in different sequence
- def get_locatio... | 746ea5fb76a9c049c37a8c15aa089c041a90a6d5 | <|skeleton|>
class Base:
def __init__(self, cluster_dir, year_id, input_me, output_me):
"""This class incorporates all the functions that all the specific causes use, but all in different sequence"""
<|body_0|>
def get_locations(self, location_set_id):
"""Pulls the location hierarchy u... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Base:
def __init__(self, cluster_dir, year_id, input_me, output_me):
"""This class incorporates all the functions that all the specific causes use, but all in different sequence"""
self.cluster_dir = cluster_dir
self.year_id = year_id
self.input_me = input_me
self.outpu... | the_stack_v2_python_sparse | nonfatal_code/obstetric_fistula/fistula_zero_out_locations_GATHER.py | Nermin-Ghith/ihme-modeling | train | 0 | |
3e21061207c8af6753ebbaa3da10e0d0d988afc1 | [
"lti = LTI(request_type='any', role_type='any')\ntry:\n lti.verify(request)\nexcept LTIException:\n return render(request, 'lti_failure.html')\nif not request.user.is_authenticated:\n try:\n lti_user = login_existing_user(request)\n except EmailAddress.DoesNotExist:\n lti_email = request.P... | <|body_start_0|>
lti = LTI(request_type='any', role_type='any')
try:
lti.verify(request)
except LTIException:
return render(request, 'lti_failure.html')
if not request.user.is_authenticated:
try:
lti_user = login_existing_user(request)
... | LtiInitializerView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LtiInitializerView:
def dispatch(self, request, *args, **kwargs):
"""Handle LTI verification and user authentication"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Handle the POST coming directly from Canvas"""
<|body_1|>
def create_lti_user(... | stack_v2_sparse_classes_36k_train_003996 | 4,866 | permissive | [
{
"docstring": "Handle LTI verification and user authentication",
"name": "dispatch",
"signature": "def dispatch(self, request, *args, **kwargs)"
},
{
"docstring": "Handle the POST coming directly from Canvas",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
},
... | 6 | stack_v2_sparse_classes_30k_train_011769 | Implement the Python class `LtiInitializerView` described below.
Class description:
Implement the LtiInitializerView class.
Method signatures and docstrings:
- def dispatch(self, request, *args, **kwargs): Handle LTI verification and user authentication
- def post(self, request, *args, **kwargs): Handle the POST comi... | Implement the Python class `LtiInitializerView` described below.
Class description:
Implement the LtiInitializerView class.
Method signatures and docstrings:
- def dispatch(self, request, *args, **kwargs): Handle LTI verification and user authentication
- def post(self, request, *args, **kwargs): Handle the POST comi... | f44773bcf7695f4f73f0cd71daed7767902bcfd4 | <|skeleton|>
class LtiInitializerView:
def dispatch(self, request, *args, **kwargs):
"""Handle LTI verification and user authentication"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Handle the POST coming directly from Canvas"""
<|body_1|>
def create_lti_user(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LtiInitializerView:
def dispatch(self, request, *args, **kwargs):
"""Handle LTI verification and user authentication"""
lti = LTI(request_type='any', role_type='any')
try:
lti.verify(request)
except LTIException:
return render(request, 'lti_failure.html'... | the_stack_v2_python_sparse | lti/views.py | Hedera-Lang-Learn/hedera | train | 9 | |
7cd179f24f63127f2a28393bc7a5f17f23c8faf7 | [
"def dfs(l, r):\n if l is None and r is None:\n return True\n if l is None or r is None:\n return False\n return l.val == r.val and dfs(l.left, r.left) and dfs(l.right, r.right)\nreturn dfs(p, q)",
"from collections import deque\nq1 = deque([p])\nq2 = deque([q])\nwhile q1 and q2:\n l = q... | <|body_start_0|>
def dfs(l, r):
if l is None and r is None:
return True
if l is None or r is None:
return False
return l.val == r.val and dfs(l.left, r.left) and dfs(l.right, r.right)
return dfs(p, q)
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSameTree(self, p, q) -> bool:
"""DFS, Time: O(n), Space: O(n)"""
<|body_0|>
def isSameTree(self, p, q) -> bool:
"""BFS, Time: O(n), Space: O(n)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def dfs(l, r):
if l is None a... | stack_v2_sparse_classes_36k_train_003997 | 1,295 | no_license | [
{
"docstring": "DFS, Time: O(n), Space: O(n)",
"name": "isSameTree",
"signature": "def isSameTree(self, p, q) -> bool"
},
{
"docstring": "BFS, Time: O(n), Space: O(n)",
"name": "isSameTree",
"signature": "def isSameTree(self, p, q) -> bool"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSameTree(self, p, q) -> bool: DFS, Time: O(n), Space: O(n)
- def isSameTree(self, p, q) -> bool: BFS, Time: O(n), Space: O(n) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSameTree(self, p, q) -> bool: DFS, Time: O(n), Space: O(n)
- def isSameTree(self, p, q) -> bool: BFS, Time: O(n), Space: O(n)
<|skeleton|>
class Solution:
def isSameT... | 72136e3487d239f5b37e2d6393e034262a6bf599 | <|skeleton|>
class Solution:
def isSameTree(self, p, q) -> bool:
"""DFS, Time: O(n), Space: O(n)"""
<|body_0|>
def isSameTree(self, p, q) -> bool:
"""BFS, Time: O(n), Space: O(n)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isSameTree(self, p, q) -> bool:
"""DFS, Time: O(n), Space: O(n)"""
def dfs(l, r):
if l is None and r is None:
return True
if l is None or r is None:
return False
return l.val == r.val and dfs(l.left, r.left) and ... | the_stack_v2_python_sparse | python/100-Same Tree.py | cwza/leetcode | train | 0 | |
f6b1e71ade3babfa4e6a0ca4f0478177dddbdc0a | [
"self.lat = float(lat)\nself.long = float(int)\nsuper(albedo, self).__init__(var, bad_val)",
"if abs(self.variable) >= self.bad_val:\n self.result = self.bad_val\n return\nif abs(self.windspeed) >= 0.3:\n pos_correction = 1 + 0.066 * 0.2 * self.windspeed / (0.066 + 0.2 * self.windspeed)\n neg_correcti... | <|body_start_0|>
self.lat = float(lat)
self.long = float(int)
super(albedo, self).__init__(var, bad_val)
<|end_body_0|>
<|body_start_1|>
if abs(self.variable) >= self.bad_val:
self.result = self.bad_val
return
if abs(self.windspeed) >= 0.3:
po... | This class represents a netrad function | albedo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class albedo:
"""This class represents a netrad function"""
def __init__(self, var, lat, long, bad_val=6999):
"""Class initializer Arguments: var: (convertible to float) the domain value lat: (convertible to float) latitude in decimal degrees long: (convertible to float) longitude in decim... | stack_v2_sparse_classes_36k_train_003998 | 17,830 | no_license | [
{
"docstring": "Class initializer Arguments: var: (convertible to float) the domain value lat: (convertible to float) latitude in decimal degrees long: (convertible to float) longitude in decimal degrees values bad_val: (convertible to int) the value to indicate a bad data item",
"name": "__init__",
"si... | 2 | stack_v2_sparse_classes_30k_train_002132 | Implement the Python class `albedo` described below.
Class description:
This class represents a netrad function
Method signatures and docstrings:
- def __init__(self, var, lat, long, bad_val=6999): Class initializer Arguments: var: (convertible to float) the domain value lat: (convertible to float) latitude in decima... | Implement the Python class `albedo` described below.
Class description:
This class represents a netrad function
Method signatures and docstrings:
- def __init__(self, var, lat, long, bad_val=6999): Class initializer Arguments: var: (convertible to float) the domain value lat: (convertible to float) latitude in decima... | 95d0c102d649c5b028d262f5254106f997a7c77a | <|skeleton|>
class albedo:
"""This class represents a netrad function"""
def __init__(self, var, lat, long, bad_val=6999):
"""Class initializer Arguments: var: (convertible to float) the domain value lat: (convertible to float) latitude in decimal degrees long: (convertible to float) longitude in decim... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class albedo:
"""This class represents a netrad function"""
def __init__(self, var, lat, long, bad_val=6999):
"""Class initializer Arguments: var: (convertible to float) the domain value lat: (convertible to float) latitude in decimal degrees long: (convertible to float) longitude in decimal degrees va... | the_stack_v2_python_sparse | csv_lib/equations.py | rwspicer/csv_utilities | train | 1 |
e7572525865d74c9e8c83c160014169331634159 | [
"errors = []\nres = list(request_helper.MakeRequests(requests=[(self.compute.addresses, 'Get', self.messages.ComputeAddressesGetRequest(address=address_ref.Name(), project=address_ref.project, region=address_ref.region))], http=self.http, batch_url=self.batch_url, errors=errors, custom_get_requests=None))\nif error... | <|body_start_0|>
errors = []
res = list(request_helper.MakeRequests(requests=[(self.compute.addresses, 'Get', self.messages.ComputeAddressesGetRequest(address=address_ref.Name(), project=address_ref.project, region=address_ref.region))], http=self.http, batch_url=self.batch_url, errors=errors, custom_ge... | Mixin class for expanding address names to IP address. | AddressExpander | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddressExpander:
"""Mixin class for expanding address names to IP address."""
def GetAddress(self, address_ref):
"""Returns the address resource corresponding to the given reference."""
<|body_0|>
def ExpandAddressFlag(self, args, region):
"""Resolves the --addre... | stack_v2_sparse_classes_36k_train_003999 | 3,171 | permissive | [
{
"docstring": "Returns the address resource corresponding to the given reference.",
"name": "GetAddress",
"signature": "def GetAddress(self, address_ref)"
},
{
"docstring": "Resolves the --address flag value. If the value of --address is a name, the regional address is queried. Args: args: The ... | 2 | null | Implement the Python class `AddressExpander` described below.
Class description:
Mixin class for expanding address names to IP address.
Method signatures and docstrings:
- def GetAddress(self, address_ref): Returns the address resource corresponding to the given reference.
- def ExpandAddressFlag(self, args, region):... | Implement the Python class `AddressExpander` described below.
Class description:
Mixin class for expanding address names to IP address.
Method signatures and docstrings:
- def GetAddress(self, address_ref): Returns the address resource corresponding to the given reference.
- def ExpandAddressFlag(self, args, region):... | d379afa2db3582d5c3be652165f0e9e2e0c154c6 | <|skeleton|>
class AddressExpander:
"""Mixin class for expanding address names to IP address."""
def GetAddress(self, address_ref):
"""Returns the address resource corresponding to the given reference."""
<|body_0|>
def ExpandAddressFlag(self, args, region):
"""Resolves the --addre... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddressExpander:
"""Mixin class for expanding address names to IP address."""
def GetAddress(self, address_ref):
"""Returns the address resource corresponding to the given reference."""
errors = []
res = list(request_helper.MakeRequests(requests=[(self.compute.addresses, 'Get', se... | the_stack_v2_python_sparse | y/google-cloud-sdk/lib/googlecloudsdk/compute/lib/addresses_utils.py | ychen820/microblog | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.