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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0d0359bd81af146d883dd4119fa71dc2fe4897f9 | [
"n = len(nums)\nif n == 0:\n return 0\ndp = [1] * n\nfor i in range(n):\n for j in range(i):\n if nums[i] > nums[j]:\n dp[i] = max(dp[i], dp[j] + 1)\nreturn max(dp)",
"def binary_search(a, num):\n l, r = (0, len(a) - 1)\n while l <= r:\n m = l + (r - l) // 2\n if a[m - ... | <|body_start_0|>
n = len(nums)
if n == 0:
return 0
dp = [1] * n
for i in range(n):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
<|end_body_0|>
<|body_start_1|>
def binary... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
"""DP Running Time: O(n^2) where n is the length of nums."""
<|body_0|>
def lengthOfLIS_2(self, nums: List[int]) -> int:
"""Binary search Running Time: O(n log n) where n is the length of nums."""
<|bod... | stack_v2_sparse_classes_36k_train_002700 | 1,260 | permissive | [
{
"docstring": "DP Running Time: O(n^2) where n is the length of nums.",
"name": "lengthOfLIS",
"signature": "def lengthOfLIS(self, nums: List[int]) -> int"
},
{
"docstring": "Binary search Running Time: O(n log n) where n is the length of nums.",
"name": "lengthOfLIS_2",
"signature": "d... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums: List[int]) -> int: DP Running Time: O(n^2) where n is the length of nums.
- def lengthOfLIS_2(self, nums: List[int]) -> int: Binary search Running Tim... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums: List[int]) -> int: DP Running Time: O(n^2) where n is the length of nums.
- def lengthOfLIS_2(self, nums: List[int]) -> int: Binary search Running Tim... | 4a508a982b125a3a90ea893ae70863df7c99cc70 | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
"""DP Running Time: O(n^2) where n is the length of nums."""
<|body_0|>
def lengthOfLIS_2(self, nums: List[int]) -> int:
"""Binary search Running Time: O(n log n) where n is the length of nums."""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
"""DP Running Time: O(n^2) where n is the length of nums."""
n = len(nums)
if n == 0:
return 0
dp = [1] * n
for i in range(n):
for j in range(i):
if nums[i] > nums[j]:
... | the_stack_v2_python_sparse | solutions/300_longest_increasing_subsequence.py | YiqunPeng/leetcode_pro | train | 0 | |
38cfe0f5bda3e41a51628ae02c58ccc004238a8e | [
"res = []\nif root:\n stk = [root]\n while stk:\n x = stk.pop()\n res.append(' ')\n if x:\n res.append(str(x.val))\n stk.insert(0, x.left)\n stk.insert(0, x.right)\n else:\n res.append('None')\nreturn ''.join(res)",
"print(data)\nif not... | <|body_start_0|>
res = []
if root:
stk = [root]
while stk:
x = stk.pop()
res.append(' ')
if x:
res.append(str(x.val))
stk.insert(0, x.left)
stk.insert(0, x.right)
... | 序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。 请设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。 示例: 你可以将以下二叉树: 1 / 2 3 / 4 5 序列化为 "[1,2,3,null,null,4,5]" 提示: 这与 LeetCode 目前使用的方式一致,详情请参阅 LeetCode 序列化二叉树的格式。你并非必须采取这种方式,你也可以采用其他的方法解决这个问题。 说明... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
"""序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。 请设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。 示例: 你可以将以下二叉树: 1 / 2 3 / 4 5 序列化为 "[1,2,3,null,null,4,5]" 提示: 这与 LeetCode 目前使用的方式一致,详情请参阅 LeetCode 序列化二叉树的格式。... | stack_v2_sparse_classes_36k_train_002701 | 22,676 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。 请设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。 示例: 你可以将以下二叉树: 1 / 2 3 / 4 5 序列化为 "[1,2,3,null,null,4,5]" 提示: 这与 LeetC... | Implement the Python class `Codec` described below.
Class description:
序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。 请设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。 示例: 你可以将以下二叉树: 1 / 2 3 / 4 5 序列化为 "[1,2,3,null,null,4,5]" 提示: 这与 LeetC... | dbe8eb449e5b112a71bc1cd4eabfd138304de4a3 | <|skeleton|>
class Codec:
"""序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。 请设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。 示例: 你可以将以下二叉树: 1 / 2 3 / 4 5 序列化为 "[1,2,3,null,null,4,5]" 提示: 这与 LeetCode 目前使用的方式一致,详情请参阅 LeetCode 序列化二叉树的格式。... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
"""序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。 请设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。 示例: 你可以将以下二叉树: 1 / 2 3 / 4 5 序列化为 "[1,2,3,null,null,4,5]" 提示: 这与 LeetCode 目前使用的方式一致,详情请参阅 LeetCode 序列化二叉树的格式。你并非必须采取这种方式,你... | the_stack_v2_python_sparse | leetcode/leetcode_special.py | Rivarrl/leetcode_python | train | 3 |
09ceeff88db61da4ecf6a84878bedc5302bdf39a | [
"if self.request.version == 'v6':\n return StrikeDetailsSerializerV6\nelif self.request.version == 'v7':\n return StrikeDetailsSerializerV6",
"if request.version == 'v6':\n return self.get_impl(request, strike_id)\nelif request.version == 'v7':\n return self.get_impl(request, strike_id)\nraise Http404... | <|body_start_0|>
if self.request.version == 'v6':
return StrikeDetailsSerializerV6
elif self.request.version == 'v7':
return StrikeDetailsSerializerV6
<|end_body_0|>
<|body_start_1|>
if request.version == 'v6':
return self.get_impl(request, strike_id)
... | This view is the endpoint for retrieving/updating details of a Strike process. | StrikeDetailsView | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StrikeDetailsView:
"""This view is the endpoint for retrieving/updating details of a Strike process."""
def get_serializer_class(self):
"""Returns the appropriate serializer based off the requests version of the REST API"""
<|body_0|>
def get(self, request, strike_id):
... | stack_v2_sparse_classes_36k_train_002702 | 30,689 | permissive | [
{
"docstring": "Returns the appropriate serializer based off the requests version of the REST API",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "Determine api version and call specific method :param request: the HTTP POST request :type request:... | 5 | stack_v2_sparse_classes_30k_train_008176 | Implement the Python class `StrikeDetailsView` described below.
Class description:
This view is the endpoint for retrieving/updating details of a Strike process.
Method signatures and docstrings:
- def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API
- def ... | Implement the Python class `StrikeDetailsView` described below.
Class description:
This view is the endpoint for retrieving/updating details of a Strike process.
Method signatures and docstrings:
- def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API
- def ... | 28618aee07ceed9e4a6eb7b8d0e6f05b31d8fd6b | <|skeleton|>
class StrikeDetailsView:
"""This view is the endpoint for retrieving/updating details of a Strike process."""
def get_serializer_class(self):
"""Returns the appropriate serializer based off the requests version of the REST API"""
<|body_0|>
def get(self, request, strike_id):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StrikeDetailsView:
"""This view is the endpoint for retrieving/updating details of a Strike process."""
def get_serializer_class(self):
"""Returns the appropriate serializer based off the requests version of the REST API"""
if self.request.version == 'v6':
return StrikeDetails... | the_stack_v2_python_sparse | scale/ingest/views.py | kfconsultant/scale | train | 0 |
4f19dc3f07891d157bef245ce520757a5c7edd35 | [
"soup = BeautifulSoup(content, 'html.parser', from_encoding='utf-8')\nurls = self._get_new_urls(page_url, soup)\ndata = self._get_new_data(page_url, soup)\nreturn (urls, data)",
"new_urls = []\nlinks = soup.find_all('a', href=re.compile('item/\\\\w+\\\\.?(html|htm)?'))\nfor link in links:\n url = link['href']\... | <|body_start_0|>
soup = BeautifulSoup(content, 'html.parser', from_encoding='utf-8')
urls = self._get_new_urls(page_url, soup)
data = self._get_new_data(page_url, soup)
return (urls, data)
<|end_body_0|>
<|body_start_1|>
new_urls = []
links = soup.find_all('a', href=re.c... | 网页解析器 | HtmlParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HtmlParser:
"""网页解析器"""
def parse(self, page_url, content):
"""用bs解析网页内容"""
<|body_0|>
def _get_new_urls(self, page_url, soup):
"""从网页中提取新URL"""
<|body_1|>
def _get_new_data(self, page_url, soup):
"""从网页中提取价值数据"""
<|body_2|>
<|end_sk... | stack_v2_sparse_classes_36k_train_002703 | 2,107 | no_license | [
{
"docstring": "用bs解析网页内容",
"name": "parse",
"signature": "def parse(self, page_url, content)"
},
{
"docstring": "从网页中提取新URL",
"name": "_get_new_urls",
"signature": "def _get_new_urls(self, page_url, soup)"
},
{
"docstring": "从网页中提取价值数据",
"name": "_get_new_data",
"signatu... | 3 | stack_v2_sparse_classes_30k_train_011924 | Implement the Python class `HtmlParser` described below.
Class description:
网页解析器
Method signatures and docstrings:
- def parse(self, page_url, content): 用bs解析网页内容
- def _get_new_urls(self, page_url, soup): 从网页中提取新URL
- def _get_new_data(self, page_url, soup): 从网页中提取价值数据 | Implement the Python class `HtmlParser` described below.
Class description:
网页解析器
Method signatures and docstrings:
- def parse(self, page_url, content): 用bs解析网页内容
- def _get_new_urls(self, page_url, soup): 从网页中提取新URL
- def _get_new_data(self, page_url, soup): 从网页中提取价值数据
<|skeleton|>
class HtmlParser:
"""网页解析器""... | 8b217a7a9d85e80e3b513727ca760e095173e263 | <|skeleton|>
class HtmlParser:
"""网页解析器"""
def parse(self, page_url, content):
"""用bs解析网页内容"""
<|body_0|>
def _get_new_urls(self, page_url, soup):
"""从网页中提取新URL"""
<|body_1|>
def _get_new_data(self, page_url, soup):
"""从网页中提取价值数据"""
<|body_2|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HtmlParser:
"""网页解析器"""
def parse(self, page_url, content):
"""用bs解析网页内容"""
soup = BeautifulSoup(content, 'html.parser', from_encoding='utf-8')
urls = self._get_new_urls(page_url, soup)
data = self._get_new_data(page_url, soup)
return (urls, data)
def _get_new... | the_stack_v2_python_sparse | baike_crawler/html_parser.py | buptxiaomiao/python | train | 0 |
10dda68f5c23fb9f11c9cef223d680df6502d150 | [
"username_mappings = request.data.get('username_mappings')\nif not self._has_valid_schema(username_mappings):\n raise ParseError('Request data does not match schema')\nsuccessful_replacements, failed_replacements = ([], [])\nfor username_pair in username_mappings:\n current_username = list(username_pair.keys(... | <|body_start_0|>
username_mappings = request.data.get('username_mappings')
if not self._has_valid_schema(username_mappings):
raise ParseError('Request data does not match schema')
successful_replacements, failed_replacements = ([], [])
for username_pair in username_mappings:
... | WARNING: This API is only meant to be used as part of a larger job that updates usernames across all services. DO NOT run this alone or users will not match across the system and things will be broken. API will recieve a list of current usernames and their new username. POST /api/discussion/v1/accounts/replace_username... | ReplaceUsernamesView | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReplaceUsernamesView:
"""WARNING: This API is only meant to be used as part of a larger job that updates usernames across all services. DO NOT run this alone or users will not match across the system and things will be broken. API will recieve a list of current usernames and their new username. P... | stack_v2_sparse_classes_36k_train_002704 | 34,067 | permissive | [
{
"docstring": "Implements the username replacement endpoint",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "Replaces the current username with the new username in the forums service",
"name": "_replace_username",
"signature": "def _replace_username(self, curr... | 3 | null | Implement the Python class `ReplaceUsernamesView` described below.
Class description:
WARNING: This API is only meant to be used as part of a larger job that updates usernames across all services. DO NOT run this alone or users will not match across the system and things will be broken. API will recieve a list of curr... | Implement the Python class `ReplaceUsernamesView` described below.
Class description:
WARNING: This API is only meant to be used as part of a larger job that updates usernames across all services. DO NOT run this alone or users will not match across the system and things will be broken. API will recieve a list of curr... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class ReplaceUsernamesView:
"""WARNING: This API is only meant to be used as part of a larger job that updates usernames across all services. DO NOT run this alone or users will not match across the system and things will be broken. API will recieve a list of current usernames and their new username. P... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReplaceUsernamesView:
"""WARNING: This API is only meant to be used as part of a larger job that updates usernames across all services. DO NOT run this alone or users will not match across the system and things will be broken. API will recieve a list of current usernames and their new username. POST /api/disc... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/discussion/rest_api/views.py | luque/better-ways-of-thinking-about-software | train | 3 |
3fa5d64b61e3b70681364fe428f0faada1c2c08d | [
"self.startFormatted = self.context.start.strftime('%-d %B %Y')\nself.endFormatted = self.context.end.strftime('%-d %B %Y')\nself.period = self.startFormatted + ' - ' + self.endFormatted\nif self.context.start.year == self.context.end.year:\n if self.context.start.month == self.context.end.month:\n self.p... | <|body_start_0|>
self.startFormatted = self.context.start.strftime('%-d %B %Y')
self.endFormatted = self.context.end.strftime('%-d %B %Y')
self.period = self.startFormatted + ' - ' + self.endFormatted
if self.context.start.year == self.context.end.year:
if self.context.start.... | Default view (called "@@view"") for a exhibition. The associated template is found in exhibition_templates/view.pt. | View | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class View:
"""Default view (called "@@view"") for a exhibition. The associated template is found in exhibition_templates/view.pt."""
def update(self):
"""Prepare information for the template"""
<|body_0|>
def images(self):
"""Return catalog search results of images to... | stack_v2_sparse_classes_36k_train_002705 | 3,830 | no_license | [
{
"docstring": "Prepare information for the template",
"name": "update",
"signature": "def update(self)"
},
{
"docstring": "Return catalog search results of images to show",
"name": "images",
"signature": "def images(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000959 | Implement the Python class `View` described below.
Class description:
Default view (called "@@view"") for a exhibition. The associated template is found in exhibition_templates/view.pt.
Method signatures and docstrings:
- def update(self): Prepare information for the template
- def images(self): Return catalog search... | Implement the Python class `View` described below.
Class description:
Default view (called "@@view"") for a exhibition. The associated template is found in exhibition_templates/view.pt.
Method signatures and docstrings:
- def update(self): Prepare information for the template
- def images(self): Return catalog search... | da53064c6e09573676ca1cc6f0a3397808c5329f | <|skeleton|>
class View:
"""Default view (called "@@view"") for a exhibition. The associated template is found in exhibition_templates/view.pt."""
def update(self):
"""Prepare information for the template"""
<|body_0|>
def images(self):
"""Return catalog search results of images to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class View:
"""Default view (called "@@view"") for a exhibition. The associated template is found in exhibition_templates/view.pt."""
def update(self):
"""Prepare information for the template"""
self.startFormatted = self.context.start.strftime('%-d %B %Y')
self.endFormatted = self.cont... | the_stack_v2_python_sparse | irwilot.content/irwilot/content/exhibition.py | kbat/obonato | train | 0 |
0ad0e087b5794c4e6fa536447cfd3b7a71a79818 | [
"self.wifi_mac = wifi_mac\nself.id = id\nself.serial = serial\nself.pin = pin",
"if dictionary is None:\n return None\nwifi_mac = dictionary.get('wifiMac')\nid = dictionary.get('id')\nserial = dictionary.get('serial')\npin = dictionary.get('pin')\nreturn cls(wifi_mac, id, serial, pin)"
] | <|body_start_0|>
self.wifi_mac = wifi_mac
self.id = id
self.serial = serial
self.pin = pin
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
wifi_mac = dictionary.get('wifiMac')
id = dictionary.get('id')
serial = dictionary.ge... | Implementation of the 'wipeNetworkSmDevice' model. TODO: type model description here. Attributes: wifi_mac (string): The wifiMac of the device to be wiped. id (string): The id of the device to be wiped. serial (string): The serial of the device to be wiped. pin (int): The pin number (a six digit value) for wiping a mac... | WipeNetworkSmDeviceModel | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WipeNetworkSmDeviceModel:
"""Implementation of the 'wipeNetworkSmDevice' model. TODO: type model description here. Attributes: wifi_mac (string): The wifiMac of the device to be wiped. id (string): The id of the device to be wiped. serial (string): The serial of the device to be wiped. pin (int):... | stack_v2_sparse_classes_36k_train_002706 | 2,124 | permissive | [
{
"docstring": "Constructor for the WipeNetworkSmDeviceModel class",
"name": "__init__",
"signature": "def __init__(self, wifi_mac=None, id=None, serial=None, pin=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representat... | 2 | null | Implement the Python class `WipeNetworkSmDeviceModel` described below.
Class description:
Implementation of the 'wipeNetworkSmDevice' model. TODO: type model description here. Attributes: wifi_mac (string): The wifiMac of the device to be wiped. id (string): The id of the device to be wiped. serial (string): The seria... | Implement the Python class `WipeNetworkSmDeviceModel` described below.
Class description:
Implementation of the 'wipeNetworkSmDevice' model. TODO: type model description here. Attributes: wifi_mac (string): The wifiMac of the device to be wiped. id (string): The id of the device to be wiped. serial (string): The seria... | 9894089eb013318243ae48869cc5130eb37f80c0 | <|skeleton|>
class WipeNetworkSmDeviceModel:
"""Implementation of the 'wipeNetworkSmDevice' model. TODO: type model description here. Attributes: wifi_mac (string): The wifiMac of the device to be wiped. id (string): The id of the device to be wiped. serial (string): The serial of the device to be wiped. pin (int):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WipeNetworkSmDeviceModel:
"""Implementation of the 'wipeNetworkSmDevice' model. TODO: type model description here. Attributes: wifi_mac (string): The wifiMac of the device to be wiped. id (string): The id of the device to be wiped. serial (string): The serial of the device to be wiped. pin (int): The pin numb... | the_stack_v2_python_sparse | meraki_sdk/models/wipe_network_sm_device_model.py | RaulCatalano/meraki-python-sdk | train | 1 |
e3e896be8568f3821d24c9de516942636c08ed72 | [
"self.lower = lower\nself.specials = SPECIAL_TOKENS\nself.lang = lang\nself.pre_id = []\nself.post_id = []\nif prepend_bos:\n self.pre_id.append(self.specials.BOS.value)\nif append_eos:\n self.post_id.append(self.specials.EOS.value)\nself.nlp = self.get_nlp(name=lang, specials=specials)",
"nlp = spacy.load(... | <|body_start_0|>
self.lower = lower
self.specials = SPECIAL_TOKENS
self.lang = lang
self.pre_id = []
self.post_id = []
if prepend_bos:
self.pre_id.append(self.specials.BOS.value)
if append_eos:
self.post_id.append(self.specials.EOS.value)
... | SpacyTokenizer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpacyTokenizer:
def __init__(self, lower: bool=True, prepend_bos: bool=False, append_eos: bool=False, specials: Optional[SPECIAL_TOKENS]=SPECIAL_TOKENS, lang: str='en_core_web_sm'):
"""Apply spacy tokenizer to str Args: lower (bool): Lowercase string. Defaults to True. prepend_bos (bool)... | stack_v2_sparse_classes_36k_train_002707 | 8,041 | permissive | [
{
"docstring": "Apply spacy tokenizer to str Args: lower (bool): Lowercase string. Defaults to True. prepend_bos (bool): Prepend BOS for seq2seq. Defaults to False. append_eos (bool): Append EOS for seq2seq. Defaults to False. specials (Optional[SPECIAL_TOKENS]): Special tokens. Defaults to SPECIAL_TOKENS. lang... | 3 | stack_v2_sparse_classes_30k_val_000915 | Implement the Python class `SpacyTokenizer` described below.
Class description:
Implement the SpacyTokenizer class.
Method signatures and docstrings:
- def __init__(self, lower: bool=True, prepend_bos: bool=False, append_eos: bool=False, specials: Optional[SPECIAL_TOKENS]=SPECIAL_TOKENS, lang: str='en_core_web_sm'): ... | Implement the Python class `SpacyTokenizer` described below.
Class description:
Implement the SpacyTokenizer class.
Method signatures and docstrings:
- def __init__(self, lower: bool=True, prepend_bos: bool=False, append_eos: bool=False, specials: Optional[SPECIAL_TOKENS]=SPECIAL_TOKENS, lang: str='en_core_web_sm'): ... | e4987310ed277abdec19462bdd749e2e7a000bec | <|skeleton|>
class SpacyTokenizer:
def __init__(self, lower: bool=True, prepend_bos: bool=False, append_eos: bool=False, specials: Optional[SPECIAL_TOKENS]=SPECIAL_TOKENS, lang: str='en_core_web_sm'):
"""Apply spacy tokenizer to str Args: lower (bool): Lowercase string. Defaults to True. prepend_bos (bool)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpacyTokenizer:
def __init__(self, lower: bool=True, prepend_bos: bool=False, append_eos: bool=False, specials: Optional[SPECIAL_TOKENS]=SPECIAL_TOKENS, lang: str='en_core_web_sm'):
"""Apply spacy tokenizer to str Args: lower (bool): Lowercase string. Defaults to True. prepend_bos (bool): Prepend BOS ... | the_stack_v2_python_sparse | slp/data/transforms.py | georgepar/slp | train | 26 | |
130ee80c384f85d2dc8d0e6909bad75f629f5641 | [
"self.log = logging.getLogger('lapis.vidme')\nself.useragent = useragent\nself.username = vidme_user\nself.password = vidme_password\nself.headers = {'User-Agent': self.useragent}",
"self.log.info('Logging into vid.me with username %s...', self.username)\nresponse = requests.post('https://api.vid.me/auth/create',... | <|body_start_0|>
self.log = logging.getLogger('lapis.vidme')
self.useragent = useragent
self.username = vidme_user
self.password = vidme_password
self.headers = {'User-Agent': self.useragent}
<|end_body_0|>
<|body_start_1|>
self.log.info('Logging into vid.me with usernam... | A vid.me export plugin. Here's where magic turns to sorcery. Will upload a single video (currently supported via tumblr). You must have a vid.me account for this to be used. | VidmePlugin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VidmePlugin:
"""A vid.me export plugin. Here's where magic turns to sorcery. Will upload a single video (currently supported via tumblr). You must have a vid.me account for this to be used."""
def __init__(self, useragent: str, vidme_user: str='', vidme_password: str='', **options):
... | stack_v2_sparse_classes_36k_train_002708 | 5,786 | permissive | [
{
"docstring": "Initialize the vid.me export API. :param useragent: The useragent to use for the vid.me API. :param vidme_user: The username with which to login to vid.me :param vidme_password: The password with which to login to vid.me :param options: Other passed options. Unused.",
"name": "__init__",
... | 4 | stack_v2_sparse_classes_30k_train_021187 | Implement the Python class `VidmePlugin` described below.
Class description:
A vid.me export plugin. Here's where magic turns to sorcery. Will upload a single video (currently supported via tumblr). You must have a vid.me account for this to be used.
Method signatures and docstrings:
- def __init__(self, useragent: s... | Implement the Python class `VidmePlugin` described below.
Class description:
A vid.me export plugin. Here's where magic turns to sorcery. Will upload a single video (currently supported via tumblr). You must have a vid.me account for this to be used.
Method signatures and docstrings:
- def __init__(self, useragent: s... | 29503bb70b7b9e47a5cea1ea03098543b1a01efb | <|skeleton|>
class VidmePlugin:
"""A vid.me export plugin. Here's where magic turns to sorcery. Will upload a single video (currently supported via tumblr). You must have a vid.me account for this to be used."""
def __init__(self, useragent: str, vidme_user: str='', vidme_password: str='', **options):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VidmePlugin:
"""A vid.me export plugin. Here's where magic turns to sorcery. Will upload a single video (currently supported via tumblr). You must have a vid.me account for this to be used."""
def __init__(self, useragent: str, vidme_user: str='', vidme_password: str='', **options):
"""Initialize... | the_stack_v2_python_sparse | plugins/vidme.py | spiral6/VelvetBot | train | 0 |
9137b4b1bc0d434921790dbb3b1ea233760b6e87 | [
"i, j = (0, 0)\nwhile i < len(nums1) and j < len(nums2):\n if nums1[i] == nums2[j]:\n return nums1[i]\n elif nums1[i] < nums2[j]:\n i += 1\n else:\n j += 1\nreturn -1",
"s1, s2 = (set(nums1), set(nums2))\nres = s1 & s2\nif res:\n return min(res)\nreturn -1"
] | <|body_start_0|>
i, j = (0, 0)
while i < len(nums1) and j < len(nums2):
if nums1[i] == nums2[j]:
return nums1[i]
elif nums1[i] < nums2[j]:
i += 1
else:
j += 1
return -1
<|end_body_0|>
<|body_start_1|>
s1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getCommon(self, nums1: List[int], nums2: List[int]) -> int:
"""数组已经排序"""
<|body_0|>
def getCommon2(self, nums1: List[int], nums2: List[int]) -> int:
"""数组未排序"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
i, j = (0, 0)
while i... | stack_v2_sparse_classes_36k_train_002709 | 864 | no_license | [
{
"docstring": "数组已经排序",
"name": "getCommon",
"signature": "def getCommon(self, nums1: List[int], nums2: List[int]) -> int"
},
{
"docstring": "数组未排序",
"name": "getCommon2",
"signature": "def getCommon2(self, nums1: List[int], nums2: List[int]) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getCommon(self, nums1: List[int], nums2: List[int]) -> int: 数组已经排序
- def getCommon2(self, nums1: List[int], nums2: List[int]) -> int: 数组未排序 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getCommon(self, nums1: List[int], nums2: List[int]) -> int: 数组已经排序
- def getCommon2(self, nums1: List[int], nums2: List[int]) -> int: 数组未排序
<|skeleton|>
class Solution:
... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def getCommon(self, nums1: List[int], nums2: List[int]) -> int:
"""数组已经排序"""
<|body_0|>
def getCommon2(self, nums1: List[int], nums2: List[int]) -> int:
"""数组未排序"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def getCommon(self, nums1: List[int], nums2: List[int]) -> int:
"""数组已经排序"""
i, j = (0, 0)
while i < len(nums1) and j < len(nums2):
if nums1[i] == nums2[j]:
return nums1[i]
elif nums1[i] < nums2[j]:
i += 1
el... | the_stack_v2_python_sparse | 4_set/6300. 最小公共值-集合交集.py | 981377660LMT/algorithm-study | train | 225 | |
3bd0246b8c25fb5a7b974efd22fd752518fc5214 | [
"page = self.get_query_param(request, 'page', default=1)\ncontext_data = self.get_context_data(page=page)\nreturn self.render_to_response(context_data)",
"context_data = super().get_context_data(page=page)\nif not News.objects.exists():\n return context_data\np = Paginator(News.objects.all(), self.news_per_pag... | <|body_start_0|>
page = self.get_query_param(request, 'page', default=1)
context_data = self.get_context_data(page=page)
return self.render_to_response(context_data)
<|end_body_0|>
<|body_start_1|>
context_data = super().get_context_data(page=page)
if not News.objects.exists():
... | NewsView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewsView:
def get(self, request, *args, **kwargs):
"""Display ``News`` items with pagination."""
<|body_0|>
def get_context_data(self, page):
"""Method to add pages info to context."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
page = self.get_que... | stack_v2_sparse_classes_36k_train_002710 | 2,744 | permissive | [
{
"docstring": "Display ``News`` items with pagination.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Method to add pages info to context.",
"name": "get_context_data",
"signature": "def get_context_data(self, page)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003347 | Implement the Python class `NewsView` described below.
Class description:
Implement the NewsView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Display ``News`` items with pagination.
- def get_context_data(self, page): Method to add pages info to context. | Implement the Python class `NewsView` described below.
Class description:
Implement the NewsView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Display ``News`` items with pagination.
- def get_context_data(self, page): Method to add pages info to context.
<|skeleton|>
class News... | d1fd8b32cf2065413c19799f45487ed317b85eb1 | <|skeleton|>
class NewsView:
def get(self, request, *args, **kwargs):
"""Display ``News`` items with pagination."""
<|body_0|>
def get_context_data(self, page):
"""Method to add pages info to context."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NewsView:
def get(self, request, *args, **kwargs):
"""Display ``News`` items with pagination."""
page = self.get_query_param(request, 'page', default=1)
context_data = self.get_context_data(page=page)
return self.render_to_response(context_data)
def get_context_data(self, ... | the_stack_v2_python_sparse | apps/news/views.py | deniskrumko/dendynotdead | train | 0 | |
c33a93578cf19ee5556107863d1b3cde312cc1d8 | [
"m_ = m\nif m == n:\n return head\nprev = None\npm, pn, head_last = (head, head, head)\nwhile m - 1 or n:\n if m - 1:\n pm = pm.next\n if m - 2:\n head_last = head_last.next\n m -= 1\n if n:\n pn = pn.next\n n -= 1\np = pm\nwhile pm != pn:\n curr = pm\n p... | <|body_start_0|>
m_ = m
if m == n:
return head
prev = None
pm, pn, head_last = (head, head, head)
while m - 1 or n:
if m - 1:
pm = pm.next
if m - 2:
head_last = head_last.next
m -= 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseBetween(self, head, m, n):
"""my solution time O(N) space O(1) :type head: ListNode :type m: int :type n: int :rtype: ListNode"""
<|body_0|>
def reverseBetween_recursion(self, head, m, n):
"""Back Tracking, hard to understanding Time O(N) Soace O... | stack_v2_sparse_classes_36k_train_002711 | 3,314 | no_license | [
{
"docstring": "my solution time O(N) space O(1) :type head: ListNode :type m: int :type n: int :rtype: ListNode",
"name": "reverseBetween",
"signature": "def reverseBetween(self, head, m, n)"
},
{
"docstring": "Back Tracking, hard to understanding Time O(N) Soace O(N) :type head: ListNode :type... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseBetween(self, head, m, n): my solution time O(N) space O(1) :type head: ListNode :type m: int :type n: int :rtype: ListNode
- def reverseBetween_recursion(self, head, ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseBetween(self, head, m, n): my solution time O(N) space O(1) :type head: ListNode :type m: int :type n: int :rtype: ListNode
- def reverseBetween_recursion(self, head, ... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def reverseBetween(self, head, m, n):
"""my solution time O(N) space O(1) :type head: ListNode :type m: int :type n: int :rtype: ListNode"""
<|body_0|>
def reverseBetween_recursion(self, head, m, n):
"""Back Tracking, hard to understanding Time O(N) Soace O... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseBetween(self, head, m, n):
"""my solution time O(N) space O(1) :type head: ListNode :type m: int :type n: int :rtype: ListNode"""
m_ = m
if m == n:
return head
prev = None
pm, pn, head_last = (head, head, head)
while m - 1 or n:
... | the_stack_v2_python_sparse | LeetCode/LinkedList/92_reverse_linked_list_ii.py | XyK0907/for_work | train | 0 | |
2bc4819e0a1189c0931604543598d3d189b2d284 | [
"low = float('-inf')\ni = -1\nfor p in preorder:\n if p < low:\n return False\n while i >= 0 and p > preorder[i]:\n low = preorder[i]\n i -= 1\n i += 1\n preorder[i] = p\nreturn True",
"stack = []\nlow = float('-inf')\nfor p in preorder:\n if p < low:\n return False\n ... | <|body_start_0|>
low = float('-inf')
i = -1
for p in preorder:
if p < low:
return False
while i >= 0 and p > preorder[i]:
low = preorder[i]
i -= 1
i += 1
preorder[i] = p
return True
<|end_body... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def verifyPreorder(self, preorder):
""":type preorder: List[int] :rtype: bool"""
<|body_0|>
def verifyPreorderStack(self, preorder):
""":type preorder: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
low = float('-in... | stack_v2_sparse_classes_36k_train_002712 | 862 | no_license | [
{
"docstring": ":type preorder: List[int] :rtype: bool",
"name": "verifyPreorder",
"signature": "def verifyPreorder(self, preorder)"
},
{
"docstring": ":type preorder: List[int] :rtype: bool",
"name": "verifyPreorderStack",
"signature": "def verifyPreorderStack(self, preorder)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def verifyPreorder(self, preorder): :type preorder: List[int] :rtype: bool
- def verifyPreorderStack(self, preorder): :type preorder: List[int] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def verifyPreorder(self, preorder): :type preorder: List[int] :rtype: bool
- def verifyPreorderStack(self, preorder): :type preorder: List[int] :rtype: bool
<|skeleton|>
class S... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def verifyPreorder(self, preorder):
""":type preorder: List[int] :rtype: bool"""
<|body_0|>
def verifyPreorderStack(self, preorder):
""":type preorder: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def verifyPreorder(self, preorder):
""":type preorder: List[int] :rtype: bool"""
low = float('-inf')
i = -1
for p in preorder:
if p < low:
return False
while i >= 0 and p > preorder[i]:
low = preorder[i]
... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetcodePythonProject/leetcode_0251_0300/LeetCode255_VerifyPreorderSequenceInBinarySearchTree.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
d88b4d638e880ef62f672a9cc46b0abccc917e5e | [
"self._name = name\nself._url = None\nself._grpc_options = dict()\nself._tlsCACerts = dict()\nself._registrar = []",
"if 'url' in info:\n self._url = info['url']\nif 'grpc_options' in info:\n self._grpc_options = info['grpc_options']\nif 'tlsCACerts' in info:\n self._tlsCACerts = info['tlsCACerts']\nif '... | <|body_start_0|>
self._name = name
self._url = None
self._grpc_options = dict()
self._tlsCACerts = dict()
self._registrar = []
<|end_body_0|>
<|body_start_1|>
if 'url' in info:
self._url = info['url']
if 'grpc_options' in info:
self._grpc_... | An organization in the network. It contains several members. | certificateAuthority | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class certificateAuthority:
"""An organization in the network. It contains several members."""
def __init__(self, name='ca'):
""":param name: Name of the organization"""
<|body_0|>
def init_with_bundle(self, info):
"""Init the peer with given info dict :param info: Dic... | stack_v2_sparse_classes_36k_train_002713 | 1,349 | permissive | [
{
"docstring": ":param name: Name of the organization",
"name": "__init__",
"signature": "def __init__(self, name='ca')"
},
{
"docstring": "Init the peer with given info dict :param info: Dict including all info, e.g., :return: True or False",
"name": "init_with_bundle",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_006603 | Implement the Python class `certificateAuthority` described below.
Class description:
An organization in the network. It contains several members.
Method signatures and docstrings:
- def __init__(self, name='ca'): :param name: Name of the organization
- def init_with_bundle(self, info): Init the peer with given info ... | Implement the Python class `certificateAuthority` described below.
Class description:
An organization in the network. It contains several members.
Method signatures and docstrings:
- def __init__(self, name='ca'): :param name: Name of the organization
- def init_with_bundle(self, info): Init the peer with given info ... | 0ca510569229217f81fb093682c38e1b4a0cd7c6 | <|skeleton|>
class certificateAuthority:
"""An organization in the network. It contains several members."""
def __init__(self, name='ca'):
""":param name: Name of the organization"""
<|body_0|>
def init_with_bundle(self, info):
"""Init the peer with given info dict :param info: Dic... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class certificateAuthority:
"""An organization in the network. It contains several members."""
def __init__(self, name='ca'):
""":param name: Name of the organization"""
self._name = name
self._url = None
self._grpc_options = dict()
self._tlsCACerts = dict()
self... | the_stack_v2_python_sparse | hfc/fabric/certificateAuthority.py | hyperledger/fabric-sdk-py | train | 439 |
26e5aa12d14ab8acbf8790f0b6e4dcbea66fad6d | [
"classification_id = args['classification_id']\ncorp = CorporationFactory.get()\nclassification = corp.product_classification_repository.get_product_classification(classification_id)\nrelation_data = classification.get_label_group_relation()\nreturn {'relations': relation_data['relations'], 'classification_has_own_... | <|body_start_0|>
classification_id = args['classification_id']
corp = CorporationFactory.get()
classification = corp.product_classification_repository.get_product_classification(classification_id)
relation_data = classification.get_label_group_relation()
return {'relations': rela... | 商品分类标签 | AProductClassificationLabel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AProductClassificationLabel:
"""商品分类标签"""
def get(args):
""":return: :classification_has_own_label: 商品分类是否有自己的标签而不是继承自上级分类"""
<|body_0|>
def put(args):
"""设置商品分类标签"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
classification_id = args['classif... | stack_v2_sparse_classes_36k_train_002714 | 1,333 | no_license | [
{
"docstring": ":return: :classification_has_own_label: 商品分类是否有自己的标签而不是继承自上级分类",
"name": "get",
"signature": "def get(args)"
},
{
"docstring": "设置商品分类标签",
"name": "put",
"signature": "def put(args)"
}
] | 2 | null | Implement the Python class `AProductClassificationLabel` described below.
Class description:
商品分类标签
Method signatures and docstrings:
- def get(args): :return: :classification_has_own_label: 商品分类是否有自己的标签而不是继承自上级分类
- def put(args): 设置商品分类标签 | Implement the Python class `AProductClassificationLabel` described below.
Class description:
商品分类标签
Method signatures and docstrings:
- def get(args): :return: :classification_has_own_label: 商品分类是否有自己的标签而不是继承自上级分类
- def put(args): 设置商品分类标签
<|skeleton|>
class AProductClassificationLabel:
"""商品分类标签"""
def get... | 39860a451678ab50ad93ce8ebe2ef8490af65d62 | <|skeleton|>
class AProductClassificationLabel:
"""商品分类标签"""
def get(args):
""":return: :classification_has_own_label: 商品分类是否有自己的标签而不是继承自上级分类"""
<|body_0|>
def put(args):
"""设置商品分类标签"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AProductClassificationLabel:
"""商品分类标签"""
def get(args):
""":return: :classification_has_own_label: 商品分类是否有自己的标签而不是继承自上级分类"""
classification_id = args['classification_id']
corp = CorporationFactory.get()
classification = corp.product_classification_repository.get_product_c... | the_stack_v2_python_sparse | api/mall/product_classification/a_product_classification_label.py | chengdg/gaia | train | 0 |
962aba92b903b38bd58bae7c43bd0443dce4b8f8 | [
"if not nums:\n return 0\nif len(nums) == 1:\n return nums[0]\nreturn max(self.rob_line(nums[1:len(nums)]), self.rob_line(nums[0:len(nums) - 1]))",
"if not nums:\n return 0\nif len(nums) == 1:\n return nums[0]\nfor i in range(len(nums)):\n if i == 0:\n even = nums[i]\n elif i == 1:\n ... | <|body_start_0|>
if not nums:
return 0
if len(nums) == 1:
return nums[0]
return max(self.rob_line(nums[1:len(nums)]), self.rob_line(nums[0:len(nums) - 1]))
<|end_body_0|>
<|body_start_1|>
if not nums:
return 0
if len(nums) == 1:
re... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rob_line(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return 0
if len(nums) =... | stack_v2_sparse_classes_36k_train_002715 | 914 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob",
"signature": "def rob(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob_line",
"signature": "def rob_line(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012712 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def rob_line(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def rob_line(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def rob(self, nums):
... | df2bcca72fd303100dbcd73d1dfae44467abbb44 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rob_line(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 rob(self, nums):
""":type nums: List[int] :rtype: int"""
if not nums:
return 0
if len(nums) == 1:
return nums[0]
return max(self.rob_line(nums[1:len(nums)]), self.rob_line(nums[0:len(nums) - 1]))
def rob_line(self, nums):
""":t... | the_stack_v2_python_sparse | 213. House Robber II/Solution_动态规划_看起来更舒服.py | Inpurple/Leetcode | train | 3 | |
ae3c32b93921c5df08d556c4b36f8d4678ca8993 | [
"self.matrix = dict()\nself.max_num = maxChoosableInteger\nif (maxChoosableInteger + 1) * maxChoosableInteger / 2 <= desiredTotal:\n return False\nif maxChoosableInteger >= desiredTotal:\n return True\nalways_win = False\nfor i in range(1, maxChoosableInteger + 1):\n result = self.dfs(1 << i, desiredTotal ... | <|body_start_0|>
self.matrix = dict()
self.max_num = maxChoosableInteger
if (maxChoosableInteger + 1) * maxChoosableInteger / 2 <= desiredTotal:
return False
if maxChoosableInteger >= desiredTotal:
return True
always_win = False
for i in range(1, m... | SolutionError | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SolutionError:
def canIWin(self, maxChoosableInteger, desiredTotal):
""":type maxChoosableInteger: int :type desiredTotal: int :rtype: bool"""
<|body_0|>
def dfs(self, choose, target):
""":type choose: int :type target: int :rtype: int"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_002716 | 4,497 | no_license | [
{
"docstring": ":type maxChoosableInteger: int :type desiredTotal: int :rtype: bool",
"name": "canIWin",
"signature": "def canIWin(self, maxChoosableInteger, desiredTotal)"
},
{
"docstring": ":type choose: int :type target: int :rtype: int",
"name": "dfs",
"signature": "def dfs(self, cho... | 2 | stack_v2_sparse_classes_30k_train_002681 | Implement the Python class `SolutionError` described below.
Class description:
Implement the SolutionError class.
Method signatures and docstrings:
- def canIWin(self, maxChoosableInteger, desiredTotal): :type maxChoosableInteger: int :type desiredTotal: int :rtype: bool
- def dfs(self, choose, target): :type choose:... | Implement the Python class `SolutionError` described below.
Class description:
Implement the SolutionError class.
Method signatures and docstrings:
- def canIWin(self, maxChoosableInteger, desiredTotal): :type maxChoosableInteger: int :type desiredTotal: int :rtype: bool
- def dfs(self, choose, target): :type choose:... | f832227c4d0e0b1c0cc326561187004ef24e2a68 | <|skeleton|>
class SolutionError:
def canIWin(self, maxChoosableInteger, desiredTotal):
""":type maxChoosableInteger: int :type desiredTotal: int :rtype: bool"""
<|body_0|>
def dfs(self, choose, target):
""":type choose: int :type target: int :rtype: int"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SolutionError:
def canIWin(self, maxChoosableInteger, desiredTotal):
""":type maxChoosableInteger: int :type desiredTotal: int :rtype: bool"""
self.matrix = dict()
self.max_num = maxChoosableInteger
if (maxChoosableInteger + 1) * maxChoosableInteger / 2 <= desiredTotal:
... | the_stack_v2_python_sparse | 464.py | Gackle/leetcode_practice | train | 0 | |
ed0ab70c2364f611668a4923e2afab45bb7d19bc | [
"if not self.request.headers.get('Content_Type') and (not self.request.headers.get('Content-Type')):\n return self.request.params\ncontent_key = 'Content_Type'\nif not self.request.headers.get(content_key):\n content_key = 'Content-Type'\nif json_accepted and 'application/json' in self.request.headers.get(con... | <|body_start_0|>
if not self.request.headers.get('Content_Type') and (not self.request.headers.get('Content-Type')):
return self.request.params
content_key = 'Content_Type'
if not self.request.headers.get(content_key):
content_key = 'Content-Type'
if json_accepted... | Base RequestHandler that serves as parent of all other handlers in the API. It defines basic methods to deal with parameter validation, response building and request parsing. | BaseResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseResource:
"""Base RequestHandler that serves as parent of all other handlers in the API. It defines basic methods to deal with parameter validation, response building and request parsing."""
def parse_request_body(self, json_accepted=True, urlencoded_accepted=True):
"""Parse the ... | stack_v2_sparse_classes_36k_train_002717 | 2,669 | no_license | [
{
"docstring": "Parse the request according to the accepted types, currently only supports two: - 'application/json' - 'application/x-www-form-urlencoded' It returns a dictionary-like object with the request parameters. Since this dictionary may come directly from the request then it is immutable.",
"name":... | 2 | stack_v2_sparse_classes_30k_train_009685 | Implement the Python class `BaseResource` described below.
Class description:
Base RequestHandler that serves as parent of all other handlers in the API. It defines basic methods to deal with parameter validation, response building and request parsing.
Method signatures and docstrings:
- def parse_request_body(self, ... | Implement the Python class `BaseResource` described below.
Class description:
Base RequestHandler that serves as parent of all other handlers in the API. It defines basic methods to deal with parameter validation, response building and request parsing.
Method signatures and docstrings:
- def parse_request_body(self, ... | 99af4ea077fc6abf8672834d88213ec93a9b7fdf | <|skeleton|>
class BaseResource:
"""Base RequestHandler that serves as parent of all other handlers in the API. It defines basic methods to deal with parameter validation, response building and request parsing."""
def parse_request_body(self, json_accepted=True, urlencoded_accepted=True):
"""Parse the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseResource:
"""Base RequestHandler that serves as parent of all other handlers in the API. It defines basic methods to deal with parameter validation, response building and request parsing."""
def parse_request_body(self, json_accepted=True, urlencoded_accepted=True):
"""Parse the request accor... | the_stack_v2_python_sparse | src/python/xplore/handler/api/base_service.py | dballesteros7/explore-city-server | train | 0 |
4f8978fd0fcefd9e86a2f524e432f64d393f19d9 | [
"if scale is not None:\n _m = lmcl_matmul(i, w, tgt, w_idx, margin, scale)\nelse:\n _m = torch.matmul(i, w.T)\nif full_precision:\n _m = _m.float()\n_m = _m.max(dim=1)[0]\nreturn _m",
"if DEBUG and dist.is_initialized() and (dist.get_rank() == 0):\n print('DEBUG max fwd')\nctx.save_for_backward(i, w, ... | <|body_start_0|>
if scale is not None:
_m = lmcl_matmul(i, w, tgt, w_idx, margin, scale)
else:
_m = torch.matmul(i, w.T)
if full_precision:
_m = _m.float()
_m = _m.max(dim=1)[0]
return _m
<|end_body_0|>
<|body_start_1|>
if DEBUG and di... | Custom checkpointed function to get max-per-token from an input and a weight | GetMaxFunction | [
"Apache-2.0",
"MIT",
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetMaxFunction:
"""Custom checkpointed function to get max-per-token from an input and a weight"""
def get_max(i: torch.Tensor, w: torch.Tensor, tgt: torch.Tensor, w_idx: int, full_precision: bool, margin: float, scale: Optional[float]) -> torch.Tensor:
"""Throughout this code: i: in... | stack_v2_sparse_classes_36k_train_002718 | 25,261 | permissive | [
{
"docstring": "Throughout this code: i: input data with shape = (split-of-tokens, d_model) w: weight data with shape = (split-of-vocabs, d_model) tgt: target prediction data with shape = (split-of-tokens,)",
"name": "get_max",
"signature": "def get_max(i: torch.Tensor, w: torch.Tensor, tgt: torch.Tenso... | 3 | null | Implement the Python class `GetMaxFunction` described below.
Class description:
Custom checkpointed function to get max-per-token from an input and a weight
Method signatures and docstrings:
- def get_max(i: torch.Tensor, w: torch.Tensor, tgt: torch.Tensor, w_idx: int, full_precision: bool, margin: float, scale: Opti... | Implement the Python class `GetMaxFunction` described below.
Class description:
Custom checkpointed function to get max-per-token from an input and a weight
Method signatures and docstrings:
- def get_max(i: torch.Tensor, w: torch.Tensor, tgt: torch.Tensor, w_idx: int, full_precision: bool, margin: float, scale: Opti... | 164cc0f3170b4a3951dd84dda29c3e1504ac4d6e | <|skeleton|>
class GetMaxFunction:
"""Custom checkpointed function to get max-per-token from an input and a weight"""
def get_max(i: torch.Tensor, w: torch.Tensor, tgt: torch.Tensor, w_idx: int, full_precision: bool, margin: float, scale: Optional[float]) -> torch.Tensor:
"""Throughout this code: i: in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetMaxFunction:
"""Custom checkpointed function to get max-per-token from an input and a weight"""
def get_max(i: torch.Tensor, w: torch.Tensor, tgt: torch.Tensor, w_idx: int, full_precision: bool, margin: float, scale: Optional[float]) -> torch.Tensor:
"""Throughout this code: i: input data with... | the_stack_v2_python_sparse | fairscale/experimental/nn/mevo.py | facebookresearch/fairscale | train | 2,553 |
d723c19cae370055641529ebaeaa219f49371327 | [
"if self.cluster_id is None:\n raise SkipTest('The cluster_id is not specified, can not run ostf')\nself.fuel_web.run_ostf(cluster_id=self.cluster_id, should_fail=getattr(self, 'ostf_tests_should_failed', 0), failed_test_name=getattr(self, 'failed_test_name', None))",
"if self.cluster_id is None:\n raise Sk... | <|body_start_0|>
if self.cluster_id is None:
raise SkipTest('The cluster_id is not specified, can not run ostf')
self.fuel_web.run_ostf(cluster_id=self.cluster_id, should_fail=getattr(self, 'ostf_tests_should_failed', 0), failed_test_name=getattr(self, 'failed_test_name', None))
<|end_body_0... | Basic actions for OSTF tests health_check - run sanity and smoke OSTF tests health_check_sanity_smoke_ha - run sanity, smoke and ha OSTF tests health_check_ha - run ha OSTF tests | HealthCheckActions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HealthCheckActions:
"""Basic actions for OSTF tests health_check - run sanity and smoke OSTF tests health_check_sanity_smoke_ha - run sanity, smoke and ha OSTF tests health_check_ha - run ha OSTF tests"""
def health_check(self):
"""Run health checker Skip action if cluster doesn't ex... | stack_v2_sparse_classes_36k_train_002719 | 3,407 | no_license | [
{
"docstring": "Run health checker Skip action if cluster doesn't exist",
"name": "health_check",
"signature": "def health_check(self)"
},
{
"docstring": "Run health checker Sanity, Smoke and HA Skip action if cluster doesn't exist",
"name": "health_check_sanity_smoke_ha",
"signature": "... | 4 | stack_v2_sparse_classes_30k_train_018667 | Implement the Python class `HealthCheckActions` described below.
Class description:
Basic actions for OSTF tests health_check - run sanity and smoke OSTF tests health_check_sanity_smoke_ha - run sanity, smoke and ha OSTF tests health_check_ha - run ha OSTF tests
Method signatures and docstrings:
- def health_check(se... | Implement the Python class `HealthCheckActions` described below.
Class description:
Basic actions for OSTF tests health_check - run sanity and smoke OSTF tests health_check_sanity_smoke_ha - run sanity, smoke and ha OSTF tests health_check_ha - run ha OSTF tests
Method signatures and docstrings:
- def health_check(se... | e825c2f0483ab2030ddc47c8a2bdc85a80e5da02 | <|skeleton|>
class HealthCheckActions:
"""Basic actions for OSTF tests health_check - run sanity and smoke OSTF tests health_check_sanity_smoke_ha - run sanity, smoke and ha OSTF tests health_check_ha - run ha OSTF tests"""
def health_check(self):
"""Run health checker Skip action if cluster doesn't ex... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HealthCheckActions:
"""Basic actions for OSTF tests health_check - run sanity and smoke OSTF tests health_check_sanity_smoke_ha - run sanity, smoke and ha OSTF tests health_check_ha - run ha OSTF tests"""
def health_check(self):
"""Run health checker Skip action if cluster doesn't exist"""
... | the_stack_v2_python_sparse | system_test/actions/ostf_actions.py | rkhozinov/fuel-qa | train | 1 |
55c0e65d648672b1eff2d72ec783ddc77d14b8f1 | [
"os.chdir(path)\nall_files = list()\nisExists = os.path.exists(path)\nif not isExists:\n return False\nelse:\n file_list = os.listdir(path)\n for file in file_list:\n filePath = path + '\\\\' + file\n if os.path.isdir(file):\n all_files.extend(self.getListFloder(path + '\\\\' + fil... | <|body_start_0|>
os.chdir(path)
all_files = list()
isExists = os.path.exists(path)
if not isExists:
return False
else:
file_list = os.listdir(path)
for file in file_list:
filePath = path + '\\' + file
if os.path.... | FloderUtil | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FloderUtil:
def getListFloder(self, path):
"""文件夹递归,返回全部文件list :param path: :return:"""
<|body_0|>
def createFloder(self, path):
"""创建文件夹"""
<|body_1|>
def delFloder(self, path):
"""删除文件夹及文件"""
<|body_2|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_002720 | 8,073 | no_license | [
{
"docstring": "文件夹递归,返回全部文件list :param path: :return:",
"name": "getListFloder",
"signature": "def getListFloder(self, path)"
},
{
"docstring": "创建文件夹",
"name": "createFloder",
"signature": "def createFloder(self, path)"
},
{
"docstring": "删除文件夹及文件",
"name": "delFloder",
... | 3 | stack_v2_sparse_classes_30k_train_018818 | Implement the Python class `FloderUtil` described below.
Class description:
Implement the FloderUtil class.
Method signatures and docstrings:
- def getListFloder(self, path): 文件夹递归,返回全部文件list :param path: :return:
- def createFloder(self, path): 创建文件夹
- def delFloder(self, path): 删除文件夹及文件 | Implement the Python class `FloderUtil` described below.
Class description:
Implement the FloderUtil class.
Method signatures and docstrings:
- def getListFloder(self, path): 文件夹递归,返回全部文件list :param path: :return:
- def createFloder(self, path): 创建文件夹
- def delFloder(self, path): 删除文件夹及文件
<|skeleton|>
class FloderUt... | 34c368c109867da26d9256bca85f872b0fac2ea7 | <|skeleton|>
class FloderUtil:
def getListFloder(self, path):
"""文件夹递归,返回全部文件list :param path: :return:"""
<|body_0|>
def createFloder(self, path):
"""创建文件夹"""
<|body_1|>
def delFloder(self, path):
"""删除文件夹及文件"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FloderUtil:
def getListFloder(self, path):
"""文件夹递归,返回全部文件list :param path: :return:"""
os.chdir(path)
all_files = list()
isExists = os.path.exists(path)
if not isExists:
return False
else:
file_list = os.listdir(path)
for fil... | the_stack_v2_python_sparse | common/utils.py | oyebino/pomp_api | train | 1 | |
cd3ca47b8c871c67c7f5747c12ecf5469278956d | [
"if len(date_string) > 10:\n return False\n exit\nSTANDARD_DATE_PATTERN = '[0-9]{4}[-]{1}[0-9]{2}[-]{1}[0-9]{2}'\nif re.match(STANDARD_DATE_PATTERN, date_string):\n return True\nelse:\n return False",
"month_string = date_string[0:3]\ndate_string = date_string[3:]\nif len(date_string) > 2:\n return... | <|body_start_0|>
if len(date_string) > 10:
return False
exit
STANDARD_DATE_PATTERN = '[0-9]{4}[-]{1}[0-9]{2}[-]{1}[0-9]{2}'
if re.match(STANDARD_DATE_PATTERN, date_string):
return True
else:
return False
<|end_body_0|>
<|body_start_1|>
... | DataValidation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataValidation:
def check_standard_date_format(date_string):
"""Check whether date is in "yyyy-mm-dd" format input: date string return: bollean value"""
<|body_0|>
def check_nonstandard_date_format(date_string):
"""Check whether date is in "MMMdd" format input: date ... | stack_v2_sparse_classes_36k_train_002721 | 8,186 | no_license | [
{
"docstring": "Check whether date is in \"yyyy-mm-dd\" format input: date string return: bollean value",
"name": "check_standard_date_format",
"signature": "def check_standard_date_format(date_string)"
},
{
"docstring": "Check whether date is in \"MMMdd\" format input: date string return: bolle... | 2 | stack_v2_sparse_classes_30k_train_001078 | Implement the Python class `DataValidation` described below.
Class description:
Implement the DataValidation class.
Method signatures and docstrings:
- def check_standard_date_format(date_string): Check whether date is in "yyyy-mm-dd" format input: date string return: bollean value
- def check_nonstandard_date_format... | Implement the Python class `DataValidation` described below.
Class description:
Implement the DataValidation class.
Method signatures and docstrings:
- def check_standard_date_format(date_string): Check whether date is in "yyyy-mm-dd" format input: date string return: bollean value
- def check_nonstandard_date_format... | 103a0c52ca4eccacc30453b46cef9c08c431d574 | <|skeleton|>
class DataValidation:
def check_standard_date_format(date_string):
"""Check whether date is in "yyyy-mm-dd" format input: date string return: bollean value"""
<|body_0|>
def check_nonstandard_date_format(date_string):
"""Check whether date is in "MMMdd" format input: date ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataValidation:
def check_standard_date_format(date_string):
"""Check whether date is in "yyyy-mm-dd" format input: date string return: bollean value"""
if len(date_string) > 10:
return False
exit
STANDARD_DATE_PATTERN = '[0-9]{4}[-]{1}[0-9]{2}[-]{1}[0-9]{2}'
... | the_stack_v2_python_sparse | projectpackage/data_preprocessing.py | leodai716/TextAnalyticsandNLP_Project | train | 0 | |
5042c1e94afe35e63b558ac09a58e86e4958e4a1 | [
"lambda_response = stdout_stream.getvalue()\nis_lambda_user_error_response = LambdaOutputParser.is_lambda_error_response(lambda_response)\nreturn (lambda_response, is_lambda_user_error_response)",
"is_lambda_user_error_response = False\nlambda_response_error_dict_len = 2\nlambda_response_error_with_stacktrace_dic... | <|body_start_0|>
lambda_response = stdout_stream.getvalue()
is_lambda_user_error_response = LambdaOutputParser.is_lambda_error_response(lambda_response)
return (lambda_response, is_lambda_user_error_response)
<|end_body_0|>
<|body_start_1|>
is_lambda_user_error_response = False
... | LambdaOutputParser | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LambdaOutputParser:
def get_lambda_output(stdout_stream: io.StringIO) -> Tuple[str, bool]:
"""This method will extract read the given stream and return the response from Lambda function separated out from any log statements it might have outputted. Logs end up in the stdout stream if the... | stack_v2_sparse_classes_36k_train_002722 | 6,283 | permissive | [
{
"docstring": "This method will extract read the given stream and return the response from Lambda function separated out from any log statements it might have outputted. Logs end up in the stdout stream if the Lambda function wrote directly to stdout using System.out.println or equivalents. Parameters --------... | 2 | null | Implement the Python class `LambdaOutputParser` described below.
Class description:
Implement the LambdaOutputParser class.
Method signatures and docstrings:
- def get_lambda_output(stdout_stream: io.StringIO) -> Tuple[str, bool]: This method will extract read the given stream and return the response from Lambda func... | Implement the Python class `LambdaOutputParser` described below.
Class description:
Implement the LambdaOutputParser class.
Method signatures and docstrings:
- def get_lambda_output(stdout_stream: io.StringIO) -> Tuple[str, bool]: This method will extract read the given stream and return the response from Lambda func... | b297ff015f2b69d7c74059c2d42ece1c29ea73ee | <|skeleton|>
class LambdaOutputParser:
def get_lambda_output(stdout_stream: io.StringIO) -> Tuple[str, bool]:
"""This method will extract read the given stream and return the response from Lambda function separated out from any log statements it might have outputted. Logs end up in the stdout stream if the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LambdaOutputParser:
def get_lambda_output(stdout_stream: io.StringIO) -> Tuple[str, bool]:
"""This method will extract read the given stream and return the response from Lambda function separated out from any log statements it might have outputted. Logs end up in the stdout stream if the Lambda functi... | the_stack_v2_python_sparse | samcli/local/services/base_local_service.py | aws/aws-sam-cli | train | 1,402 | |
1e9265aeb881ff02b9d5435fff1c45af5f9b0a99 | [
"location = self.request.GET.get('location')\nquery = self.request.GET.get('q')\ncoords = None\nif location:\n coords = get_coordinates(location)\nif coords:\n self.located = True\nqueryset = Group.objects.search(search=query, location=coords)\nreturn queryset",
"context = super(GroupListView, self).get_con... | <|body_start_0|>
location = self.request.GET.get('location')
query = self.request.GET.get('q')
coords = None
if location:
coords = get_coordinates(location)
if coords:
self.located = True
queryset = Group.objects.search(search=query, location=coord... | View for listing groups. | GroupListView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupListView:
"""View for listing groups."""
def get_queryset(self):
"""Modify queryset if there are search params in the request."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Group list view context object populator"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k_train_002723 | 19,778 | permissive | [
{
"docstring": "Modify queryset if there are search params in the request.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Group list view context object populator",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004887 | Implement the Python class `GroupListView` described below.
Class description:
View for listing groups.
Method signatures and docstrings:
- def get_queryset(self): Modify queryset if there are search params in the request.
- def get_context_data(self, **kwargs): Group list view context object populator | Implement the Python class `GroupListView` described below.
Class description:
View for listing groups.
Method signatures and docstrings:
- def get_queryset(self): Modify queryset if there are search params in the request.
- def get_context_data(self, **kwargs): Group list view context object populator
<|skeleton|>
... | a56c0f89df82694bf5db32a04d8b092974791972 | <|skeleton|>
class GroupListView:
"""View for listing groups."""
def get_queryset(self):
"""Modify queryset if there are search params in the request."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Group list view context object populator"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupListView:
"""View for listing groups."""
def get_queryset(self):
"""Modify queryset if there are search params in the request."""
location = self.request.GET.get('location')
query = self.request.GET.get('q')
coords = None
if location:
coords = get_... | the_stack_v2_python_sparse | open_connect/groups/views.py | ofa/connect | train | 66 |
c8143d7baa0c82403e5c71cec9afd15dcfe9cf1c | [
"super(Firewall, self).__init__()\nself.log = logger.setup_logging(self.__class__.__name__)\nself.schema_class = 'edge_firewall_schema.FirewallSchema'\nself.set_content_type('application/xml')\nself.set_accept_type('application/xml')\nself.auth_type = 'vsm'\nif edge is not None:\n self.set_connection(edge.get_co... | <|body_start_0|>
super(Firewall, self).__init__()
self.log = logger.setup_logging(self.__class__.__name__)
self.schema_class = 'edge_firewall_schema.FirewallSchema'
self.set_content_type('application/xml')
self.set_accept_type('application/xml')
self.auth_type = 'vsm'
... | Firewall | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Firewall:
def __init__(self, edge=None, version=None):
"""Constructor to create Firewall object @param edge object on which Firewall has to be configured"""
<|body_0|>
def create(self, schema_object):
"""Client method to perform create operation @param schema_object ... | stack_v2_sparse_classes_36k_train_002724 | 5,236 | no_license | [
{
"docstring": "Constructor to create Firewall object @param edge object on which Firewall has to be configured",
"name": "__init__",
"signature": "def __init__(self, edge=None, version=None)"
},
{
"docstring": "Client method to perform create operation @param schema_object instance of BaseSchem... | 2 | stack_v2_sparse_classes_30k_train_011326 | Implement the Python class `Firewall` described below.
Class description:
Implement the Firewall class.
Method signatures and docstrings:
- def __init__(self, edge=None, version=None): Constructor to create Firewall object @param edge object on which Firewall has to be configured
- def create(self, schema_object): Cl... | Implement the Python class `Firewall` described below.
Class description:
Implement the Firewall class.
Method signatures and docstrings:
- def __init__(self, edge=None, version=None): Constructor to create Firewall object @param edge object on which Firewall has to be configured
- def create(self, schema_object): Cl... | 5b55817c050b637e2747084290f6206d2e622938 | <|skeleton|>
class Firewall:
def __init__(self, edge=None, version=None):
"""Constructor to create Firewall object @param edge object on which Firewall has to be configured"""
<|body_0|>
def create(self, schema_object):
"""Client method to perform create operation @param schema_object ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Firewall:
def __init__(self, edge=None, version=None):
"""Constructor to create Firewall object @param edge object on which Firewall has to be configured"""
super(Firewall, self).__init__()
self.log = logger.setup_logging(self.__class__.__name__)
self.schema_class = 'edge_firew... | the_stack_v2_python_sparse | SystemTesting/pylib/nsx/vsm/edge/firewall.py | Cloudxtreme/MyProject | train | 0 | |
47267d35a5be5dc5650810141f772b2e90408375 | [
"uid = request.GET.get('uid', None)\nrestaurant_id = request.GET.get('restaurant-id', None)\nif uid is not None:\n self.queryset = self.queryset.filter(uid=uid).order_by('-created_at', '-id')\nelif restaurant_id is not None:\n self.queryset = self.queryset.filter(restaurant=restaurant_id).order_by('-created_a... | <|body_start_0|>
uid = request.GET.get('uid', None)
restaurant_id = request.GET.get('restaurant-id', None)
if uid is not None:
self.queryset = self.queryset.filter(uid=uid).order_by('-created_at', '-id')
elif restaurant_id is not None:
self.queryset = self.queryse... | Restaurnat의 Review를 read/create/delete 하는 API | ReviewViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReviewViewSet:
"""Restaurnat의 Review를 read/create/delete 하는 API"""
def list(self, request, *args, **kwargs):
"""리뷰 리스트를 불러오는 API --- + parameters : + `uid` : uid에 해당하는 전체 리뷰 리스트를 조회 (**uid 또는 restaurant-id 하나 필수**) + `restaurant-id` : 리뷰 id에 해당하는 전체 리뷰 리스트를 조회 (**uid 또는 restaurant-id... | stack_v2_sparse_classes_36k_train_002725 | 31,279 | no_license | [
{
"docstring": "리뷰 리스트를 불러오는 API --- + parameters : + `uid` : uid에 해당하는 전체 리뷰 리스트를 조회 (**uid 또는 restaurant-id 하나 필수**) + `restaurant-id` : 리뷰 id에 해당하는 전체 리뷰 리스트를 조회 (**uid 또는 restaurant-id 하나 필수**) + 리턴 시 최신 등록일 기준 정렬하여 반환 + review 등록 시 Image가 같이 등록되어야 합니다. + 앱에서 review를 먼저 등록 하고 uid로 한번 조회하면 가장 최근에 등록된 review의... | 3 | stack_v2_sparse_classes_30k_train_004363 | Implement the Python class `ReviewViewSet` described below.
Class description:
Restaurnat의 Review를 read/create/delete 하는 API
Method signatures and docstrings:
- def list(self, request, *args, **kwargs): 리뷰 리스트를 불러오는 API --- + parameters : + `uid` : uid에 해당하는 전체 리뷰 리스트를 조회 (**uid 또는 restaurant-id 하나 필수**) + `restauran... | Implement the Python class `ReviewViewSet` described below.
Class description:
Restaurnat의 Review를 read/create/delete 하는 API
Method signatures and docstrings:
- def list(self, request, *args, **kwargs): 리뷰 리스트를 불러오는 API --- + parameters : + `uid` : uid에 해당하는 전체 리뷰 리스트를 조회 (**uid 또는 restaurant-id 하나 필수**) + `restauran... | 2f9ded6f1389a83b6627c2269d0cc9083fc6b5ee | <|skeleton|>
class ReviewViewSet:
"""Restaurnat의 Review를 read/create/delete 하는 API"""
def list(self, request, *args, **kwargs):
"""리뷰 리스트를 불러오는 API --- + parameters : + `uid` : uid에 해당하는 전체 리뷰 리스트를 조회 (**uid 또는 restaurant-id 하나 필수**) + `restaurant-id` : 리뷰 id에 해당하는 전체 리뷰 리스트를 조회 (**uid 또는 restaurant-id... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReviewViewSet:
"""Restaurnat의 Review를 read/create/delete 하는 API"""
def list(self, request, *args, **kwargs):
"""리뷰 리스트를 불러오는 API --- + parameters : + `uid` : uid에 해당하는 전체 리뷰 리스트를 조회 (**uid 또는 restaurant-id 하나 필수**) + `restaurant-id` : 리뷰 id에 해당하는 전체 리뷰 리스트를 조회 (**uid 또는 restaurant-id 하나 필수**) + 리... | the_stack_v2_python_sparse | dining/views.py | gaussian37/djangoserver | train | 2 |
1d83103e7ca98b2c2cab1e66dbf098a4dc62c3f0 | [
"if self.measure == self.MeasureType.PROGRESS:\n if self.threshold > 1.0:\n raise TrainerConfigError('Threshold for next lesson cannot be greater than 1 when the measure is progress.')\n if self.threshold < 0.0:\n raise TrainerConfigError('Threshold for next lesson cannot be negative when the me... | <|body_start_0|>
if self.measure == self.MeasureType.PROGRESS:
if self.threshold > 1.0:
raise TrainerConfigError('Threshold for next lesson cannot be greater than 1 when the measure is progress.')
if self.threshold < 0.0:
raise TrainerConfigError('Threshol... | CompletionCriteriaSettings contains the information needed to figure out if the next lesson must start. | CompletionCriteriaSettings | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompletionCriteriaSettings:
"""CompletionCriteriaSettings contains the information needed to figure out if the next lesson must start."""
def _check_threshold_value(self, attribute, value):
"""Verify that the threshold has a value between 0 and 1 when the measure is PROGRESS"""
... | stack_v2_sparse_classes_36k_train_002726 | 33,986 | permissive | [
{
"docstring": "Verify that the threshold has a value between 0 and 1 when the measure is PROGRESS",
"name": "_check_threshold_value",
"signature": "def _check_threshold_value(self, attribute, value)"
},
{
"docstring": "Given measures, this method returns a boolean indicating if the lesson needs... | 2 | stack_v2_sparse_classes_30k_train_016232 | Implement the Python class `CompletionCriteriaSettings` described below.
Class description:
CompletionCriteriaSettings contains the information needed to figure out if the next lesson must start.
Method signatures and docstrings:
- def _check_threshold_value(self, attribute, value): Verify that the threshold has a va... | Implement the Python class `CompletionCriteriaSettings` described below.
Class description:
CompletionCriteriaSettings contains the information needed to figure out if the next lesson must start.
Method signatures and docstrings:
- def _check_threshold_value(self, attribute, value): Verify that the threshold has a va... | 768405d0f80d30acb29e1f7c201a98ce67a668b3 | <|skeleton|>
class CompletionCriteriaSettings:
"""CompletionCriteriaSettings contains the information needed to figure out if the next lesson must start."""
def _check_threshold_value(self, attribute, value):
"""Verify that the threshold has a value between 0 and 1 when the measure is PROGRESS"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CompletionCriteriaSettings:
"""CompletionCriteriaSettings contains the information needed to figure out if the next lesson must start."""
def _check_threshold_value(self, attribute, value):
"""Verify that the threshold has a value between 0 and 1 when the measure is PROGRESS"""
if self.me... | the_stack_v2_python_sparse | ml-agents/mlagents/trainers/settings.py | xogur6889/ml-agents | train | 2 |
0188a3036a03be53b1697d07374c06ffcfbb8e6a | [
"self.X = X_init\nself.Y = Y_init\nself.l = l\nself.sigma_f = sigma_f\nself.K = self.kernel(self.X, self.X)",
"a = np.sum(X1 ** 2, axis=1, keepdims=True)\nb = np.sum(X2 ** 2, axis=1, keepdims=True)\nc = np.matmul(X1, X2.T)\ndist_sq = a + b.reshape(1, -1) - 2 * c\nK = self.sigma_f ** 2 * np.exp(-0.5 * (1 / self.l ... | <|body_start_0|>
self.X = X_init
self.Y = Y_init
self.l = l
self.sigma_f = sigma_f
self.K = self.kernel(self.X, self.X)
<|end_body_0|>
<|body_start_1|>
a = np.sum(X1 ** 2, axis=1, keepdims=True)
b = np.sum(X2 ** 2, axis=1, keepdims=True)
c = np.matmul(X1,... | that instantiates a noiseless 1D Gaussian process | GaussianProcess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianProcess:
"""that instantiates a noiseless 1D Gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""constructor"""
<|body_0|>
def kernel(self, X1, X2):
"""the covariance kernel matrix"""
<|body_1|>
def predict(self, X_s):
... | stack_v2_sparse_classes_36k_train_002727 | 1,175 | no_license | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self, X_init, Y_init, l=1, sigma_f=1)"
},
{
"docstring": "the covariance kernel matrix",
"name": "kernel",
"signature": "def kernel(self, X1, X2)"
},
{
"docstring": "Predicts the mean and standard deviat... | 3 | null | Implement the Python class `GaussianProcess` described below.
Class description:
that instantiates a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, X_init, Y_init, l=1, sigma_f=1): constructor
- def kernel(self, X1, X2): the covariance kernel matrix
- def predict(self, X_s): Pred... | Implement the Python class `GaussianProcess` described below.
Class description:
that instantiates a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, X_init, Y_init, l=1, sigma_f=1): constructor
- def kernel(self, X1, X2): the covariance kernel matrix
- def predict(self, X_s): Pred... | bda9efa60075afa834433ff1b5179db80f2487ae | <|skeleton|>
class GaussianProcess:
"""that instantiates a noiseless 1D Gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""constructor"""
<|body_0|>
def kernel(self, X1, X2):
"""the covariance kernel matrix"""
<|body_1|>
def predict(self, X_s):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GaussianProcess:
"""that instantiates a noiseless 1D Gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""constructor"""
self.X = X_init
self.Y = Y_init
self.l = l
self.sigma_f = sigma_f
self.K = self.kernel(self.X, self.X)
def ke... | the_stack_v2_python_sparse | unsupervised_learning/0x03-hyperparameter_tuning/1-gp.py | vandeldiegoc/holbertonschool-machine_learning | train | 0 |
25ad54205403765addf9fb4712a5b14539e39736 | [
"self.k = k\nself.heap = nums\nheapq.heapify(self.heap)\nwhile len(self.heap) > k:\n heapq.heappop(self.heap)",
"if len(self.heap) < self.k:\n heapq.heappush(self.heap, val)\nelif self.heap[0] < val:\n heapq.heapreplace(self.heap, val)\nreturn self.heap[0]"
] | <|body_start_0|>
self.k = k
self.heap = nums
heapq.heapify(self.heap)
while len(self.heap) > k:
heapq.heappop(self.heap)
<|end_body_0|>
<|body_start_1|>
if len(self.heap) < self.k:
heapq.heappush(self.heap, val)
elif self.heap[0] < val:
... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.k = k
self.heap = nums
heapq.heapify(... | stack_v2_sparse_classes_36k_train_002728 | 1,999 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | null | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | 1d1876620a55ff88af7bc390cf1a4fd4350d8d16 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
self.k = k
self.heap = nums
heapq.heapify(self.heap)
while len(self.heap) > k:
heapq.heappop(self.heap)
def add(self, val):
""":type val: int :rtype: int"""
... | the_stack_v2_python_sparse | 02-算法思想/设计/703.数据流中的第K大元素.py | jh-lau/leetcode_in_python | train | 0 | |
e14f5f493f1270683ae216a11c4bef6faf33476c | [
"incomplete_activities = user_domain.IncompleteActivities('user_id0', ['exp_id0'], ['collect_id0'])\nself.assertEqual(incomplete_activities.id, 'user_id0')\nself.assertListEqual(incomplete_activities.exploration_ids, ['exp_id0'])\nself.assertListEqual(incomplete_activities.collection_ids, ['collect_id0'])",
"inco... | <|body_start_0|>
incomplete_activities = user_domain.IncompleteActivities('user_id0', ['exp_id0'], ['collect_id0'])
self.assertEqual(incomplete_activities.id, 'user_id0')
self.assertListEqual(incomplete_activities.exploration_ids, ['exp_id0'])
self.assertListEqual(incomplete_activities.c... | Testing domain object for incomplete activities model. | IncompleteActivitiesTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IncompleteActivitiesTests:
"""Testing domain object for incomplete activities model."""
def test_initialization(self):
"""Testing init method."""
<|body_0|>
def test_add_exploration_id(self):
"""Testing add_exploration_id."""
<|body_1|>
def test_remo... | stack_v2_sparse_classes_36k_train_002729 | 14,816 | permissive | [
{
"docstring": "Testing init method.",
"name": "test_initialization",
"signature": "def test_initialization(self)"
},
{
"docstring": "Testing add_exploration_id.",
"name": "test_add_exploration_id",
"signature": "def test_add_exploration_id(self)"
},
{
"docstring": "Testing remov... | 5 | null | Implement the Python class `IncompleteActivitiesTests` described below.
Class description:
Testing domain object for incomplete activities model.
Method signatures and docstrings:
- def test_initialization(self): Testing init method.
- def test_add_exploration_id(self): Testing add_exploration_id.
- def test_remove_e... | Implement the Python class `IncompleteActivitiesTests` described below.
Class description:
Testing domain object for incomplete activities model.
Method signatures and docstrings:
- def test_initialization(self): Testing init method.
- def test_add_exploration_id(self): Testing add_exploration_id.
- def test_remove_e... | 899b9755a6b795a8991e596055ac24065a8435e0 | <|skeleton|>
class IncompleteActivitiesTests:
"""Testing domain object for incomplete activities model."""
def test_initialization(self):
"""Testing init method."""
<|body_0|>
def test_add_exploration_id(self):
"""Testing add_exploration_id."""
<|body_1|>
def test_remo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IncompleteActivitiesTests:
"""Testing domain object for incomplete activities model."""
def test_initialization(self):
"""Testing init method."""
incomplete_activities = user_domain.IncompleteActivities('user_id0', ['exp_id0'], ['collect_id0'])
self.assertEqual(incomplete_activiti... | the_stack_v2_python_sparse | core/domain/user_domain_test.py | import-keshav/oppia | train | 4 |
280e1bb21b70460e1fcf65589ee00549f3fe9cb9 | [
"categories = Tag.objects.values('id', 'name').annotate(news_num=Count('news')).filter(is_delete=False).order_by('-news_num')\ncontext = {'categories': categories}\nreturn render(request, 'cms/news_category.html', context=context)",
"name = request.POST.get('name', None)\nif not name or not name.strip():\n ret... | <|body_start_0|>
categories = Tag.objects.values('id', 'name').annotate(news_num=Count('news')).filter(is_delete=False).order_by('-news_num')
context = {'categories': categories}
return render(request, 'cms/news_category.html', context=context)
<|end_body_0|>
<|body_start_1|>
name = req... | 新闻分类怎删改查 | NewsTags | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewsTags:
"""新闻分类怎删改查"""
def get(self, request):
"""获取新闻分类"""
<|body_0|>
def post(self, request):
"""添加新闻分类"""
<|body_1|>
def put(self, request):
"""编辑新闻分类"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
categories = Tag.obj... | stack_v2_sparse_classes_36k_train_002730 | 27,319 | no_license | [
{
"docstring": "获取新闻分类",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "添加新闻分类",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "编辑新闻分类",
"name": "put",
"signature": "def put(self, request)"
}
] | 3 | stack_v2_sparse_classes_30k_test_001145 | Implement the Python class `NewsTags` described below.
Class description:
新闻分类怎删改查
Method signatures and docstrings:
- def get(self, request): 获取新闻分类
- def post(self, request): 添加新闻分类
- def put(self, request): 编辑新闻分类 | Implement the Python class `NewsTags` described below.
Class description:
新闻分类怎删改查
Method signatures and docstrings:
- def get(self, request): 获取新闻分类
- def post(self, request): 添加新闻分类
- def put(self, request): 编辑新闻分类
<|skeleton|>
class NewsTags:
"""新闻分类怎删改查"""
def get(self, request):
"""获取新闻分类"""
... | 14316e211e5970aefb9288365451739839aba941 | <|skeleton|>
class NewsTags:
"""新闻分类怎删改查"""
def get(self, request):
"""获取新闻分类"""
<|body_0|>
def post(self, request):
"""添加新闻分类"""
<|body_1|>
def put(self, request):
"""编辑新闻分类"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NewsTags:
"""新闻分类怎删改查"""
def get(self, request):
"""获取新闻分类"""
categories = Tag.objects.values('id', 'name').annotate(news_num=Count('news')).filter(is_delete=False).order_by('-news_num')
context = {'categories': categories}
return render(request, 'cms/news_category.html', ... | the_stack_v2_python_sparse | apps/cms/views.py | achieveIdeal/- | train | 0 |
e71e7cac4c12355acd936e4d145765c87fe6ec08 | [
"torch.nn.Module.__init__(self)\nself._is_all = is_all\nif self._is_all:\n self.features = torchvision.models.vgg16(pretrained=True).features\n self.features = torch.nn.Sequential(*list(self.features.children())[:-2])\nself.relu5_3 = torch.nn.ReLU(inplace=False)\nself.fc = torch.nn.Linear(in_features=512 * 51... | <|body_start_0|>
torch.nn.Module.__init__(self)
self._is_all = is_all
if self._is_all:
self.features = torchvision.models.vgg16(pretrained=True).features
self.features = torch.nn.Sequential(*list(self.features.children())[:-2])
self.relu5_3 = torch.nn.ReLU(inplace... | Mean field B-CNN model. The B-CNN model is illustrated as follows. conv1^2 (64) -> pool1 -> conv2^2 (128) -> pool2 -> conv3^3 (256) -> pool3 -> conv4^3 (512) -> pool4 -> conv5^3 (512) -> mean field bilinear pooling -> fc. The network accepts a 3*448*448 input, and the relu5-3 activation has shape 512*28*28 since we dow... | BCNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BCNN:
"""Mean field B-CNN model. The B-CNN model is illustrated as follows. conv1^2 (64) -> pool1 -> conv2^2 (128) -> pool2 -> conv3^3 (256) -> pool3 -> conv4^3 (512) -> pool4 -> conv5^3 (512) -> mean field bilinear pooling -> fc. The network accepts a 3*448*448 input, and the relu5-3 activation ... | stack_v2_sparse_classes_36k_train_002731 | 3,951 | no_license | [
{
"docstring": "Declare all needed layers. Args: num_classes, int. is_all, bool: In the all/fc phase.",
"name": "__init__",
"signature": "def __init__(self, num_classes, is_all)"
},
{
"docstring": "Initialize the weight and bias for each module. Args: module, torch.nn.Module.",
"name": "_ini... | 3 | stack_v2_sparse_classes_30k_train_014870 | Implement the Python class `BCNN` described below.
Class description:
Mean field B-CNN model. The B-CNN model is illustrated as follows. conv1^2 (64) -> pool1 -> conv2^2 (128) -> pool2 -> conv3^3 (256) -> pool3 -> conv4^3 (512) -> pool4 -> conv5^3 (512) -> mean field bilinear pooling -> fc. The network accepts a 3*448... | Implement the Python class `BCNN` described below.
Class description:
Mean field B-CNN model. The B-CNN model is illustrated as follows. conv1^2 (64) -> pool1 -> conv2^2 (128) -> pool2 -> conv3^3 (256) -> pool3 -> conv4^3 (512) -> pool4 -> conv5^3 (512) -> mean field bilinear pooling -> fc. The network accepts a 3*448... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class BCNN:
"""Mean field B-CNN model. The B-CNN model is illustrated as follows. conv1^2 (64) -> pool1 -> conv2^2 (128) -> pool2 -> conv3^3 (256) -> pool3 -> conv4^3 (512) -> pool4 -> conv5^3 (512) -> mean field bilinear pooling -> fc. The network accepts a 3*448*448 input, and the relu5-3 activation ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BCNN:
"""Mean field B-CNN model. The B-CNN model is illustrated as follows. conv1^2 (64) -> pool1 -> conv2^2 (128) -> pool2 -> conv3^3 (256) -> pool3 -> conv4^3 (512) -> pool4 -> conv5^3 (512) -> mean field bilinear pooling -> fc. The network accepts a 3*448*448 input, and the relu5-3 activation has shape 512... | the_stack_v2_python_sparse | generated/test_HaoMood_blinear_cnn_faster.py | jansel/pytorch-jit-paritybench | train | 35 |
9f95cf977af74443652f7e7c38da58eac95ac980 | [
"resp = None\nfor i in range(4):\n try:\n resp = requests.get(url, params=params, timeout=5)\n except requests.Timeout:\n trimmed_params = {k: v for k, v in list(params.items()) if k not in list(ST_BASE_PARAMS.keys())}\n log.error('GET Timeout to {} w/ {}'.format(url[len(ST_BASE_URL):], t... | <|body_start_0|>
resp = None
for i in range(4):
try:
resp = requests.get(url, params=params, timeout=5)
except requests.Timeout:
trimmed_params = {k: v for k, v in list(params.items()) if k not in list(ST_BASE_PARAMS.keys())}
log.er... | Uses `requests` library to GET and POST to Stocktwits, and also to convert resonses to JSON | Requests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Requests:
"""Uses `requests` library to GET and POST to Stocktwits, and also to convert resonses to JSON"""
def get_json(url, params=None):
"""Uses tries to GET a few times before giving up if a timeout. returns JSON"""
<|body_0|>
def post_json(url, params=None, deadline... | stack_v2_sparse_classes_36k_train_002732 | 3,330 | no_license | [
{
"docstring": "Uses tries to GET a few times before giving up if a timeout. returns JSON",
"name": "get_json",
"signature": "def get_json(url, params=None)"
},
{
"docstring": "Tries to post a couple times in a loop before giving up if a timeout.",
"name": "post_json",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_016583 | Implement the Python class `Requests` described below.
Class description:
Uses `requests` library to GET and POST to Stocktwits, and also to convert resonses to JSON
Method signatures and docstrings:
- def get_json(url, params=None): Uses tries to GET a few times before giving up if a timeout. returns JSON
- def post... | Implement the Python class `Requests` described below.
Class description:
Uses `requests` library to GET and POST to Stocktwits, and also to convert resonses to JSON
Method signatures and docstrings:
- def get_json(url, params=None): Uses tries to GET a few times before giving up if a timeout. returns JSON
- def post... | 3938c276a6df5759b055712072bfde983a7ce66a | <|skeleton|>
class Requests:
"""Uses `requests` library to GET and POST to Stocktwits, and also to convert resonses to JSON"""
def get_json(url, params=None):
"""Uses tries to GET a few times before giving up if a timeout. returns JSON"""
<|body_0|>
def post_json(url, params=None, deadline... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Requests:
"""Uses `requests` library to GET and POST to Stocktwits, and also to convert resonses to JSON"""
def get_json(url, params=None):
"""Uses tries to GET a few times before giving up if a timeout. returns JSON"""
resp = None
for i in range(4):
try:
... | the_stack_v2_python_sparse | Scrapers/stocktwitScraper.py | webclinic017/SP_DayTrading | train | 1 |
3c0ce2bf58aeabbcb17fa76c2d382917c302a445 | [
"super().__init__(template_fn='joint_calling.html')\nself.title = 'Joint Calling Report'\nself.vcf = data\nself.table_html, self.table_options = self.create_datatable()\nself.create_html('joint_calling.html')",
"datatable = DataTable(self.vcf.df, 'jc')\ndatatable.datatable.datatable_options = {'scrollX': 'true', ... | <|body_start_0|>
super().__init__(template_fn='joint_calling.html')
self.title = 'Joint Calling Report'
self.vcf = data
self.table_html, self.table_options = self.create_datatable()
self.create_html('joint_calling.html')
<|end_body_0|>
<|body_start_1|>
datatable = DataTa... | Write HTML report of variant calling. This class takes a csv file generated by sequana_variant_filter. | JointCallingModule | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JointCallingModule:
"""Write HTML report of variant calling. This class takes a csv file generated by sequana_variant_filter."""
def __init__(self, data):
""".. rubric:: constructor :param data: it can be a csv filename created by sequana.freebayes_vcf_filter or a :class:`freebayes_v... | stack_v2_sparse_classes_36k_train_002733 | 2,093 | permissive | [
{
"docstring": ".. rubric:: constructor :param data: it can be a csv filename created by sequana.freebayes_vcf_filter or a :class:`freebayes_vcf_filter.Filtered_freebayes` object.",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "Variants detected section.",
"n... | 2 | stack_v2_sparse_classes_30k_train_021382 | Implement the Python class `JointCallingModule` described below.
Class description:
Write HTML report of variant calling. This class takes a csv file generated by sequana_variant_filter.
Method signatures and docstrings:
- def __init__(self, data): .. rubric:: constructor :param data: it can be a csv filename created... | Implement the Python class `JointCallingModule` described below.
Class description:
Write HTML report of variant calling. This class takes a csv file generated by sequana_variant_filter.
Method signatures and docstrings:
- def __init__(self, data): .. rubric:: constructor :param data: it can be a csv filename created... | 8717094493d1993debd079f324c540541dece70f | <|skeleton|>
class JointCallingModule:
"""Write HTML report of variant calling. This class takes a csv file generated by sequana_variant_filter."""
def __init__(self, data):
""".. rubric:: constructor :param data: it can be a csv filename created by sequana.freebayes_vcf_filter or a :class:`freebayes_v... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JointCallingModule:
"""Write HTML report of variant calling. This class takes a csv file generated by sequana_variant_filter."""
def __init__(self, data):
""".. rubric:: constructor :param data: it can be a csv filename created by sequana.freebayes_vcf_filter or a :class:`freebayes_vcf_filter.Fil... | the_stack_v2_python_sparse | sequana/modules_report/joint_calling.py | sequana/sequana | train | 155 |
152c2c8b2941f99f7ed332e3cacaa616c5701b07 | [
"article = fetch_an_article(slug)\nreport = request.data\nif article.author == request.user:\n raise ValidationError(detail={'error': \"You can't report your article.\"})\ntry:\n already_reported = EscalationModel.objects.get(article=article, reporter=request.user, reason=report['reason'])\n if already_rep... | <|body_start_0|>
article = fetch_an_article(slug)
report = request.data
if article.author == request.user:
raise ValidationError(detail={'error': "You can't report your article."})
try:
already_reported = EscalationModel.objects.get(article=article, reporter=reque... | User can report an article | ExcalationAPIView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExcalationAPIView:
"""User can report an article"""
def post(self, request, slug):
"""Creates a single report for a specific article"""
<|body_0|>
def delete(self, request, slug):
"""Admin to delete an article"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_002734 | 4,286 | permissive | [
{
"docstring": "Creates a single report for a specific article",
"name": "post",
"signature": "def post(self, request, slug)"
},
{
"docstring": "Admin to delete an article",
"name": "delete",
"signature": "def delete(self, request, slug)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015975 | Implement the Python class `ExcalationAPIView` described below.
Class description:
User can report an article
Method signatures and docstrings:
- def post(self, request, slug): Creates a single report for a specific article
- def delete(self, request, slug): Admin to delete an article | Implement the Python class `ExcalationAPIView` described below.
Class description:
User can report an article
Method signatures and docstrings:
- def post(self, request, slug): Creates a single report for a specific article
- def delete(self, request, slug): Admin to delete an article
<|skeleton|>
class ExcalationAP... | d0f73bf166ad41f243cff6d82caced2f9facf2f9 | <|skeleton|>
class ExcalationAPIView:
"""User can report an article"""
def post(self, request, slug):
"""Creates a single report for a specific article"""
<|body_0|>
def delete(self, request, slug):
"""Admin to delete an article"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExcalationAPIView:
"""User can report an article"""
def post(self, request, slug):
"""Creates a single report for a specific article"""
article = fetch_an_article(slug)
report = request.data
if article.author == request.user:
raise ValidationError(detail={'erro... | the_stack_v2_python_sparse | authors/apps/escalation/views.py | andela/ah-the-immortals-backend | train | 3 |
b5773deb1210f2b601be84ad429209722783a316 | [
"data = self.get_json()\nuser_id = data.pop('user_id', None)\nif user_id is None:\n return self.error('User ID must be specified')\nstream_id = int(stream_id)\nwith self.Session() as session:\n su = session.scalars(StreamUser.select(session.user_or_token).where(StreamUser.stream_id == stream_id).where(StreamU... | <|body_start_0|>
data = self.get_json()
user_id = data.pop('user_id', None)
if user_id is None:
return self.error('User ID must be specified')
stream_id = int(stream_id)
with self.Session() as session:
su = session.scalars(StreamUser.select(session.user_or... | StreamUserHandler | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StreamUserHandler:
def post(self, stream_id, *ignored_args):
"""--- description: Grant stream access to a user tags: - streams - users parameters: - in: path name: stream_id required: true schema: type: integer requestBody: content: application/json: schema: type: object properties: user... | stack_v2_sparse_classes_36k_train_002735 | 8,804 | permissive | [
{
"docstring": "--- description: Grant stream access to a user tags: - streams - users parameters: - in: path name: stream_id required: true schema: type: integer requestBody: content: application/json: schema: type: object properties: user_id: type: integer required: - user_id responses: 200: content: applicat... | 2 | null | Implement the Python class `StreamUserHandler` described below.
Class description:
Implement the StreamUserHandler class.
Method signatures and docstrings:
- def post(self, stream_id, *ignored_args): --- description: Grant stream access to a user tags: - streams - users parameters: - in: path name: stream_id required... | Implement the Python class `StreamUserHandler` described below.
Class description:
Implement the StreamUserHandler class.
Method signatures and docstrings:
- def post(self, stream_id, *ignored_args): --- description: Grant stream access to a user tags: - streams - users parameters: - in: path name: stream_id required... | 161d3532ba3ba059446addcdac58ca96f39e9636 | <|skeleton|>
class StreamUserHandler:
def post(self, stream_id, *ignored_args):
"""--- description: Grant stream access to a user tags: - streams - users parameters: - in: path name: stream_id required: true schema: type: integer requestBody: content: application/json: schema: type: object properties: user... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StreamUserHandler:
def post(self, stream_id, *ignored_args):
"""--- description: Grant stream access to a user tags: - streams - users parameters: - in: path name: stream_id required: true schema: type: integer requestBody: content: application/json: schema: type: object properties: user_id: type: int... | the_stack_v2_python_sparse | skyportal/handlers/api/stream.py | skyportal/skyportal | train | 80 | |
ffd2fd90891382dbdac94833ab7b1ceb9b18bbfb | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn PropertyRule()",
"from ..binary_operator import BinaryOperator\nfrom .rule_operation import RuleOperation\nfrom ..binary_operator import BinaryOperator\nfrom .rule_operation import RuleOperation\nfields: Dict[str, Callable[[Any], None]... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return PropertyRule()
<|end_body_0|>
<|body_start_1|>
from ..binary_operator import BinaryOperator
from .rule_operation import RuleOperation
from ..binary_operator import BinaryOperator... | PropertyRule | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PropertyRule:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PropertyRule:
"""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: ... | stack_v2_sparse_classes_36k_train_002736 | 3,656 | 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: PropertyRule",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(... | 3 | stack_v2_sparse_classes_30k_train_010471 | Implement the Python class `PropertyRule` described below.
Class description:
Implement the PropertyRule class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PropertyRule: Creates a new instance of the appropriate class based on discriminator value Ar... | Implement the Python class `PropertyRule` described below.
Class description:
Implement the PropertyRule class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PropertyRule: Creates a new instance of the appropriate class based on discriminator value Ar... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class PropertyRule:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PropertyRule:
"""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: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PropertyRule:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> PropertyRule:
"""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: PropertyRule""... | the_stack_v2_python_sparse | msgraph/generated/models/external_connectors/property_rule.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
5d5b29c9197d99cad3bcedcfbd6e81568364e188 | [
"self.alias_name = alias_name\nself.client_subnet_whitelist = client_subnet_whitelist\nself.smb_config = smb_config\nself.view_path = view_path",
"if dictionary is None:\n return None\nalias_name = dictionary.get('aliasName')\nclient_subnet_whitelist = None\nif dictionary.get('clientSubnetWhitelist') != None:\... | <|body_start_0|>
self.alias_name = alias_name
self.client_subnet_whitelist = client_subnet_whitelist
self.smb_config = smb_config
self.view_path = view_path
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
alias_name = dictionary.get('aliasN... | Implementation of the 'ViewAliasInfo' model. View Alias Info is returned as part of list views. Attributes: alias_name (string): Alias name. client_subnet_whitelist (list of ClusterConfigProtoSubnet): List of external client subnet IPs that are allowed to access the share. smb_config (AliasSmbConfig): Message defining ... | ViewAliasInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ViewAliasInfo:
"""Implementation of the 'ViewAliasInfo' model. View Alias Info is returned as part of list views. Attributes: alias_name (string): Alias name. client_subnet_whitelist (list of ClusterConfigProtoSubnet): List of external client subnet IPs that are allowed to access the share. smb_c... | stack_v2_sparse_classes_36k_train_002737 | 2,873 | permissive | [
{
"docstring": "Constructor for the ViewAliasInfo class",
"name": "__init__",
"signature": "def __init__(self, alias_name=None, client_subnet_whitelist=None, smb_config=None, view_path=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A ... | 2 | stack_v2_sparse_classes_30k_train_014896 | Implement the Python class `ViewAliasInfo` described below.
Class description:
Implementation of the 'ViewAliasInfo' model. View Alias Info is returned as part of list views. Attributes: alias_name (string): Alias name. client_subnet_whitelist (list of ClusterConfigProtoSubnet): List of external client subnet IPs that... | Implement the Python class `ViewAliasInfo` described below.
Class description:
Implementation of the 'ViewAliasInfo' model. View Alias Info is returned as part of list views. Attributes: alias_name (string): Alias name. client_subnet_whitelist (list of ClusterConfigProtoSubnet): List of external client subnet IPs that... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ViewAliasInfo:
"""Implementation of the 'ViewAliasInfo' model. View Alias Info is returned as part of list views. Attributes: alias_name (string): Alias name. client_subnet_whitelist (list of ClusterConfigProtoSubnet): List of external client subnet IPs that are allowed to access the share. smb_c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ViewAliasInfo:
"""Implementation of the 'ViewAliasInfo' model. View Alias Info is returned as part of list views. Attributes: alias_name (string): Alias name. client_subnet_whitelist (list of ClusterConfigProtoSubnet): List of external client subnet IPs that are allowed to access the share. smb_config (AliasS... | the_stack_v2_python_sparse | cohesity_management_sdk/models/view_alias_info.py | cohesity/management-sdk-python | train | 24 |
073f3fef7ba2dbfc985efa88704e051ca0aedc82 | [
"if ioType(outFile) is not str:\n self._encoding = 'utf-8'\nelse:\n self._encoding = None\nself._outFile = outFile\nself.formatEvent = formatEvent",
"text = self.formatEvent(event)\nif text:\n if self._encoding is None:\n self._outFile.write(text)\n else:\n self._outFile.write(text.encod... | <|body_start_0|>
if ioType(outFile) is not str:
self._encoding = 'utf-8'
else:
self._encoding = None
self._outFile = outFile
self.formatEvent = formatEvent
<|end_body_0|>
<|body_start_1|>
text = self.formatEvent(event)
if text:
if self... | Log observer that writes to a file-like object. | FileLogObserver | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileLogObserver:
"""Log observer that writes to a file-like object."""
def __init__(self, outFile: IO[Any], formatEvent: Callable[[LogEvent], Optional[str]]) -> None:
"""@param outFile: A file-like object. Ideally one should be passed which accepts text data. Otherwise, UTF-8 L{bytes... | stack_v2_sparse_classes_36k_train_002738 | 2,386 | permissive | [
{
"docstring": "@param outFile: A file-like object. Ideally one should be passed which accepts text data. Otherwise, UTF-8 L{bytes} will be used. @param formatEvent: A callable that formats an event.",
"name": "__init__",
"signature": "def __init__(self, outFile: IO[Any], formatEvent: Callable[[LogEvent... | 2 | null | Implement the Python class `FileLogObserver` described below.
Class description:
Log observer that writes to a file-like object.
Method signatures and docstrings:
- def __init__(self, outFile: IO[Any], formatEvent: Callable[[LogEvent], Optional[str]]) -> None: @param outFile: A file-like object. Ideally one should be... | Implement the Python class `FileLogObserver` described below.
Class description:
Log observer that writes to a file-like object.
Method signatures and docstrings:
- def __init__(self, outFile: IO[Any], formatEvent: Callable[[LogEvent], Optional[str]]) -> None: @param outFile: A file-like object. Ideally one should be... | 5cee0a8c4180a3108538b4e4ce945a18726595a6 | <|skeleton|>
class FileLogObserver:
"""Log observer that writes to a file-like object."""
def __init__(self, outFile: IO[Any], formatEvent: Callable[[LogEvent], Optional[str]]) -> None:
"""@param outFile: A file-like object. Ideally one should be passed which accepts text data. Otherwise, UTF-8 L{bytes... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileLogObserver:
"""Log observer that writes to a file-like object."""
def __init__(self, outFile: IO[Any], formatEvent: Callable[[LogEvent], Optional[str]]) -> None:
"""@param outFile: A file-like object. Ideally one should be passed which accepts text data. Otherwise, UTF-8 L{bytes} will be use... | the_stack_v2_python_sparse | venv/Lib/site-packages/twisted/logger/_file.py | zoelesv/Smathchat | train | 9 |
0d0f0669dff277982599a0fad23940d6e8c13f1d | [
"attack_value = randint(1, 100)\naccuracy_bonus = 0\nif attacker.db.wielded_weapon:\n weapon = attacker.db.wielded_weapon\n accuracy_bonus += weapon.db.accuracy_bonus\nelse:\n accuracy_bonus += attacker.db.unarmed_accuracy\nattack_value += accuracy_bonus\nreturn attack_value",
"defense_value = 50\nif def... | <|body_start_0|>
attack_value = randint(1, 100)
accuracy_bonus = 0
if attacker.db.wielded_weapon:
weapon = attacker.db.wielded_weapon
accuracy_bonus += weapon.db.accuracy_bonus
else:
accuracy_bonus += attacker.db.unarmed_accuracy
attack_value +... | Has all the methods of the basic combat, with the addition of equipment. | EquipmentCombatRules | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EquipmentCombatRules:
"""Has all the methods of the basic combat, with the addition of equipment."""
def get_attack(self, attacker, defender):
"""Returns a value for an attack roll. Args: attacker (obj): Character doing the attacking defender (obj): Character being attacked Returns: ... | stack_v2_sparse_classes_36k_train_002739 | 23,139 | permissive | [
{
"docstring": "Returns a value for an attack roll. Args: attacker (obj): Character doing the attacking defender (obj): Character being attacked Returns: attack_value (int): Attack roll value, compared against a defense value to determine whether an attack hits or misses. Notes: In this example, a weapon's accu... | 4 | null | Implement the Python class `EquipmentCombatRules` described below.
Class description:
Has all the methods of the basic combat, with the addition of equipment.
Method signatures and docstrings:
- def get_attack(self, attacker, defender): Returns a value for an attack roll. Args: attacker (obj): Character doing the att... | Implement the Python class `EquipmentCombatRules` described below.
Class description:
Has all the methods of the basic combat, with the addition of equipment.
Method signatures and docstrings:
- def get_attack(self, attacker, defender): Returns a value for an attack roll. Args: attacker (obj): Character doing the att... | b3ca58b5c1325a3bf57051dfe23560a08d2947b7 | <|skeleton|>
class EquipmentCombatRules:
"""Has all the methods of the basic combat, with the addition of equipment."""
def get_attack(self, attacker, defender):
"""Returns a value for an attack roll. Args: attacker (obj): Character doing the attacking defender (obj): Character being attacked Returns: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EquipmentCombatRules:
"""Has all the methods of the basic combat, with the addition of equipment."""
def get_attack(self, attacker, defender):
"""Returns a value for an attack roll. Args: attacker (obj): Character doing the attacking defender (obj): Character being attacked Returns: attack_value ... | the_stack_v2_python_sparse | evennia/contrib/game_systems/turnbattle/tb_equip.py | evennia/evennia | train | 1,781 |
46e1b6040e5c41d9cd5760ec9902fce4a5acda80 | [
"self.client = aff4.FACTORY.Open(self.client_id, token=self.token)\nself.system = str(self.client.Get(self.client.Schema.SYSTEM))\nself.os_version = str(self.client.Get(self.client.Schema.OS_VERSION))\nself.os_major_version = self.os_version.split('.')[0]\nif self.use_tsk:\n self.path_type = rdfvalue.PathSpec.Pa... | <|body_start_0|>
self.client = aff4.FACTORY.Open(self.client_id, token=self.token)
self.system = str(self.client.Get(self.client.Schema.SYSTEM))
self.os_version = str(self.client.Get(self.client.Schema.OS_VERSION))
self.os_major_version = self.os_version.split('.')[0]
if self.use... | Do the initial work for a system investigation. This encapsulates the different platform specific modules. | WinSystemActivityInvestigation | [
"Apache-2.0",
"DOC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WinSystemActivityInvestigation:
"""Do the initial work for a system investigation. This encapsulates the different platform specific modules."""
def Start(self):
"""Start."""
<|body_0|>
def FinishFlow(self, responses):
"""Complete anything we need to do for each ... | stack_v2_sparse_classes_36k_train_002740 | 10,734 | permissive | [
{
"docstring": "Start.",
"name": "Start",
"signature": "def Start(self)"
},
{
"docstring": "Complete anything we need to do for each flow finishing.",
"name": "FinishFlow",
"signature": "def FinishFlow(self, responses)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005170 | Implement the Python class `WinSystemActivityInvestigation` described below.
Class description:
Do the initial work for a system investigation. This encapsulates the different platform specific modules.
Method signatures and docstrings:
- def Start(self): Start.
- def FinishFlow(self, responses): Complete anything we... | Implement the Python class `WinSystemActivityInvestigation` described below.
Class description:
Do the initial work for a system investigation. This encapsulates the different platform specific modules.
Method signatures and docstrings:
- def Start(self): Start.
- def FinishFlow(self, responses): Complete anything we... | ba1648b97a76f844ffb8e1891cc9e2680f9b1c6e | <|skeleton|>
class WinSystemActivityInvestigation:
"""Do the initial work for a system investigation. This encapsulates the different platform specific modules."""
def Start(self):
"""Start."""
<|body_0|>
def FinishFlow(self, responses):
"""Complete anything we need to do for each ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WinSystemActivityInvestigation:
"""Do the initial work for a system investigation. This encapsulates the different platform specific modules."""
def Start(self):
"""Start."""
self.client = aff4.FACTORY.Open(self.client_id, token=self.token)
self.system = str(self.client.Get(self.c... | the_stack_v2_python_sparse | lib/flows/general/automation.py | defaultnamehere/grr | train | 3 |
32461cec98e979724d01ce2a93d409f178cb4cae | [
"min1 = sys.maxint\nmin2 = sys.maxint\nfor e in nums:\n if e < min1:\n min1 = e\n elif e != min1 and e < min2:\n min2 = e\n elif e > min2:\n return True\nreturn False",
"stk = []\nfor elt in nums:\n while stk and stk[-1] >= elt:\n stk.pop()\n stk.append(elt)\n if len(... | <|body_start_0|>
min1 = sys.maxint
min2 = sys.maxint
for e in nums:
if e < min1:
min1 = e
elif e != min1 and e < min2:
min2 = e
elif e > min2:
return True
return False
<|end_body_0|>
<|body_start_1|>
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def increasingTriplet(self, nums):
"""Brute force: O(N^3) :type nums: List[int] :rtype: bool"""
<|body_0|>
def increasingTripletError(self, nums):
"""use stack :type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_002741 | 1,251 | permissive | [
{
"docstring": "Brute force: O(N^3) :type nums: List[int] :rtype: bool",
"name": "increasingTriplet",
"signature": "def increasingTriplet(self, nums)"
},
{
"docstring": "use stack :type nums: List[int] :rtype: bool",
"name": "increasingTripletError",
"signature": "def increasingTripletEr... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def increasingTriplet(self, nums): Brute force: O(N^3) :type nums: List[int] :rtype: bool
- def increasingTripletError(self, nums): use stack :type nums: List[int] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def increasingTriplet(self, nums): Brute force: O(N^3) :type nums: List[int] :rtype: bool
- def increasingTripletError(self, nums): use stack :type nums: List[int] :rtype: bool
... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def increasingTriplet(self, nums):
"""Brute force: O(N^3) :type nums: List[int] :rtype: bool"""
<|body_0|>
def increasingTripletError(self, nums):
"""use stack :type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def increasingTriplet(self, nums):
"""Brute force: O(N^3) :type nums: List[int] :rtype: bool"""
min1 = sys.maxint
min2 = sys.maxint
for e in nums:
if e < min1:
min1 = e
elif e != min1 and e < min2:
min2 = e
... | the_stack_v2_python_sparse | 334 Increasing Triplet Subsequence.py | Aminaba123/LeetCode | train | 1 | |
e1a658ef177f3a3b89a7b6d6f05d4b227994ac30 | [
"containers = []\n\ndef publish(queue):\n for user, tenant_id in self._iterate_per_tenants():\n self.context['tenants'][tenant_id]['containers'] = []\n for i in range(containers_per_tenant):\n args = (user, self.context['tenants'][tenant_id]['containers'])\n queue.append(args)... | <|body_start_0|>
containers = []
def publish(queue):
for user, tenant_id in self._iterate_per_tenants():
self.context['tenants'][tenant_id]['containers'] = []
for i in range(containers_per_tenant):
args = (user, self.context['tenants'][ten... | Mix-in method for Swift Object Context. | SwiftObjectMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SwiftObjectMixin:
"""Mix-in method for Swift Object Context."""
def _create_containers(self, containers_per_tenant, threads):
"""Create containers and store results in Rally context. :param containers_per_tenant: int, number of containers to create per tenant :param threads: int, num... | stack_v2_sparse_classes_36k_train_002742 | 6,033 | permissive | [
{
"docstring": "Create containers and store results in Rally context. :param containers_per_tenant: int, number of containers to create per tenant :param threads: int, number of threads to use for broker pattern :returns: list of tuples containing (account, container)",
"name": "_create_containers",
"si... | 4 | null | Implement the Python class `SwiftObjectMixin` described below.
Class description:
Mix-in method for Swift Object Context.
Method signatures and docstrings:
- def _create_containers(self, containers_per_tenant, threads): Create containers and store results in Rally context. :param containers_per_tenant: int, number of... | Implement the Python class `SwiftObjectMixin` described below.
Class description:
Mix-in method for Swift Object Context.
Method signatures and docstrings:
- def _create_containers(self, containers_per_tenant, threads): Create containers and store results in Rally context. :param containers_per_tenant: int, number of... | 9ff67887bf848c5966bb4a2f37018500d30dbe45 | <|skeleton|>
class SwiftObjectMixin:
"""Mix-in method for Swift Object Context."""
def _create_containers(self, containers_per_tenant, threads):
"""Create containers and store results in Rally context. :param containers_per_tenant: int, number of containers to create per tenant :param threads: int, num... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SwiftObjectMixin:
"""Mix-in method for Swift Object Context."""
def _create_containers(self, containers_per_tenant, threads):
"""Create containers and store results in Rally context. :param containers_per_tenant: int, number of containers to create per tenant :param threads: int, number of thread... | the_stack_v2_python_sparse | rally_openstack/task/contexts/swift/utils.py | openstack/rally-openstack | train | 41 |
2b9dd1c87a37d5ffa9a2ac6b41c0dc8a8263c406 | [
"base_plugins = [AttributeDict(name='Information', plugin_name='information')]\nextra_cost_plugins = cls._get_extra_cost_plugins()\ndynamic_extra_cost_plugins = cls._get_dynamic_extra_cost_plugins()\nteams_plugins = cls._get_teams_plugins()\nbase_usage_types_plugins = cls._get_base_usage_types_plugins()\nregular_us... | <|body_start_0|>
base_plugins = [AttributeDict(name='Information', plugin_name='information')]
extra_cost_plugins = cls._get_extra_cost_plugins()
dynamic_extra_cost_plugins = cls._get_dynamic_extra_cost_plugins()
teams_plugins = cls._get_teams_plugins()
base_usage_types_plugins =... | Reports for services | ServicesCostsReport | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServicesCostsReport:
"""Reports for services"""
def get_plugins(cls):
"""Returns list of plugins to call, with information and extra cost about each, such as name and arguments"""
<|body_0|>
def _get_report_data(cls, start, end, is_active, forecast, service_environments)... | stack_v2_sparse_classes_36k_train_002743 | 5,357 | permissive | [
{
"docstring": "Returns list of plugins to call, with information and extra cost about each, such as name and arguments",
"name": "get_plugins",
"signature": "def get_plugins(cls)"
},
{
"docstring": "Use plugins to get usages data for given ventures. Plugin logic can be so complicated but for th... | 3 | null | Implement the Python class `ServicesCostsReport` described below.
Class description:
Reports for services
Method signatures and docstrings:
- def get_plugins(cls): Returns list of plugins to call, with information and extra cost about each, such as name and arguments
- def _get_report_data(cls, start, end, is_active,... | Implement the Python class `ServicesCostsReport` described below.
Class description:
Reports for services
Method signatures and docstrings:
- def get_plugins(cls): Returns list of plugins to call, with information and extra cost about each, such as name and arguments
- def _get_report_data(cls, start, end, is_active,... | 51020e4779ea17b47c56f1a55ec57953dd36afbb | <|skeleton|>
class ServicesCostsReport:
"""Reports for services"""
def get_plugins(cls):
"""Returns list of plugins to call, with information and extra cost about each, such as name and arguments"""
<|body_0|>
def _get_report_data(cls, start, end, is_active, forecast, service_environments)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ServicesCostsReport:
"""Reports for services"""
def get_plugins(cls):
"""Returns list of plugins to call, with information and extra cost about each, such as name and arguments"""
base_plugins = [AttributeDict(name='Information', plugin_name='information')]
extra_cost_plugins = cl... | the_stack_v2_python_sparse | src/ralph_scrooge/report/report_services_costs.py | allegro/ralph_pricing | train | 5 |
f12217cde314af78647de5b541f82c4004fde46f | [
"res = ['']\nfor ch in S:\n l = []\n for item in res:\n if ch.isdigit():\n l.append('%s%s' % (item, ch))\n else:\n l.append('%s%s' % (item, ch.lower()))\n l.append('%s%s' % (item, ch.upper()))\n res = l\nreturn res",
"length = len(S)\nif length == 0:\n re... | <|body_start_0|>
res = ['']
for ch in S:
l = []
for item in res:
if ch.isdigit():
l.append('%s%s' % (item, ch))
else:
l.append('%s%s' % (item, ch.lower()))
l.append('%s%s' % (item, ch.uppe... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def letterCasePermutation(self, S):
""":type S: str :rtype: List[str]"""
<|body_0|>
def letterCasePermutation_v1(self, S):
""":type S: str :rtype: List[str]"""
<|body_1|>
def letterCasePermutation_v1(self, S):
""":type S: str :rtype: Li... | stack_v2_sparse_classes_36k_train_002744 | 3,222 | no_license | [
{
"docstring": ":type S: str :rtype: List[str]",
"name": "letterCasePermutation",
"signature": "def letterCasePermutation(self, S)"
},
{
"docstring": ":type S: str :rtype: List[str]",
"name": "letterCasePermutation_v1",
"signature": "def letterCasePermutation_v1(self, S)"
},
{
"d... | 3 | stack_v2_sparse_classes_30k_train_001298 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCasePermutation(self, S): :type S: str :rtype: List[str]
- def letterCasePermutation_v1(self, S): :type S: str :rtype: List[str]
- def letterCasePermutation_v1(self, S)... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCasePermutation(self, S): :type S: str :rtype: List[str]
- def letterCasePermutation_v1(self, S): :type S: str :rtype: List[str]
- def letterCasePermutation_v1(self, S)... | 98fb752c574a6ec5961a274e41a44275b56da194 | <|skeleton|>
class Solution:
def letterCasePermutation(self, S):
""":type S: str :rtype: List[str]"""
<|body_0|>
def letterCasePermutation_v1(self, S):
""":type S: str :rtype: List[str]"""
<|body_1|>
def letterCasePermutation_v1(self, S):
""":type S: str :rtype: Li... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def letterCasePermutation(self, S):
""":type S: str :rtype: List[str]"""
res = ['']
for ch in S:
l = []
for item in res:
if ch.isdigit():
l.append('%s%s' % (item, ch))
else:
l.appe... | the_stack_v2_python_sparse | Challenges/letterCasePermutation.py | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | train | 0 | |
720dd2a675f4a266561c3e84030b1ef6f7f5802a | [
"result = []\nstack = []\nl = len(T) - 1\nwhile l >= 0:\n cur = T[l]\n pos = l\n while stack:\n idx, prev = stack.pop()\n if prev > cur:\n pos = idx\n stack.append((idx, prev))\n break\n result.append(pos - l)\n stack.append((l, cur))\n l -= 1\nreturn... | <|body_start_0|>
result = []
stack = []
l = len(T) - 1
while l >= 0:
cur = T[l]
pos = l
while stack:
idx, prev = stack.pop()
if prev > cur:
pos = idx
stack.append((idx, prev))
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def dailyTemperatures(self, T):
""":type T: List[int] :rtype: List[int]"""
<|body_0|>
def dailyTemperatures1(self, T):
""":type temperatures: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = []
s... | stack_v2_sparse_classes_36k_train_002745 | 2,172 | no_license | [
{
"docstring": ":type T: List[int] :rtype: List[int]",
"name": "dailyTemperatures",
"signature": "def dailyTemperatures(self, T)"
},
{
"docstring": ":type temperatures: List[int] :rtype: List[int]",
"name": "dailyTemperatures1",
"signature": "def dailyTemperatures1(self, T)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dailyTemperatures(self, T): :type T: List[int] :rtype: List[int]
- def dailyTemperatures1(self, T): :type temperatures: List[int] :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dailyTemperatures(self, T): :type T: List[int] :rtype: List[int]
- def dailyTemperatures1(self, T): :type temperatures: List[int] :rtype: List[int]
<|skeleton|>
class Soluti... | 233d12deca34f51c3bb0406831cc07f3b72b50cf | <|skeleton|>
class Solution:
def dailyTemperatures(self, T):
""":type T: List[int] :rtype: List[int]"""
<|body_0|>
def dailyTemperatures1(self, T):
""":type temperatures: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def dailyTemperatures(self, T):
""":type T: List[int] :rtype: List[int]"""
result = []
stack = []
l = len(T) - 1
while l >= 0:
cur = T[l]
pos = l
while stack:
idx, prev = stack.pop()
if prev >... | the_stack_v2_python_sparse | Python/Daily Temperatures/main.py | briansu2004/MyLeet | train | 1 | |
6ef8bf7ca4fdff01b6181dc08bfc497a0f2c7164 | [
"length = len(nums)\nif length == 0:\n self.record = [0]\nelse:\n self.record = [nums[0]]\n for i in range(1, length):\n self.record.append(nums[i] + self.record[i - 1])",
"if i == 0 or j == 0:\n return self.record[max(i, j)]\nelse:\n return self.record[j] - self.record[i - 1] if i < j else ... | <|body_start_0|>
length = len(nums)
if length == 0:
self.record = [0]
else:
self.record = [nums[0]]
for i in range(1, length):
self.record.append(nums[i] + self.record[i - 1])
<|end_body_0|>
<|body_start_1|>
if i == 0 or j == 0:
... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
length = len(nums)
if length == 0:
self... | stack_v2_sparse_classes_36k_train_002746 | 31,532 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, i, j)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001051 | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int
<|skeleton|>
class NumArray:
def __init__(self, nums):
... | dbe8eb449e5b112a71bc1cd4eabfd138304de4a3 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
length = len(nums)
if length == 0:
self.record = [0]
else:
self.record = [nums[0]]
for i in range(1, length):
self.record.append(nums[i] + self.record[i - 1])
... | the_stack_v2_python_sparse | leetcode/leetcode.py | Rivarrl/leetcode_python | train | 3 | |
b751186e072b41eaa4a4d57ebaa6fe20be4b4161 | [
"payload = self.create_object.copy()\nurl = reverse(self.create_url)\nresponse = self.client.post(url, data=payload)\nself.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\nself.assertIn('detail', response.data)\nself.assertEqual(response.data['detail'], STR_401_MESSAGE)",
"user = self.template_use... | <|body_start_0|>
payload = self.create_object.copy()
url = reverse(self.create_url)
response = self.client.post(url, data=payload)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertIn('detail', response.data)
self.assertEqual(response.data['d... | BasicCreateApiTestCaseRunMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicCreateApiTestCaseRunMixin:
def test_create_anonymous(self):
"""Anonymous user should NOT be able to create"""
<|body_0|>
def test_create_staff_user(self):
"""Staff user should be able to create objects"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_002747 | 9,174 | permissive | [
{
"docstring": "Anonymous user should NOT be able to create",
"name": "test_create_anonymous",
"signature": "def test_create_anonymous(self)"
},
{
"docstring": "Staff user should be able to create objects",
"name": "test_create_staff_user",
"signature": "def test_create_staff_user(self)"... | 2 | null | Implement the Python class `BasicCreateApiTestCaseRunMixin` described below.
Class description:
Implement the BasicCreateApiTestCaseRunMixin class.
Method signatures and docstrings:
- def test_create_anonymous(self): Anonymous user should NOT be able to create
- def test_create_staff_user(self): Staff user should be ... | Implement the Python class `BasicCreateApiTestCaseRunMixin` described below.
Class description:
Implement the BasicCreateApiTestCaseRunMixin class.
Method signatures and docstrings:
- def test_create_anonymous(self): Anonymous user should NOT be able to create
- def test_create_staff_user(self): Staff user should be ... | 9baa530f2f3405322f74ccc145641148f253341b | <|skeleton|>
class BasicCreateApiTestCaseRunMixin:
def test_create_anonymous(self):
"""Anonymous user should NOT be able to create"""
<|body_0|>
def test_create_staff_user(self):
"""Staff user should be able to create objects"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BasicCreateApiTestCaseRunMixin:
def test_create_anonymous(self):
"""Anonymous user should NOT be able to create"""
payload = self.create_object.copy()
url = reverse(self.create_url)
response = self.client.post(url, data=payload)
self.assertEqual(response.status_code, st... | the_stack_v2_python_sparse | palvelutori/test_mixins.py | City-of-Turku/munpalvelut_backend | train | 0 | |
9416a281915edd0e510d0de1aebb4aa0bcdebe0c | [
"str = ''\nif strs == []:\n return str\nfor j in range(0, len(strs[0])):\n letter = strs[0][j]\n index = 0\n for i in range(1, len(strs)):\n word_length = len(strs[i])\n if j < word_length:\n if strs[i][j] == letter:\n index += 1\n if index == len(strs) - 1:\n ... | <|body_start_0|>
str = ''
if strs == []:
return str
for j in range(0, len(strs[0])):
letter = strs[0][j]
index = 0
for i in range(1, len(strs)):
word_length = len(strs[i])
if j < word_length:
if s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestCommonPrefix_last(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_0|>
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_1|>
def longestCommonPrefix1(self, strs):
""":type strs: Li... | stack_v2_sparse_classes_36k_train_002748 | 1,997 | no_license | [
{
"docstring": ":type strs: List[str] :rtype: str",
"name": "longestCommonPrefix_last",
"signature": "def longestCommonPrefix_last(self, strs)"
},
{
"docstring": ":type strs: List[str] :rtype: str",
"name": "longestCommonPrefix",
"signature": "def longestCommonPrefix(self, strs)"
},
... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonPrefix_last(self, strs): :type strs: List[str] :rtype: str
- def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str
- def longestCommonPrefix1(se... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonPrefix_last(self, strs): :type strs: List[str] :rtype: str
- def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str
- def longestCommonPrefix1(se... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def longestCommonPrefix_last(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_0|>
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_1|>
def longestCommonPrefix1(self, strs):
""":type strs: Li... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestCommonPrefix_last(self, strs):
""":type strs: List[str] :rtype: str"""
str = ''
if strs == []:
return str
for j in range(0, len(strs[0])):
letter = strs[0][j]
index = 0
for i in range(1, len(strs)):
... | the_stack_v2_python_sparse | LeetCode/String/14_longest_common_prefix.py | XyK0907/for_work | train | 0 | |
c7389dc65df3d130abfba389aca3b4f677314116 | [
"if root is None:\n return 0\nreturn self.partial_max_path_sum(root)[0]",
"if root.left and root.right:\n left_max_sum, left_max_sum_end_with_root = self.partial_max_path_sum(root.left)\n right_max_sum, right_max_sum_end_with_root = self.partial_max_path_sum(root.right)\n max_sum_end_with_root = max(r... | <|body_start_0|>
if root is None:
return 0
return self.partial_max_path_sum(root)[0]
<|end_body_0|>
<|body_start_1|>
if root.left and root.right:
left_max_sum, left_max_sum_end_with_root = self.partial_max_path_sum(root.left)
right_max_sum, right_max_sum_end_... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxPathSum(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def partial_max_path_sum(self, root):
""":param root: :return: max_path_sum, max_path_sum_end_with_root"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root i... | stack_v2_sparse_classes_36k_train_002749 | 2,204 | permissive | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "maxPathSum",
"signature": "def maxPathSum(self, root)"
},
{
"docstring": ":param root: :return: max_path_sum, max_path_sum_end_with_root",
"name": "partial_max_path_sum",
"signature": "def partial_max_path_sum(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002882 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxPathSum(self, root): :type root: TreeNode :rtype: int
- def partial_max_path_sum(self, root): :param root: :return: max_path_sum, max_path_sum_end_with_root | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxPathSum(self, root): :type root: TreeNode :rtype: int
- def partial_max_path_sum(self, root): :param root: :return: max_path_sum, max_path_sum_end_with_root
<|skeleton|>
... | 6ddba1f3b86c40639a8203cbc3373d52301c1b1f | <|skeleton|>
class Solution:
def maxPathSum(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def partial_max_path_sum(self, root):
""":param root: :return: max_path_sum, max_path_sum_end_with_root"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxPathSum(self, root):
""":type root: TreeNode :rtype: int"""
if root is None:
return 0
return self.partial_max_path_sum(root)[0]
def partial_max_path_sum(self, root):
""":param root: :return: max_path_sum, max_path_sum_end_with_root"""
i... | the_stack_v2_python_sparse | algorithms/python/leetcode/BinaryTreeMaximumPathSum.py | ytjia/leetcode | train | 0 | |
7bcf23c8332392ed97bb3fec7180364952dc0d6f | [
"def del_element(node):\n \"\"\"\n A -> B -> C -> ...\n :param node: A\n :param val: B.val\n :return: A->C->..\n \"\"\"\n tmp_node = node.next.next\n del node.next\n node.next = tmp_node\n return node\nwhile head and head.val == val:\n head = ... | <|body_start_0|>
def del_element(node):
"""
A -> B -> C -> ...
:param node: A
:param val: B.val
:return: A->C->..
"""
tmp_node = node.next.next
del node.next
node.n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
"""注意: 1. head为空时 2. 全部删除时 3. ListNode类有默认值 :param head: :param val: :return:"""
<|body_0|>
def removeElements2(self, head: ListNode, val: int) -> ListNode:
"""listnode加一个头结点! a->b->c 0->a->b->... | stack_v2_sparse_classes_36k_train_002750 | 2,684 | no_license | [
{
"docstring": "注意: 1. head为空时 2. 全部删除时 3. ListNode类有默认值 :param head: :param val: :return:",
"name": "removeElements",
"signature": "def removeElements(self, head: ListNode, val: int) -> ListNode"
},
{
"docstring": "listnode加一个头结点! a->b->c 0->a->b->c :param head: :param val: :return:",
"name... | 2 | stack_v2_sparse_classes_30k_train_009888 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElements(self, head: ListNode, val: int) -> ListNode: 注意: 1. head为空时 2. 全部删除时 3. ListNode类有默认值 :param head: :param val: :return:
- def removeElements2(self, head: ListN... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElements(self, head: ListNode, val: int) -> ListNode: 注意: 1. head为空时 2. 全部删除时 3. ListNode类有默认值 :param head: :param val: :return:
- def removeElements2(self, head: ListN... | b1680014ce3f55ba952a1e64241c0cbb783cc436 | <|skeleton|>
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
"""注意: 1. head为空时 2. 全部删除时 3. ListNode类有默认值 :param head: :param val: :return:"""
<|body_0|>
def removeElements2(self, head: ListNode, val: int) -> ListNode:
"""listnode加一个头结点! a->b->c 0->a->b->... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
"""注意: 1. head为空时 2. 全部删除时 3. ListNode类有默认值 :param head: :param val: :return:"""
def del_element(node):
"""
A -> B -> C -> ...
:param node: A
:param... | the_stack_v2_python_sparse | a_203.py | sun510001/leetcode_jianzhi_offer_2 | train | 0 | |
82b600607dccb3c417ef894eb56e357e8620333a | [
"user_id = request.user.id\naddress_id = request.query_params['address_id']\ncategory_id = request.query_params['category_id']\ntry:\n user_address = Address.objects.get(id=address_id, user_id=user_id)\nexcept:\n return Response({'message': 'Wrong Address', 'status': False}, status=status.HTTP_400_BAD_REQUEST... | <|body_start_0|>
user_id = request.user.id
address_id = request.query_params['address_id']
category_id = request.query_params['category_id']
try:
user_address = Address.objects.get(id=address_id, user_id=user_id)
except:
return Response({'message': 'Wrong ... | ProductViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductViewSet:
def list(self, request, *args, **kwargs):
"""list api to retrieve items based on user location and minimum price"""
<|body_0|>
def create(self, request, *args, **kwargs):
"""create item in database"""
<|body_1|>
def retrieve(self, request... | stack_v2_sparse_classes_36k_train_002751 | 6,395 | no_license | [
{
"docstring": "list api to retrieve items based on user location and minimum price",
"name": "list",
"signature": "def list(self, request, *args, **kwargs)"
},
{
"docstring": "create item in database",
"name": "create",
"signature": "def create(self, request, *args, **kwargs)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_020737 | Implement the Python class `ProductViewSet` described below.
Class description:
Implement the ProductViewSet class.
Method signatures and docstrings:
- def list(self, request, *args, **kwargs): list api to retrieve items based on user location and minimum price
- def create(self, request, *args, **kwargs): create ite... | Implement the Python class `ProductViewSet` described below.
Class description:
Implement the ProductViewSet class.
Method signatures and docstrings:
- def list(self, request, *args, **kwargs): list api to retrieve items based on user location and minimum price
- def create(self, request, *args, **kwargs): create ite... | 51f87a1ceddde427028f7229efcbe6abd730c655 | <|skeleton|>
class ProductViewSet:
def list(self, request, *args, **kwargs):
"""list api to retrieve items based on user location and minimum price"""
<|body_0|>
def create(self, request, *args, **kwargs):
"""create item in database"""
<|body_1|>
def retrieve(self, request... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProductViewSet:
def list(self, request, *args, **kwargs):
"""list api to retrieve items based on user location and minimum price"""
user_id = request.user.id
address_id = request.query_params['address_id']
category_id = request.query_params['category_id']
try:
... | the_stack_v2_python_sparse | products/api/views.py | mofahmi99/e_commerce | train | 0 | |
0ea535e4e9f7a1e90d07a5d9b553051827490b41 | [
"self.data = [0]\nfor w_ in w:\n self.data.append(self.data[-1] + w_)\nself.data = self.data[1:]",
"rand = random.randint(1, self.data[-1])\nidx = bisect.bisect_left(self.data, rand)\nreturn idx"
] | <|body_start_0|>
self.data = [0]
for w_ in w:
self.data.append(self.data[-1] + w_)
self.data = self.data[1:]
<|end_body_0|>
<|body_start_1|>
rand = random.randint(1, self.data[-1])
idx = bisect.bisect_left(self.data, rand)
return idx
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.data = [0]
for w_ in w:
self.data.append(self.data[-1] + w_)
se... | stack_v2_sparse_classes_36k_train_002752 | 1,440 | no_license | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, w)"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006227 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int
<|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|... | a5cb862f0c5a3cfd21468141800568c2dedded0a | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, w):
""":type w: List[int]"""
self.data = [0]
for w_ in w:
self.data.append(self.data[-1] + w_)
self.data = self.data[1:]
def pickIndex(self):
""":rtype: int"""
rand = random.randint(1, self.data[-1])
idx = bi... | the_stack_v2_python_sparse | python/leetcode/sampling/528_random_pick_weight.py | Levintsky/topcoder | train | 0 | |
e71679f4724cb5fef6718719cff5f0a1f7e6fb65 | [
"value = value.strip()\nwhile value.endswith('/'):\n value = value[:-1]\nself.getField('branch').set(self, value)",
"list = DisplayList()\ntypes = self.aq_inner.aq_parent.getProposalTypes()\nfor type in types:\n list.add(type, type)\nreturn list",
"parent = self.aq_inner.aq_parent\nmaxId = 0\nfor id in pa... | <|body_start_0|>
value = value.strip()
while value.endswith('/'):
value = value[:-1]
self.getField('branch').set(self, value)
<|end_body_0|>
<|body_start_1|>
list = DisplayList()
types = self.aq_inner.aq_parent.getProposalTypes()
for type in types:
... | What used to be a PLIP. | PSCImprovementProposal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PSCImprovementProposal:
"""What used to be a PLIP."""
def setBranch(self, value):
"""Set the repository branch, stripping off whitespace and any trailing slashes"""
<|body_0|>
def getProposalTypesVocab(self):
"""Get the allowed proposal types."""
<|body_1... | stack_v2_sparse_classes_36k_train_002753 | 10,955 | no_license | [
{
"docstring": "Set the repository branch, stripping off whitespace and any trailing slashes",
"name": "setBranch",
"signature": "def setBranch(self, value)"
},
{
"docstring": "Get the allowed proposal types.",
"name": "getProposalTypesVocab",
"signature": "def getProposalTypesVocab(self... | 3 | stack_v2_sparse_classes_30k_train_019393 | Implement the Python class `PSCImprovementProposal` described below.
Class description:
What used to be a PLIP.
Method signatures and docstrings:
- def setBranch(self, value): Set the repository branch, stripping off whitespace and any trailing slashes
- def getProposalTypesVocab(self): Get the allowed proposal types... | Implement the Python class `PSCImprovementProposal` described below.
Class description:
What used to be a PLIP.
Method signatures and docstrings:
- def setBranch(self, value): Set the repository branch, stripping off whitespace and any trailing slashes
- def getProposalTypesVocab(self): Get the allowed proposal types... | 8a7bdbdb98c3f9fc1073c6061cd2d3a0ec80caf5 | <|skeleton|>
class PSCImprovementProposal:
"""What used to be a PLIP."""
def setBranch(self, value):
"""Set the repository branch, stripping off whitespace and any trailing slashes"""
<|body_0|>
def getProposalTypesVocab(self):
"""Get the allowed proposal types."""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PSCImprovementProposal:
"""What used to be a PLIP."""
def setBranch(self, value):
"""Set the repository branch, stripping off whitespace and any trailing slashes"""
value = value.strip()
while value.endswith('/'):
value = value[:-1]
self.getField('branch').set(... | the_stack_v2_python_sparse | buildout-cache/eggs/Products.PloneSoftwareCenter-1.6.4-py2.7.egg/Products/PloneSoftwareCenter/content/proposal.py | renansfs/Plone_SP | train | 0 |
f1ba6b584cde4ab86970e3ca1c829b1fc9abaf9b | [
"if not nums:\n return []\nm = len(nums)\nres = []\nfor i in range(m):\n tmp = 0\n for j in range(i + 1, m):\n if nums[i] > nums[j]:\n tmp += 1\n res.append(tmp)\nreturn res",
"import bisect\nsortns = []\nres = []\nfor n in reversed(nums):\n idx = bisect.bisect_left(sortns, n)\n ... | <|body_start_0|>
if not nums:
return []
m = len(nums)
res = []
for i in range(m):
tmp = 0
for j in range(i + 1, m):
if nums[i] > nums[j]:
tmp += 1
res.append(tmp)
return res
<|end_body_0|>
<|body... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countSmaller(self, nums):
"""暴力: O(n^2) 超时"""
<|body_0|>
def countSmaller1(self, nums):
"""逆序插入 数组反过来插入一个有序数组(降序)中,插入的位置就是在原数组中位于它右侧的元素的个数。 O(nlogn)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return []
... | stack_v2_sparse_classes_36k_train_002754 | 968 | no_license | [
{
"docstring": "暴力: O(n^2) 超时",
"name": "countSmaller",
"signature": "def countSmaller(self, nums)"
},
{
"docstring": "逆序插入 数组反过来插入一个有序数组(降序)中,插入的位置就是在原数组中位于它右侧的元素的个数。 O(nlogn)",
"name": "countSmaller1",
"signature": "def countSmaller1(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017175 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countSmaller(self, nums): 暴力: O(n^2) 超时
- def countSmaller1(self, nums): 逆序插入 数组反过来插入一个有序数组(降序)中,插入的位置就是在原数组中位于它右侧的元素的个数。 O(nlogn) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countSmaller(self, nums): 暴力: O(n^2) 超时
- def countSmaller1(self, nums): 逆序插入 数组反过来插入一个有序数组(降序)中,插入的位置就是在原数组中位于它右侧的元素的个数。 O(nlogn)
<|skeleton|>
class Solution:
def coun... | 57f303aa6e76f7c5292fa60bffdfddcb4ff9ddfb | <|skeleton|>
class Solution:
def countSmaller(self, nums):
"""暴力: O(n^2) 超时"""
<|body_0|>
def countSmaller1(self, nums):
"""逆序插入 数组反过来插入一个有序数组(降序)中,插入的位置就是在原数组中位于它右侧的元素的个数。 O(nlogn)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countSmaller(self, nums):
"""暴力: O(n^2) 超时"""
if not nums:
return []
m = len(nums)
res = []
for i in range(m):
tmp = 0
for j in range(i + 1, m):
if nums[i] > nums[j]:
tmp += 1
... | the_stack_v2_python_sparse | 4_LEETCODE/1_DataStructure/5_TREE/2_TreeArray/315. 计算右侧小于当前元素的个数.py | fzingithub/SwordRefers2Offer | train | 1 | |
0f6a8f9a0b2354cd6fe61c9fc6ce284261d00112 | [
"for brid, br in cls.Baudrates:\n if baudrate == br:\n return brid\nraise MTException('unsupported baudrate.')",
"for brid, br in cls.Baudrates:\n if baudrate_id == brid:\n return br\nraise MTException('unknown baudrate id.')"
] | <|body_start_0|>
for brid, br in cls.Baudrates:
if baudrate == br:
return brid
raise MTException('unsupported baudrate.')
<|end_body_0|>
<|body_start_1|>
for brid, br in cls.Baudrates:
if baudrate_id == brid:
return br
raise MTExce... | Baudrate information and conversion. | Baudrates | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Baudrates:
"""Baudrate information and conversion."""
def get_BRID(cls, baudrate):
"""Get baudrate id for a given baudrate."""
<|body_0|>
def get_BR(cls, baudrate_id):
"""Get baudrate for a given baudrate id."""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_002755 | 7,681 | no_license | [
{
"docstring": "Get baudrate id for a given baudrate.",
"name": "get_BRID",
"signature": "def get_BRID(cls, baudrate)"
},
{
"docstring": "Get baudrate for a given baudrate id.",
"name": "get_BR",
"signature": "def get_BR(cls, baudrate_id)"
}
] | 2 | null | Implement the Python class `Baudrates` described below.
Class description:
Baudrate information and conversion.
Method signatures and docstrings:
- def get_BRID(cls, baudrate): Get baudrate id for a given baudrate.
- def get_BR(cls, baudrate_id): Get baudrate for a given baudrate id. | Implement the Python class `Baudrates` described below.
Class description:
Baudrate information and conversion.
Method signatures and docstrings:
- def get_BRID(cls, baudrate): Get baudrate id for a given baudrate.
- def get_BR(cls, baudrate_id): Get baudrate for a given baudrate id.
<|skeleton|>
class Baudrates:
... | c49b59e28b0e7de9ab247c7421eb765e77f9eb2c | <|skeleton|>
class Baudrates:
"""Baudrate information and conversion."""
def get_BRID(cls, baudrate):
"""Get baudrate id for a given baudrate."""
<|body_0|>
def get_BR(cls, baudrate_id):
"""Get baudrate for a given baudrate id."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Baudrates:
"""Baudrate information and conversion."""
def get_BRID(cls, baudrate):
"""Get baudrate id for a given baudrate."""
for brid, br in cls.Baudrates:
if baudrate == br:
return brid
raise MTException('unsupported baudrate.')
def get_BR(cls, ... | the_stack_v2_python_sparse | src/xsens_driver/scripts/mtdef.py | Southampton-Maritime-Robotics/DelphinROSv3 | train | 1 |
e94417b36416adbfe227ab0f03b7116556e310e3 | [
"self.common_acl = common_acl\nself.grant_vec = grant_vec\nself.keystone_acl = keystone_acl\nself.swift_read_acl = swift_read_acl\nself.swift_write_acl = swift_write_acl",
"if dictionary is None:\n return None\ncommon_acl = cohesity_management_sdk.models.common_acl_proto.CommonACLProto.from_dictionary(dictiona... | <|body_start_0|>
self.common_acl = common_acl
self.grant_vec = grant_vec
self.keystone_acl = keystone_acl
self.swift_read_acl = swift_read_acl
self.swift_write_acl = swift_write_acl
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
co... | Implementation of the 'ACLProto' model. Protobuf that describes the access control list (ACL) permissions for a bucket or for an object. Attributes: common_acl (CommonACLProto): CommonACL of the Swift container. grant_vec (list of ACLProto_Grant): TODO: Type description here. keystone_acl (KeystoneACLProto): KeystoneAC... | ACLProto | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ACLProto:
"""Implementation of the 'ACLProto' model. Protobuf that describes the access control list (ACL) permissions for a bucket or for an object. Attributes: common_acl (CommonACLProto): CommonACL of the Swift container. grant_vec (list of ACLProto_Grant): TODO: Type description here. keyston... | stack_v2_sparse_classes_36k_train_002756 | 3,081 | permissive | [
{
"docstring": "Constructor for the ACLProto class",
"name": "__init__",
"signature": "def __init__(self, common_acl=None, grant_vec=None, keystone_acl=None, swift_read_acl=None, swift_write_acl=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dicti... | 2 | stack_v2_sparse_classes_30k_train_001725 | Implement the Python class `ACLProto` described below.
Class description:
Implementation of the 'ACLProto' model. Protobuf that describes the access control list (ACL) permissions for a bucket or for an object. Attributes: common_acl (CommonACLProto): CommonACL of the Swift container. grant_vec (list of ACLProto_Grant... | Implement the Python class `ACLProto` described below.
Class description:
Implementation of the 'ACLProto' model. Protobuf that describes the access control list (ACL) permissions for a bucket or for an object. Attributes: common_acl (CommonACLProto): CommonACL of the Swift container. grant_vec (list of ACLProto_Grant... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ACLProto:
"""Implementation of the 'ACLProto' model. Protobuf that describes the access control list (ACL) permissions for a bucket or for an object. Attributes: common_acl (CommonACLProto): CommonACL of the Swift container. grant_vec (list of ACLProto_Grant): TODO: Type description here. keyston... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ACLProto:
"""Implementation of the 'ACLProto' model. Protobuf that describes the access control list (ACL) permissions for a bucket or for an object. Attributes: common_acl (CommonACLProto): CommonACL of the Swift container. grant_vec (list of ACLProto_Grant): TODO: Type description here. keystone_acl (Keysto... | the_stack_v2_python_sparse | cohesity_management_sdk/models/acl_proto.py | cohesity/management-sdk-python | train | 24 |
2e9a48d8a1e226e74422483d98bd35f476f4d882 | [
"maxi = max(nums)\nfor i in nums:\n if i != maxi and i * 2 > maxi:\n return -1\nreturn nums.index(maxi)",
"m = max(nums)\nif all((m >= x * 2 for x in nums if x != m)):\n return nums.index(m)\nreturn -1"
] | <|body_start_0|>
maxi = max(nums)
for i in nums:
if i != maxi and i * 2 > maxi:
return -1
return nums.index(maxi)
<|end_body_0|>
<|body_start_1|>
m = max(nums)
if all((m >= x * 2 for x in nums if x != m)):
return nums.index(m)
retu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def dominantIndex(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def dominantIndex(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
maxi = max(nums)
for i in nums:
... | stack_v2_sparse_classes_36k_train_002757 | 704 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "dominantIndex",
"signature": "def dominantIndex(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "dominantIndex",
"signature": "def dominantIndex(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dominantIndex(self, nums): :type nums: List[int] :rtype: int
- def dominantIndex(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 dominantIndex(self, nums): :type nums: List[int] :rtype: int
- def dominantIndex(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def dominan... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def dominantIndex(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def dominantIndex(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 dominantIndex(self, nums):
""":type nums: List[int] :rtype: int"""
maxi = max(nums)
for i in nums:
if i != maxi and i * 2 > maxi:
return -1
return nums.index(maxi)
def dominantIndex(self, nums):
""":type nums: List[int] :rt... | the_stack_v2_python_sparse | 0747_Largest_Number_At_Least_Twice_of_Others.py | bingli8802/leetcode | train | 0 | |
77123e5295ffb0f4911f0c13bdcc05501ada7114 | [
"N = len(M)\nseen = set()\n\ndef dfs(node):\n for nei, adj in enumerate(M[node]):\n if adj and nei not in seen:\n seen.add(nei)\n dfs(nei)\nans = 0\nfor i in range(N):\n if i not in seen:\n dfs(i)\n ans += 1\nreturn ans",
"if not M or not M[0]:\n return 0\nm = l... | <|body_start_0|>
N = len(M)
seen = set()
def dfs(node):
for nei, adj in enumerate(M[node]):
if adj and nei not in seen:
seen.add(nei)
dfs(nei)
ans = 0
for i in range(N):
if i not in seen:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findCircleNum(self, M):
"""personal solution: https://leetcode.com/problems/friend-circles/discuss/101349/Python-Simple-Explanation :type M: List[List[int]] :rtype: int"""
<|body_0|>
def findCircleNum2(self, M):
"""from submission :param M: :return:"""
... | stack_v2_sparse_classes_36k_train_002758 | 2,487 | no_license | [
{
"docstring": "personal solution: https://leetcode.com/problems/friend-circles/discuss/101349/Python-Simple-Explanation :type M: List[List[int]] :rtype: int",
"name": "findCircleNum",
"signature": "def findCircleNum(self, M)"
},
{
"docstring": "from submission :param M: :return:",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_006920 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findCircleNum(self, M): personal solution: https://leetcode.com/problems/friend-circles/discuss/101349/Python-Simple-Explanation :type M: List[List[int]] :rtype: int
- def fi... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findCircleNum(self, M): personal solution: https://leetcode.com/problems/friend-circles/discuss/101349/Python-Simple-Explanation :type M: List[List[int]] :rtype: int
- def fi... | 2526f8c0dec7101123123740e146ee4081e979ee | <|skeleton|>
class Solution:
def findCircleNum(self, M):
"""personal solution: https://leetcode.com/problems/friend-circles/discuss/101349/Python-Simple-Explanation :type M: List[List[int]] :rtype: int"""
<|body_0|>
def findCircleNum2(self, M):
"""from submission :param M: :return:"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findCircleNum(self, M):
"""personal solution: https://leetcode.com/problems/friend-circles/discuss/101349/Python-Simple-Explanation :type M: List[List[int]] :rtype: int"""
N = len(M)
seen = set()
def dfs(node):
for nei, adj in enumerate(M[node]):
... | the_stack_v2_python_sparse | 547. Friend Circles.py | zhangpengGenedock/leetcode_python | train | 1 | |
6a69df370ec9607afaa3dffb5f765c542dbb4e7a | [
"dp = [[0 for _ in range(k + 1)] for _ in range(n + 1)]\nMOD = 10 ** 9 + 7\ndp[0][0] = 1\nfor i in range(n + 1):\n for j in range(i):\n for m in range(k + 1):\n if m - j >= 0 and m - j <= k:\n dp[i][m] = (dp[i][m] + dp[i - 1][m - j]) % MOD\nreturn dp[n][k]",
"\"\"\"\n dp... | <|body_start_0|>
dp = [[0 for _ in range(k + 1)] for _ in range(n + 1)]
MOD = 10 ** 9 + 7
dp[0][0] = 1
for i in range(n + 1):
for j in range(i):
for m in range(k + 1):
if m - j >= 0 and m - j <= k:
dp[i][m] = (dp[i][... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kInversePairsTLE(self, n, k):
""":type n: int :type k: int :rtype: int"""
<|body_0|>
def kInversePairs(self, n, k):
""":type n: int :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dp = [[0 for _ in range(k + 1)... | stack_v2_sparse_classes_36k_train_002759 | 3,240 | no_license | [
{
"docstring": ":type n: int :type k: int :rtype: int",
"name": "kInversePairsTLE",
"signature": "def kInversePairsTLE(self, n, k)"
},
{
"docstring": ":type n: int :type k: int :rtype: int",
"name": "kInversePairs",
"signature": "def kInversePairs(self, n, k)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kInversePairsTLE(self, n, k): :type n: int :type k: int :rtype: int
- def kInversePairs(self, n, k): :type n: int :type k: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kInversePairsTLE(self, n, k): :type n: int :type k: int :rtype: int
- def kInversePairs(self, n, k): :type n: int :type k: int :rtype: int
<|skeleton|>
class Solution:
... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def kInversePairsTLE(self, n, k):
""":type n: int :type k: int :rtype: int"""
<|body_0|>
def kInversePairs(self, n, k):
""":type n: int :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def kInversePairsTLE(self, n, k):
""":type n: int :type k: int :rtype: int"""
dp = [[0 for _ in range(k + 1)] for _ in range(n + 1)]
MOD = 10 ** 9 + 7
dp[0][0] = 1
for i in range(n + 1):
for j in range(i):
for m in range(k + 1):
... | the_stack_v2_python_sparse | K/KInversePairsArray.py | bssrdf/pyleet | train | 2 | |
45b4c7e3167768d9d2d54de6d1a53f11a8550256 | [
"QActiveViewsListWidgetItem.opened_views += 1\nview_name = f'({QActiveViewsListWidgetItem.opened_views:d}) {view_window.name}'\nsuper().__init__(view_name, parent, _type)\nview_window.setWindowTitle(f'({QActiveViewsListWidgetItem.opened_views:d}) {view_window.windowTitle()} - {view_window.waypoints_model.name}')\nv... | <|body_start_0|>
QActiveViewsListWidgetItem.opened_views += 1
view_name = f'({QActiveViewsListWidgetItem.opened_views:d}) {view_window.name}'
super().__init__(view_name, parent, _type)
view_window.setWindowTitle(f'({QActiveViewsListWidgetItem.opened_views:d}) {view_window.windowTitle()} ... | Subclass of QListWidgetItem, represents an open view in the list of open views. Keeps a reference to the view instance (i.e. the window) it represents in the list of open views. | QActiveViewsListWidgetItem | [
"LicenseRef-scancode-other-permissive",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QActiveViewsListWidgetItem:
"""Subclass of QListWidgetItem, represents an open view in the list of open views. Keeps a reference to the view instance (i.e. the window) it represents in the list of open views."""
def __init__(self, view_window, parent=None, viewsChanged=None, mscolab=False, _... | stack_v2_sparse_classes_36k_train_002760 | 49,238 | permissive | [
{
"docstring": "Add ID number to the title of the corresponding view window.",
"name": "__init__",
"signature": "def __init__(self, view_window, parent=None, viewsChanged=None, mscolab=False, _type=QtWidgets.QListWidgetItem.UserType)"
},
{
"docstring": "Slot that removes this QListWidgetItem fro... | 2 | stack_v2_sparse_classes_30k_train_004274 | Implement the Python class `QActiveViewsListWidgetItem` described below.
Class description:
Subclass of QListWidgetItem, represents an open view in the list of open views. Keeps a reference to the view instance (i.e. the window) it represents in the list of open views.
Method signatures and docstrings:
- def __init__... | Implement the Python class `QActiveViewsListWidgetItem` described below.
Class description:
Subclass of QListWidgetItem, represents an open view in the list of open views. Keeps a reference to the view instance (i.e. the window) it represents in the list of open views.
Method signatures and docstrings:
- def __init__... | 56e9528b552a9d8f2e267661473b8f0e724fd093 | <|skeleton|>
class QActiveViewsListWidgetItem:
"""Subclass of QListWidgetItem, represents an open view in the list of open views. Keeps a reference to the view instance (i.e. the window) it represents in the list of open views."""
def __init__(self, view_window, parent=None, viewsChanged=None, mscolab=False, _... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QActiveViewsListWidgetItem:
"""Subclass of QListWidgetItem, represents an open view in the list of open views. Keeps a reference to the view instance (i.e. the window) it represents in the list of open views."""
def __init__(self, view_window, parent=None, viewsChanged=None, mscolab=False, _type=QtWidget... | the_stack_v2_python_sparse | mslib/msui/msui_mainwindow.py | Open-MSS/MSS | train | 56 |
41f3c2d33a597626cc610bcb6a0aed532131dd2e | [
"payload = ev.payload\nclient_id = int(re.search('^\\\\d+', payload).group())\nweapons = re.findall('([a-zA-Z\\\\.]+):(\\\\d+):(\\\\d+):(\\\\d+):(\\\\d+)', payload)\ngrah = re.findall('([a-zA-Z\\\\.]+):(\\\\d+)', payload)\nevent = events.Q3EVPlayerStats(ev.time, client_id)\nfor weapon_name, shot, hit, pick, drop in... | <|body_start_0|>
payload = ev.payload
client_id = int(re.search('^\\d+', payload).group())
weapons = re.findall('([a-zA-Z\\.]+):(\\d+):(\\d+):(\\d+):(\\d+)', payload)
grah = re.findall('([a-zA-Z\\.]+):(\\d+)', payload)
event = events.Q3EVPlayerStats(ev.time, client_id)
fo... | OspParserMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OspParserMixin:
def parse_weapon_stat(self, ev: RawEvent) -> events.Q3EVPlayerStats:
"""Example: 2 MachineGun:1367:267:0:0 Shotgun:473:107:23:8 G.Launcher:8:1:8:3 R.Launcher:30:11:9:5 LightningGun:403:68:15:10 Plasmagun:326:45:13:8 Given:5252 Recvd:7836 Armor:620 Health:545"""
<|... | stack_v2_sparse_classes_36k_train_002761 | 2,113 | permissive | [
{
"docstring": "Example: 2 MachineGun:1367:267:0:0 Shotgun:473:107:23:8 G.Launcher:8:1:8:3 R.Launcher:30:11:9:5 LightningGun:403:68:15:10 Plasmagun:326:45:13:8 Given:5252 Recvd:7836 Armor:620 Health:545",
"name": "parse_weapon_stat",
"signature": "def parse_weapon_stat(self, ev: RawEvent) -> events.Q3EV... | 2 | stack_v2_sparse_classes_30k_train_019567 | Implement the Python class `OspParserMixin` described below.
Class description:
Implement the OspParserMixin class.
Method signatures and docstrings:
- def parse_weapon_stat(self, ev: RawEvent) -> events.Q3EVPlayerStats: Example: 2 MachineGun:1367:267:0:0 Shotgun:473:107:23:8 G.Launcher:8:1:8:3 R.Launcher:30:11:9:5 L... | Implement the Python class `OspParserMixin` described below.
Class description:
Implement the OspParserMixin class.
Method signatures and docstrings:
- def parse_weapon_stat(self, ev: RawEvent) -> events.Q3EVPlayerStats: Example: 2 MachineGun:1367:267:0:0 Shotgun:473:107:23:8 G.Launcher:8:1:8:3 R.Launcher:30:11:9:5 L... | 0f5ab1807909be24ddb12c58d38437952bff126b | <|skeleton|>
class OspParserMixin:
def parse_weapon_stat(self, ev: RawEvent) -> events.Q3EVPlayerStats:
"""Example: 2 MachineGun:1367:267:0:0 Shotgun:473:107:23:8 G.Launcher:8:1:8:3 R.Launcher:30:11:9:5 LightningGun:403:68:15:10 Plasmagun:326:45:13:8 Given:5252 Recvd:7836 Armor:620 Health:545"""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OspParserMixin:
def parse_weapon_stat(self, ev: RawEvent) -> events.Q3EVPlayerStats:
"""Example: 2 MachineGun:1367:267:0:0 Shotgun:473:107:23:8 G.Launcher:8:1:8:3 R.Launcher:30:11:9:5 LightningGun:403:68:15:10 Plasmagun:326:45:13:8 Given:5252 Recvd:7836 Armor:620 Health:545"""
payload = ev.pay... | the_stack_v2_python_sparse | src/quakestats/core/q3parser/modparse/osp.py | brabiega/quakestats | train | 22 | |
9750f9c0d3e432c43d6dcf4bd5c1eee8f5beeaba | [
"if hasattr(self, '_owning_pipeline') and self._owning_pipeline is not None:\n return self._owning_pipeline\nelse:\n return self.parent().owning_pipeline",
"if self.owning_pipeline is None:\n return []\nreturn list(self.owning_pipeline.filtered_sessions.keys())",
"if self.owning_pipeline is None:\n ... | <|body_start_0|>
if hasattr(self, '_owning_pipeline') and self._owning_pipeline is not None:
return self._owning_pipeline
else:
return self.parent().owning_pipeline
<|end_body_0|>
<|body_start_1|>
if self.owning_pipeline is None:
return []
return list... | Implementors own a pipeline or have access through a parent | PipelineOwningMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PipelineOwningMixin:
"""Implementors own a pipeline or have access through a parent"""
def owning_pipeline(self):
"""The owning_pipeline property."""
<|body_0|>
def all_filtered_session_keys(self):
"""Gets the names of the filters applied and updates the config r... | stack_v2_sparse_classes_36k_train_002762 | 1,315 | permissive | [
{
"docstring": "The owning_pipeline property.",
"name": "owning_pipeline",
"signature": "def owning_pipeline(self)"
},
{
"docstring": "Gets the names of the filters applied and updates the config rows with them.",
"name": "all_filtered_session_keys",
"signature": "def all_filtered_sessio... | 4 | stack_v2_sparse_classes_30k_train_010890 | Implement the Python class `PipelineOwningMixin` described below.
Class description:
Implementors own a pipeline or have access through a parent
Method signatures and docstrings:
- def owning_pipeline(self): The owning_pipeline property.
- def all_filtered_session_keys(self): Gets the names of the filters applied and... | Implement the Python class `PipelineOwningMixin` described below.
Class description:
Implementors own a pipeline or have access through a parent
Method signatures and docstrings:
- def owning_pipeline(self): The owning_pipeline property.
- def all_filtered_session_keys(self): Gets the names of the filters applied and... | 212399d826284b394fce8894ff1a93133aef783f | <|skeleton|>
class PipelineOwningMixin:
"""Implementors own a pipeline or have access through a parent"""
def owning_pipeline(self):
"""The owning_pipeline property."""
<|body_0|>
def all_filtered_session_keys(self):
"""Gets the names of the filters applied and updates the config r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PipelineOwningMixin:
"""Implementors own a pipeline or have access through a parent"""
def owning_pipeline(self):
"""The owning_pipeline property."""
if hasattr(self, '_owning_pipeline') and self._owning_pipeline is not None:
return self._owning_pipeline
else:
... | the_stack_v2_python_sparse | src/pyphoplacecellanalysis/GUI/Qt/Mixins/PipelineOwningMixin.py | CommanderPho/pyPhoPlaceCellAnalysis | train | 1 |
1bd51f95a2baf714c322213714d1e00b613203fe | [
"state = super().get_updated_state(current_stream_state, latest_record)\nif state:\n state[self.cursor_field] = int(state[self.cursor_field])\nreturn state",
"params = super().request_params(**kwargs)\nparams['include'] = 'comment_count'\nreturn params"
] | <|body_start_0|>
state = super().get_updated_state(current_stream_state, latest_record)
if state:
state[self.cursor_field] = int(state[self.cursor_field])
return state
<|end_body_0|>
<|body_start_1|>
params = super().request_params(**kwargs)
params['include'] = 'comm... | Tickets stream: https://developer.zendesk.com/api-reference/ticketing/ticket-management/incremental_exports/ | Tickets | [
"MIT",
"Elastic-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tickets:
"""Tickets stream: https://developer.zendesk.com/api-reference/ticketing/ticket-management/incremental_exports/"""
def get_updated_state(self, current_stream_state: MutableMapping[str, Any], latest_record: Mapping[str, Any]) -> Mapping[str, Any]:
"""Save state as integer"""
... | stack_v2_sparse_classes_36k_train_002763 | 20,471 | permissive | [
{
"docstring": "Save state as integer",
"name": "get_updated_state",
"signature": "def get_updated_state(self, current_stream_state: MutableMapping[str, Any], latest_record: Mapping[str, Any]) -> Mapping[str, Any]"
},
{
"docstring": "Adds the field 'comment_count'",
"name": "request_params",... | 2 | null | Implement the Python class `Tickets` described below.
Class description:
Tickets stream: https://developer.zendesk.com/api-reference/ticketing/ticket-management/incremental_exports/
Method signatures and docstrings:
- def get_updated_state(self, current_stream_state: MutableMapping[str, Any], latest_record: Mapping[s... | Implement the Python class `Tickets` described below.
Class description:
Tickets stream: https://developer.zendesk.com/api-reference/ticketing/ticket-management/incremental_exports/
Method signatures and docstrings:
- def get_updated_state(self, current_stream_state: MutableMapping[str, Any], latest_record: Mapping[s... | 802a8184cdd11c1eb905a54ed07c8732b0c0b807 | <|skeleton|>
class Tickets:
"""Tickets stream: https://developer.zendesk.com/api-reference/ticketing/ticket-management/incremental_exports/"""
def get_updated_state(self, current_stream_state: MutableMapping[str, Any], latest_record: Mapping[str, Any]) -> Mapping[str, Any]:
"""Save state as integer"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Tickets:
"""Tickets stream: https://developer.zendesk.com/api-reference/ticketing/ticket-management/incremental_exports/"""
def get_updated_state(self, current_stream_state: MutableMapping[str, Any], latest_record: Mapping[str, Any]) -> Mapping[str, Any]:
"""Save state as integer"""
state... | the_stack_v2_python_sparse | airbyte-integrations/connectors/source-zendesk-support/source_zendesk_support/streams.py | Velocity-Engineering/airbyte | train | 0 |
30a5ee229f4c1f7362685acc48abbe857b53741a | [
"clen = len(prerequisites)\nif clen == 0:\n return True\nvisited = [0 for _ in range(numCourses)]\ninverse_adj = [set() for _ in range(numCourses)]\nfor second, first in prerequisites:\n inverse_adj[second].add(first)\nfor i in range(numCourses):\n if self.__dfs(i, inverse_adj, visited):\n return Fa... | <|body_start_0|>
clen = len(prerequisites)
if clen == 0:
return True
visited = [0 for _ in range(numCourses)]
inverse_adj = [set() for _ in range(numCourses)]
for second, first in prerequisites:
inverse_adj[second].add(first)
for i in range(numCour... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canFinish(self, numCourses, prerequisites):
""":type numCourses: int 课程门数 :type prerequisites: List[List[int]] 课程与课程之间的关系 :rtype: bool"""
<|body_0|>
def __dfs(self, vertex, inverse_adj, visited):
"""注意:这个递归方法的返回值是返回是否有环 :param vertex: 结点的索引 :param inver... | stack_v2_sparse_classes_36k_train_002764 | 8,289 | no_license | [
{
"docstring": ":type numCourses: int 课程门数 :type prerequisites: List[List[int]] 课程与课程之间的关系 :rtype: bool",
"name": "canFinish",
"signature": "def canFinish(self, numCourses, prerequisites)"
},
{
"docstring": "注意:这个递归方法的返回值是返回是否有环 :param vertex: 结点的索引 :param inverse_adj: 逆邻接表,记录的是当前结点的前驱结点的集合 :par... | 2 | stack_v2_sparse_classes_30k_train_002283 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canFinish(self, numCourses, prerequisites): :type numCourses: int 课程门数 :type prerequisites: List[List[int]] 课程与课程之间的关系 :rtype: bool
- def __dfs(self, vertex, inverse_adj, vis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canFinish(self, numCourses, prerequisites): :type numCourses: int 课程门数 :type prerequisites: List[List[int]] 课程与课程之间的关系 :rtype: bool
- def __dfs(self, vertex, inverse_adj, vis... | fd89d81943d862d9d6e8da661b50afa268b413c8 | <|skeleton|>
class Solution:
def canFinish(self, numCourses, prerequisites):
""":type numCourses: int 课程门数 :type prerequisites: List[List[int]] 课程与课程之间的关系 :rtype: bool"""
<|body_0|>
def __dfs(self, vertex, inverse_adj, visited):
"""注意:这个递归方法的返回值是返回是否有环 :param vertex: 结点的索引 :param inver... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canFinish(self, numCourses, prerequisites):
""":type numCourses: int 课程门数 :type prerequisites: List[List[int]] 课程与课程之间的关系 :rtype: bool"""
clen = len(prerequisites)
if clen == 0:
return True
visited = [0 for _ in range(numCourses)]
inverse_adj =... | the_stack_v2_python_sparse | 207.课程表.py | jzijin/leetcode | train | 1 | |
c62c2f563f3c36428319d5c13bb0644237e3ebd4 | [
"self.total_iterations = 0\nself._current_iteration_delta = 0\nself.last_iteration_delta = 0\nself._model = model\nself._edges = list(model.edges)\nself._current_edge_index = 0\nself._max_iterations = max_iterations\nself._converge_delta = converge_delta",
"self.total_iterations = 0\nself._current_iteration_delta... | <|body_start_0|>
self.total_iterations = 0
self._current_iteration_delta = 0
self.last_iteration_delta = 0
self._model = model
self._edges = list(model.edges)
self._current_edge_index = 0
self._max_iterations = max_iterations
self._converge_delta = converg... | Defines an update ordering where updates are done in both directions for each edge in the cluster graph. | FloodingProtocol | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FloodingProtocol:
"""Defines an update ordering where updates are done in both directions for each edge in the cluster graph."""
def __init__(self, model, max_iterations=30, converge_delta=10 ** (-10)):
"""Constructor. :param model: The model. :param max_iterations: Maximum number of... | stack_v2_sparse_classes_36k_train_002765 | 18,882 | permissive | [
{
"docstring": "Constructor. :param model: The model. :param max_iterations: Maximum number of times to update each edge. :param converge_delta: Stop updates after the change in potential between two passes over all the edges is less than `converge_delta`.",
"name": "__init__",
"signature": "def __init_... | 3 | stack_v2_sparse_classes_30k_train_007025 | Implement the Python class `FloodingProtocol` described below.
Class description:
Defines an update ordering where updates are done in both directions for each edge in the cluster graph.
Method signatures and docstrings:
- def __init__(self, model, max_iterations=30, converge_delta=10 ** (-10)): Constructor. :param m... | Implement the Python class `FloodingProtocol` described below.
Class description:
Defines an update ordering where updates are done in both directions for each edge in the cluster graph.
Method signatures and docstrings:
- def __init__(self, model, max_iterations=30, converge_delta=10 ** (-10)): Constructor. :param m... | 445b2cf8736a4a28cff2b074a32afe8fe6986d53 | <|skeleton|>
class FloodingProtocol:
"""Defines an update ordering where updates are done in both directions for each edge in the cluster graph."""
def __init__(self, model, max_iterations=30, converge_delta=10 ** (-10)):
"""Constructor. :param model: The model. :param max_iterations: Maximum number of... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FloodingProtocol:
"""Defines an update ordering where updates are done in both directions for each edge in the cluster graph."""
def __init__(self, model, max_iterations=30, converge_delta=10 ** (-10)):
"""Constructor. :param model: The model. :param max_iterations: Maximum number of times to upd... | the_stack_v2_python_sparse | Statistical_methods/LoopyBeliefPropagation/pyugm/infer_message.py | WN1695173791/Background-Subtraction-Unsupervised-Learning | train | 1 |
128bc6d37f288a77ec7a17c7877c1157ec936faa | [
"super().__init__()\nself.margin = margin\nself.reduction = reduction or 'none'",
"device = embeddings_pred.device\npairwise_similarity = torch.einsum('se,ae->sa', embeddings_pred, embeddings_true)\nbs = embeddings_pred.shape[0]\nbatch_idx = torch.arange(bs, device=device)\nloss = F.cross_entropy(pairwise_similar... | <|body_start_0|>
super().__init__()
self.margin = margin
self.reduction = reduction or 'none'
<|end_body_0|>
<|body_start_1|>
device = embeddings_pred.device
pairwise_similarity = torch.einsum('se,ae->sa', embeddings_pred, embeddings_true)
bs = embeddings_pred.shape[0]
... | ContrastivePairwiseEmbeddingLoss – proof of concept criterion. Still work in progress. @TODO: Docs. Contribution is welcome. | ContrastivePairwiseEmbeddingLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContrastivePairwiseEmbeddingLoss:
"""ContrastivePairwiseEmbeddingLoss – proof of concept criterion. Still work in progress. @TODO: Docs. Contribution is welcome."""
def __init__(self, margin=1.0, reduction='mean'):
"""Args: margin: margin parameter reduction: criterion reduction type... | stack_v2_sparse_classes_36k_train_002766 | 7,661 | permissive | [
{
"docstring": "Args: margin: margin parameter reduction: criterion reduction type",
"name": "__init__",
"signature": "def __init__(self, margin=1.0, reduction='mean')"
},
{
"docstring": "Forward propagation method for the contrastive loss. Work in progress. Args: embeddings_pred: predicted embe... | 2 | stack_v2_sparse_classes_30k_train_001907 | Implement the Python class `ContrastivePairwiseEmbeddingLoss` described below.
Class description:
ContrastivePairwiseEmbeddingLoss – proof of concept criterion. Still work in progress. @TODO: Docs. Contribution is welcome.
Method signatures and docstrings:
- def __init__(self, margin=1.0, reduction='mean'): Args: mar... | Implement the Python class `ContrastivePairwiseEmbeddingLoss` described below.
Class description:
ContrastivePairwiseEmbeddingLoss – proof of concept criterion. Still work in progress. @TODO: Docs. Contribution is welcome.
Method signatures and docstrings:
- def __init__(self, margin=1.0, reduction='mean'): Args: mar... | e99f90655d0efcf22559a46e928f0f98c9807ebf | <|skeleton|>
class ContrastivePairwiseEmbeddingLoss:
"""ContrastivePairwiseEmbeddingLoss – proof of concept criterion. Still work in progress. @TODO: Docs. Contribution is welcome."""
def __init__(self, margin=1.0, reduction='mean'):
"""Args: margin: margin parameter reduction: criterion reduction type... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContrastivePairwiseEmbeddingLoss:
"""ContrastivePairwiseEmbeddingLoss – proof of concept criterion. Still work in progress. @TODO: Docs. Contribution is welcome."""
def __init__(self, margin=1.0, reduction='mean'):
"""Args: margin: margin parameter reduction: criterion reduction type"""
s... | the_stack_v2_python_sparse | catalyst/contrib/losses/contrastive.py | catalyst-team/catalyst | train | 3,038 |
23a6eb4380fc9dab4b7a01d3bfc50ce7ea5b6d35 | [
"self.name = u'Search'\nQtGui.QWidget.__init__(self, *args, **kargs)\nself.book = book\nself.main_window = main_window\nself.search_line = WWLineEdit(language_name=self.book.structure.language)\nself.casse_checkbox = QtGui.QCheckBox()\nself.regexp_checkbox = QtGui.QCheckBox()\nself.entireword_checkbox = QtGui.QChec... | <|body_start_0|>
self.name = u'Search'
QtGui.QWidget.__init__(self, *args, **kargs)
self.book = book
self.main_window = main_window
self.search_line = WWLineEdit(language_name=self.book.structure.language)
self.casse_checkbox = QtGui.QCheckBox()
self.regexp_checkb... | WWSearchPanel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WWSearchPanel:
def __init__(self, book, main_window=None, *args, **kargs):
"""Pannel that allow to search in the book some word. Some options can be added : casse sensitivity, regular expression, entire word. - book : the book where to search the informations - main_window : the WWMainWi... | stack_v2_sparse_classes_36k_train_002767 | 17,387 | no_license | [
{
"docstring": "Pannel that allow to search in the book some word. Some options can be added : casse sensitivity, regular expression, entire word. - book : the book where to search the informations - main_window : the WWMainWindow instance (it should work with None for test reasons) Known error, some error with... | 4 | stack_v2_sparse_classes_30k_train_017603 | Implement the Python class `WWSearchPanel` described below.
Class description:
Implement the WWSearchPanel class.
Method signatures and docstrings:
- def __init__(self, book, main_window=None, *args, **kargs): Pannel that allow to search in the book some word. Some options can be added : casse sensitivity, regular ex... | Implement the Python class `WWSearchPanel` described below.
Class description:
Implement the WWSearchPanel class.
Method signatures and docstrings:
- def __init__(self, book, main_window=None, *args, **kargs): Pannel that allow to search in the book some word. Some options can be added : casse sensitivity, regular ex... | 922bc7bbc9279653834cb4a168c0a2ea5b797337 | <|skeleton|>
class WWSearchPanel:
def __init__(self, book, main_window=None, *args, **kargs):
"""Pannel that allow to search in the book some word. Some options can be added : casse sensitivity, regular expression, entire word. - book : the book where to search the informations - main_window : the WWMainWi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WWSearchPanel:
def __init__(self, book, main_window=None, *args, **kargs):
"""Pannel that allow to search in the book some word. Some options can be added : casse sensitivity, regular expression, entire word. - book : the book where to search the informations - main_window : the WWMainWindow instance ... | the_stack_v2_python_sparse | script/WolfWriterTabWidget.py | grumpfou/WolfWriter | train | 0 | |
4028e715473d7abaae005468f63aea49dbc9ae04 | [
"self.device_path = device_path\nself.id = id\nself.offline = offline",
"if dictionary is None:\n return None\ndevice_path = dictionary.get('devicePath')\nid = dictionary.get('id')\noffline = dictionary.get('offline')\nreturn cls(device_path, id, offline)"
] | <|body_start_0|>
self.device_path = device_path
self.id = id
self.offline = offline
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
device_path = dictionary.get('devicePath')
id = dictionary.get('id')
offline = dictionary.get('offli... | Implementation of the 'NodeSystemDiskInfo' model. TODO: type description here. Attributes: device_path (string): DevicePath is the device path of the disk. id (long|int): Id is the id of the disk. offline (bool): Offline specifies whether a disk is marked offline. | NodeSystemDiskInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NodeSystemDiskInfo:
"""Implementation of the 'NodeSystemDiskInfo' model. TODO: type description here. Attributes: device_path (string): DevicePath is the device path of the disk. id (long|int): Id is the id of the disk. offline (bool): Offline specifies whether a disk is marked offline."""
d... | stack_v2_sparse_classes_36k_train_002768 | 1,741 | permissive | [
{
"docstring": "Constructor for the NodeSystemDiskInfo class",
"name": "__init__",
"signature": "def __init__(self, device_path=None, id=None, offline=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the o... | 2 | null | Implement the Python class `NodeSystemDiskInfo` described below.
Class description:
Implementation of the 'NodeSystemDiskInfo' model. TODO: type description here. Attributes: device_path (string): DevicePath is the device path of the disk. id (long|int): Id is the id of the disk. offline (bool): Offline specifies whet... | Implement the Python class `NodeSystemDiskInfo` described below.
Class description:
Implementation of the 'NodeSystemDiskInfo' model. TODO: type description here. Attributes: device_path (string): DevicePath is the device path of the disk. id (long|int): Id is the id of the disk. offline (bool): Offline specifies whet... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class NodeSystemDiskInfo:
"""Implementation of the 'NodeSystemDiskInfo' model. TODO: type description here. Attributes: device_path (string): DevicePath is the device path of the disk. id (long|int): Id is the id of the disk. offline (bool): Offline specifies whether a disk is marked offline."""
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NodeSystemDiskInfo:
"""Implementation of the 'NodeSystemDiskInfo' model. TODO: type description here. Attributes: device_path (string): DevicePath is the device path of the disk. id (long|int): Id is the id of the disk. offline (bool): Offline specifies whether a disk is marked offline."""
def __init__(s... | the_stack_v2_python_sparse | cohesity_management_sdk/models/node_system_disk_info.py | cohesity/management-sdk-python | train | 24 |
58572ad946f99a653257c1c0912d5772a35b60bb | [
"self.kind = 'Cluster'\nself.api_version = 'v3'\nreturn super()._prepare_request(requires_id=requires_id, prepend_key=prepend_key, base_path=base_path)",
"previous_state = self\ntry:\n return super().fetch(session=session, requires_id=requires_id, base_path=base_path, error_message=error_message, **params)\nex... | <|body_start_0|>
self.kind = 'Cluster'
self.api_version = 'v3'
return super()._prepare_request(requires_id=requires_id, prepend_key=prepend_key, base_path=base_path)
<|end_body_0|>
<|body_start_1|>
previous_state = self
try:
return super().fetch(session=session, requ... | Cluster | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cluster:
def _prepare_request(self, requires_id=True, prepend_key=True, base_path=None):
"""This is a workaround for the non-properly working default value of the resource framework see openstacksdk.compute.v2.server."""
<|body_0|>
def fetch(self, session, requires_id=True, ... | stack_v2_sparse_classes_36k_train_002769 | 4,430 | permissive | [
{
"docstring": "This is a workaround for the non-properly working default value of the resource framework see openstacksdk.compute.v2.server.",
"name": "_prepare_request",
"signature": "def _prepare_request(self, requires_id=True, prepend_key=True, base_path=None)"
},
{
"docstring": "Work around... | 2 | stack_v2_sparse_classes_30k_train_004866 | Implement the Python class `Cluster` described below.
Class description:
Implement the Cluster class.
Method signatures and docstrings:
- def _prepare_request(self, requires_id=True, prepend_key=True, base_path=None): This is a workaround for the non-properly working default value of the resource framework see openst... | Implement the Python class `Cluster` described below.
Class description:
Implement the Cluster class.
Method signatures and docstrings:
- def _prepare_request(self, requires_id=True, prepend_key=True, base_path=None): This is a workaround for the non-properly working default value of the resource framework see openst... | 809f3796dba48ad0535990caf7519bb9afa71d2d | <|skeleton|>
class Cluster:
def _prepare_request(self, requires_id=True, prepend_key=True, base_path=None):
"""This is a workaround for the non-properly working default value of the resource framework see openstacksdk.compute.v2.server."""
<|body_0|>
def fetch(self, session, requires_id=True, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Cluster:
def _prepare_request(self, requires_id=True, prepend_key=True, base_path=None):
"""This is a workaround for the non-properly working default value of the resource framework see openstacksdk.compute.v2.server."""
self.kind = 'Cluster'
self.api_version = 'v3'
return supe... | the_stack_v2_python_sparse | opentelekom/cce/v3/cluster.py | tsdicloud/python-opentelekom-sdk | train | 0 | |
de9e106ce3605acdd4425ee99b856a83374db9f4 | [
"queryset = super(ProductAdmin, self).get_queryset(request)\nif request.user.is_superuser:\n return queryset\nreturn queryset.filter(author_id=request.user.id)",
"if not obj.author:\n obj.author = request.user\nobj.save()"
] | <|body_start_0|>
queryset = super(ProductAdmin, self).get_queryset(request)
if request.user.is_superuser:
return queryset
return queryset.filter(author_id=request.user.id)
<|end_body_0|>
<|body_start_1|>
if not obj.author:
obj.author = request.user
obj.sa... | ProductAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductAdmin:
def get_queryset(self, request):
"""Show only products created by user"""
<|body_0|>
def save_model(self, request, obj, form, change):
"""Save the user that create the post as author"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
quer... | stack_v2_sparse_classes_36k_train_002770 | 4,618 | no_license | [
{
"docstring": "Show only products created by user",
"name": "get_queryset",
"signature": "def get_queryset(self, request)"
},
{
"docstring": "Save the user that create the post as author",
"name": "save_model",
"signature": "def save_model(self, request, obj, form, change)"
}
] | 2 | null | Implement the Python class `ProductAdmin` described below.
Class description:
Implement the ProductAdmin class.
Method signatures and docstrings:
- def get_queryset(self, request): Show only products created by user
- def save_model(self, request, obj, form, change): Save the user that create the post as author | Implement the Python class `ProductAdmin` described below.
Class description:
Implement the ProductAdmin class.
Method signatures and docstrings:
- def get_queryset(self, request): Show only products created by user
- def save_model(self, request, obj, form, change): Save the user that create the post as author
<|sk... | 3df3984339780f0974aa3da34f955486dd785c88 | <|skeleton|>
class ProductAdmin:
def get_queryset(self, request):
"""Show only products created by user"""
<|body_0|>
def save_model(self, request, obj, form, change):
"""Save the user that create the post as author"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProductAdmin:
def get_queryset(self, request):
"""Show only products created by user"""
queryset = super(ProductAdmin, self).get_queryset(request)
if request.user.is_superuser:
return queryset
return queryset.filter(author_id=request.user.id)
def save_model(sel... | the_stack_v2_python_sparse | healthylife/shop/admin.py | AlbertoSanmartinMartinez/HealthyLife | train | 0 | |
7b8bc374e83151edeaf30faa25c9c22b180cc242 | [
"media_id = params.get('media_id', None)\nif media_id != None:\n if len(media_id) != 1:\n raise Exception('Entity type list endpoints expect only one media ID!')\n media_element = Media.objects.get(pk=media_id[0])\n states = StateType.objects.filter(media=media_element.meta)\n for state in states... | <|body_start_0|>
media_id = params.get('media_id', None)
if media_id != None:
if len(media_id) != 1:
raise Exception('Entity type list endpoints expect only one media ID!')
media_element = Media.objects.get(pk=media_id[0])
states = StateType.objects.fi... | Create or retrieve state types. A state type is the metadata definition object for a state. It includes association type, name, description, and (like other entity types) may have any number of attribute types associated with it. | StateTypeListAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StateTypeListAPI:
"""Create or retrieve state types. A state type is the metadata definition object for a state. It includes association type, name, description, and (like other entity types) may have any number of attribute types associated with it."""
def _get(self, params):
"""Ret... | stack_v2_sparse_classes_36k_train_002771 | 7,310 | permissive | [
{
"docstring": "Retrieve state types. A state type is the metadata definition object for a state. It includes association type, name, description, and (like other entity types) may have any number of attribute types associated with it.",
"name": "_get",
"signature": "def _get(self, params)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_009324 | Implement the Python class `StateTypeListAPI` described below.
Class description:
Create or retrieve state types. A state type is the metadata definition object for a state. It includes association type, name, description, and (like other entity types) may have any number of attribute types associated with it.
Method... | Implement the Python class `StateTypeListAPI` described below.
Class description:
Create or retrieve state types. A state type is the metadata definition object for a state. It includes association type, name, description, and (like other entity types) may have any number of attribute types associated with it.
Method... | 0eb75ee9333316b06f773de2b75e8e797a98ffdb | <|skeleton|>
class StateTypeListAPI:
"""Create or retrieve state types. A state type is the metadata definition object for a state. It includes association type, name, description, and (like other entity types) may have any number of attribute types associated with it."""
def _get(self, params):
"""Ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StateTypeListAPI:
"""Create or retrieve state types. A state type is the metadata definition object for a state. It includes association type, name, description, and (like other entity types) may have any number of attribute types associated with it."""
def _get(self, params):
"""Retrieve state t... | the_stack_v2_python_sparse | main/rest/state_type.py | kristianmk/tator | train | 0 |
bde200ab78ba02cdf6700fe3a5089ff0cacd8f30 | [
"self.color_code = color_code\nself.day = day\nself.month = month\nself.name = name",
"if type(self) is not type(other):\n return NotImplemented\nif self.day != other.day:\n return False\nif self.month != other.month:\n return False\nif self.name != other.name:\n return False\nif self.color_code != ot... | <|body_start_0|>
self.color_code = color_code
self.day = day
self.month = month
self.name = name
<|end_body_0|>
<|body_start_1|>
if type(self) is not type(other):
return NotImplemented
if self.day != other.day:
return False
if self.month !... | Represents a calendar event. Attributes ---------- day : `int` The day's value. month : `int` The month's value. name : `str` The event's name. color_code : `str` Color code to use to highlight the event's name. | CalendarEvent | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CalendarEvent:
"""Represents a calendar event. Attributes ---------- day : `int` The day's value. month : `int` The month's value. name : `str` The event's name. color_code : `str` Color code to use to highlight the event's name."""
def __init__(self, month, day, name, color_code):
"... | stack_v2_sparse_classes_36k_train_002772 | 3,074 | no_license | [
{
"docstring": "Creates a new calendar event. Parameters ---------- month : `int` The month's value. day : `int` The day's value. name : `str` The event's name. color_code : `str` Color code to use to highlight the event's name.",
"name": "__init__",
"signature": "def __init__(self, month, day, name, co... | 4 | stack_v2_sparse_classes_30k_train_018896 | Implement the Python class `CalendarEvent` described below.
Class description:
Represents a calendar event. Attributes ---------- day : `int` The day's value. month : `int` The month's value. name : `str` The event's name. color_code : `str` Color code to use to highlight the event's name.
Method signatures and docst... | Implement the Python class `CalendarEvent` described below.
Class description:
Represents a calendar event. Attributes ---------- day : `int` The day's value. month : `int` The month's value. name : `str` The event's name. color_code : `str` Color code to use to highlight the event's name.
Method signatures and docst... | 74f92b598e86606ea3a269311316cddd84a5215f | <|skeleton|>
class CalendarEvent:
"""Represents a calendar event. Attributes ---------- day : `int` The day's value. month : `int` The month's value. name : `str` The event's name. color_code : `str` Color code to use to highlight the event's name."""
def __init__(self, month, day, name, color_code):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CalendarEvent:
"""Represents a calendar event. Attributes ---------- day : `int` The day's value. month : `int` The month's value. name : `str` The event's name. color_code : `str` Color code to use to highlight the event's name."""
def __init__(self, month, day, name, color_code):
"""Creates a n... | the_stack_v2_python_sparse | koishi/plugins/touhou_calendar/calendar_event.py | HuyaneMatsu/Koishi | train | 17 |
c2d9c3916d607173ab3c2bfd8cf464ac770f52ae | [
"self.continue_on_error = continue_on_error\nself.is_active = is_active\nself.script_params = script_params\nself.script_path = script_path\nself.timeout_secs = timeout_secs",
"if dictionary is None:\n return None\ncontinue_on_error = dictionary.get('continueOnError')\nis_active = dictionary.get('isActive')\ns... | <|body_start_0|>
self.continue_on_error = continue_on_error
self.is_active = is_active
self.script_params = script_params
self.script_path = script_path
self.timeout_secs = timeout_secs
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
... | Implementation of the 'RemoteScriptPathAndParams' model. Specifies the path to the remote script and any parameters expected by the remote script. Attributes: continue_on_error (bool): Specifies if the script needs to continue even if there is an occurence of an error. If this flag is set to true, then backup job will ... | RemoteScriptPathAndParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RemoteScriptPathAndParams:
"""Implementation of the 'RemoteScriptPathAndParams' model. Specifies the path to the remote script and any parameters expected by the remote script. Attributes: continue_on_error (bool): Specifies if the script needs to continue even if there is an occurence of an erro... | stack_v2_sparse_classes_36k_train_002773 | 3,261 | permissive | [
{
"docstring": "Constructor for the RemoteScriptPathAndParams class",
"name": "__init__",
"signature": "def __init__(self, continue_on_error=None, is_active=None, script_params=None, script_path=None, timeout_secs=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args... | 2 | stack_v2_sparse_classes_30k_train_003782 | Implement the Python class `RemoteScriptPathAndParams` described below.
Class description:
Implementation of the 'RemoteScriptPathAndParams' model. Specifies the path to the remote script and any parameters expected by the remote script. Attributes: continue_on_error (bool): Specifies if the script needs to continue e... | Implement the Python class `RemoteScriptPathAndParams` described below.
Class description:
Implementation of the 'RemoteScriptPathAndParams' model. Specifies the path to the remote script and any parameters expected by the remote script. Attributes: continue_on_error (bool): Specifies if the script needs to continue e... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RemoteScriptPathAndParams:
"""Implementation of the 'RemoteScriptPathAndParams' model. Specifies the path to the remote script and any parameters expected by the remote script. Attributes: continue_on_error (bool): Specifies if the script needs to continue even if there is an occurence of an erro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RemoteScriptPathAndParams:
"""Implementation of the 'RemoteScriptPathAndParams' model. Specifies the path to the remote script and any parameters expected by the remote script. Attributes: continue_on_error (bool): Specifies if the script needs to continue even if there is an occurence of an error. If this fl... | the_stack_v2_python_sparse | cohesity_management_sdk/models/remote_script_path_and_params.py | cohesity/management-sdk-python | train | 24 |
aa23386d48b1f39114417a6bda8a2addc65a952b | [
"self.data_path = data_path\nwith h5py.File(self.data_path, 'r') as data:\n self.X = data['X'][:]\n self.cvs = data['cvs'][:].astype('str')\n self.speakers = data['speakers'][:]\n self.cv_accuracy = data['cv_accuracy'][:]\n self.cv_accuracy_baseline = data['cv_accuracy_baseline'][:]\n self.c_accur... | <|body_start_0|>
self.data_path = data_path
with h5py.File(self.data_path, 'r') as data:
self.X = data['X'][:]
self.cvs = data['cvs'][:].astype('str')
self.speakers = data['speakers'][:]
self.cv_accuracy = data['cv_accuracy'][:]
self.cv_accurac... | CV | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CV:
def __init__(self, data_path):
"""Processes consonant-vowel perception dataset obtained from the Chang lab. This class operates on the processed neural data. Parameters ---------- data_path : string The path to the dataset."""
<|body_0|>
def get_design_matrix(self, stimu... | stack_v2_sparse_classes_36k_train_002774 | 3,395 | no_license | [
{
"docstring": "Processes consonant-vowel perception dataset obtained from the Chang lab. This class operates on the processed neural data. Parameters ---------- data_path : string The path to the dataset.",
"name": "__init__",
"signature": "def __init__(self, data_path)"
},
{
"docstring": "Extr... | 3 | null | Implement the Python class `CV` described below.
Class description:
Implement the CV class.
Method signatures and docstrings:
- def __init__(self, data_path): Processes consonant-vowel perception dataset obtained from the Chang lab. This class operates on the processed neural data. Parameters ---------- data_path : s... | Implement the Python class `CV` described below.
Class description:
Implement the CV class.
Method signatures and docstrings:
- def __init__(self, data_path): Processes consonant-vowel perception dataset obtained from the Chang lab. This class operates on the processed neural data. Parameters ---------- data_path : s... | b9ea21c4af1f3101615bb393ff330e3a79f86876 | <|skeleton|>
class CV:
def __init__(self, data_path):
"""Processes consonant-vowel perception dataset obtained from the Chang lab. This class operates on the processed neural data. Parameters ---------- data_path : string The path to the dataset."""
<|body_0|>
def get_design_matrix(self, stimu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CV:
def __init__(self, data_path):
"""Processes consonant-vowel perception dataset obtained from the Chang lab. This class operates on the processed neural data. Parameters ---------- data_path : string The path to the dataset."""
self.data_path = data_path
with h5py.File(self.data_pat... | the_stack_v2_python_sparse | neuropacks/cv/cv.py | BouchardLab/neuropacks | train | 4 | |
abddb939990176bda53e17a35662b50bfea1ba86 | [
"errors = {}\nfor sub_resource in resource.get_sub_resources():\n try:\n cls.release_resource(sub_resource, username)\n except ServerError as ex:\n errors[sub_resource.name] = (ex.ERROR_CODE, str(ex))\nif resource.OWNABLE:\n if username is not None and resource.is_available(username):\n ... | <|body_start_0|>
errors = {}
for sub_resource in resource.get_sub_resources():
try:
cls.release_resource(sub_resource, username)
except ServerError as ex:
errors[sub_resource.name] = (ex.ERROR_CODE, str(ex))
if resource.OWNABLE:
... | Release the given resources one by one. For complex resource, marks also its sub-resources as free. Raises: ResourceReleaseError: if resource is a complex resource and fails. ResourcePermissionError: if resource is locked by other user. ResourceAlreadyAvailableError: if resource was already available. | ReleaseResources | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReleaseResources:
"""Release the given resources one by one. For complex resource, marks also its sub-resources as free. Raises: ResourceReleaseError: if resource is a complex resource and fails. ResourcePermissionError: if resource is locked by other user. ResourceAlreadyAvailableError: if resou... | stack_v2_sparse_classes_36k_train_002775 | 4,862 | permissive | [
{
"docstring": "Mark the resource as free. For complex resource, marks also its sub-resources as free. Args: resource (ResourceData): resource to release. username (str): name of the releasing user. Raises: ResourceReleaseError: if resource is a complex resource and fails. ResourcePermissionError: if resource i... | 2 | stack_v2_sparse_classes_30k_train_001450 | Implement the Python class `ReleaseResources` described below.
Class description:
Release the given resources one by one. For complex resource, marks also its sub-resources as free. Raises: ResourceReleaseError: if resource is a complex resource and fails. ResourcePermissionError: if resource is locked by other user. ... | Implement the Python class `ReleaseResources` described below.
Class description:
Release the given resources one by one. For complex resource, marks also its sub-resources as free. Raises: ResourceReleaseError: if resource is a complex resource and fails. ResourcePermissionError: if resource is locked by other user. ... | c443bc1b99e02f047adfcab9943966f0023f652c | <|skeleton|>
class ReleaseResources:
"""Release the given resources one by one. For complex resource, marks also its sub-resources as free. Raises: ResourceReleaseError: if resource is a complex resource and fails. ResourcePermissionError: if resource is locked by other user. ResourceAlreadyAvailableError: if resou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReleaseResources:
"""Release the given resources one by one. For complex resource, marks also its sub-resources as free. Raises: ResourceReleaseError: if resource is a complex resource and fails. ResourcePermissionError: if resource is locked by other user. ResourceAlreadyAvailableError: if resource was alrea... | the_stack_v2_python_sparse | src/rotest/api/resource_control/release_resources.py | gregoil/rotest | train | 26 |
30f126b48c2c2c1b925fdb0453832f01e9b22b0a | [
"cls.endpoint = '/api/courseentry/'\ncls.course = CourseFactory(name='Course', description='Description', start='2020-01-05', cost=5000, deleted=False)\ncls.student = StudentFactory(user__username='student', user__first_name='Name', user__last_name='Surname', about='About student')\ncls.superuser = User.objects.cre... | <|body_start_0|>
cls.endpoint = '/api/courseentry/'
cls.course = CourseFactory(name='Course', description='Description', start='2020-01-05', cost=5000, deleted=False)
cls.student = StudentFactory(user__username='student', user__first_name='Name', user__last_name='Surname', about='About student')... | Тесты записей на курс | CourseEntryTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CourseEntryTestCase:
"""Тесты записей на курс"""
def setUpTestData(cls):
"""Данные для тесткейса"""
<|body_0|>
def test_course_entry_list(self):
"""Список записей на курс"""
<|body_1|>
def test_get_course_entry(self):
"""Получение записи на к... | stack_v2_sparse_classes_36k_train_002776 | 33,302 | no_license | [
{
"docstring": "Данные для тесткейса",
"name": "setUpTestData",
"signature": "def setUpTestData(cls)"
},
{
"docstring": "Список записей на курс",
"name": "test_course_entry_list",
"signature": "def test_course_entry_list(self)"
},
{
"docstring": "Получение записи на курс",
"n... | 5 | stack_v2_sparse_classes_30k_train_006648 | Implement the Python class `CourseEntryTestCase` described below.
Class description:
Тесты записей на курс
Method signatures and docstrings:
- def setUpTestData(cls): Данные для тесткейса
- def test_course_entry_list(self): Список записей на курс
- def test_get_course_entry(self): Получение записи на курс
- def test_... | Implement the Python class `CourseEntryTestCase` described below.
Class description:
Тесты записей на курс
Method signatures and docstrings:
- def setUpTestData(cls): Данные для тесткейса
- def test_course_entry_list(self): Список записей на курс
- def test_get_course_entry(self): Получение записи на курс
- def test_... | 3de0f8eeb4dbf9ec37b17ece0dde51c9e0f381ac | <|skeleton|>
class CourseEntryTestCase:
"""Тесты записей на курс"""
def setUpTestData(cls):
"""Данные для тесткейса"""
<|body_0|>
def test_course_entry_list(self):
"""Список записей на курс"""
<|body_1|>
def test_get_course_entry(self):
"""Получение записи на к... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CourseEntryTestCase:
"""Тесты записей на курс"""
def setUpTestData(cls):
"""Данные для тесткейса"""
cls.endpoint = '/api/courseentry/'
cls.course = CourseFactory(name='Course', description='Description', start='2020-01-05', cost=5000, deleted=False)
cls.student = StudentFa... | the_stack_v2_python_sparse | education_django/education_app/test_api.py | ilyaignatyev/python-web-otus-ru | train | 0 |
252582162b5d1ef00d22b9799e3277364b18cb80 | [
"if rx == 'Msip1mm':\n self.nhorns = 6\n self.spacing = 0\n self.rotation = 0\n self.RIGHT = np.array([0, 0, 0, 0, 0, 0])\n self.UP = np.array([0, 0, 0, 0, 0, 0])\nelse:\n self.nhorns = 16\n self.spacing = spacing\n self.rotation = rotation / 180.0 * np.pi\n self.RIGHT = np.array([-1.5, -... | <|body_start_0|>
if rx == 'Msip1mm':
self.nhorns = 6
self.spacing = 0
self.rotation = 0
self.RIGHT = np.array([0, 0, 0, 0, 0, 0])
self.UP = np.array([0, 0, 0, 0, 0, 0])
else:
self.nhorns = 16
self.spacing = spacing
... | Class to define the geometry of the SEQUOIA array and provide methods to compute offsets. | Grid | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Grid:
"""Class to define the geometry of the SEQUOIA array and provide methods to compute offsets."""
def __init__(self, rx='Sequoia', spacing=27.9, rotation=46.0):
"""Constructor for Grid class. Args: spacing (float): spacing of beams in grid in arcsec rotation (float): rotation of ... | stack_v2_sparse_classes_36k_train_002777 | 3,326 | no_license | [
{
"docstring": "Constructor for Grid class. Args: spacing (float): spacing of beams in grid in arcsec rotation (float): rotation of array relative to telescope in degrees",
"name": "__init__",
"signature": "def __init__(self, rx='Sequoia', spacing=27.9, rotation=46.0)"
},
{
"docstring": "Returns... | 3 | stack_v2_sparse_classes_30k_train_005545 | Implement the Python class `Grid` described below.
Class description:
Class to define the geometry of the SEQUOIA array and provide methods to compute offsets.
Method signatures and docstrings:
- def __init__(self, rx='Sequoia', spacing=27.9, rotation=46.0): Constructor for Grid class. Args: spacing (float): spacing ... | Implement the Python class `Grid` described below.
Class description:
Class to define the geometry of the SEQUOIA array and provide methods to compute offsets.
Method signatures and docstrings:
- def __init__(self, rx='Sequoia', spacing=27.9, rotation=46.0): Constructor for Grid class. Args: spacing (float): spacing ... | 4064f6ca5d2807fbb99626838493d0f91cbd8748 | <|skeleton|>
class Grid:
"""Class to define the geometry of the SEQUOIA array and provide methods to compute offsets."""
def __init__(self, rx='Sequoia', spacing=27.9, rotation=46.0):
"""Constructor for Grid class. Args: spacing (float): spacing of beams in grid in arcsec rotation (float): rotation of ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Grid:
"""Class to define the geometry of the SEQUOIA array and provide methods to compute offsets."""
def __init__(self, rx='Sequoia', spacing=27.9, rotation=46.0):
"""Constructor for Grid class. Args: spacing (float): spacing of beams in grid in arcsec rotation (float): rotation of array relativ... | the_stack_v2_python_sparse | lmtslr/grid/grid.py | myunm82/SpectralLineReduction | train | 0 |
55a8d31018ec74d8722fc0afe894a7a192e2d665 | [
"schema = AuditListInputSchema()\nparams, errors = schema.load(request.args)\nif errors:\n abort(400, errors)\naudit_query = AuditTable.select(AuditTable, fn.GROUP_CONCAT(ContactTable.name.distinct(), ContactSchema.SEPARATER_NAME_EMAIL, ContactTable.email, python_value=lambda contacts: [dict(zip(['name', 'email'... | <|body_start_0|>
schema = AuditListInputSchema()
params, errors = schema.load(request.args)
if errors:
abort(400, errors)
audit_query = AuditTable.select(AuditTable, fn.GROUP_CONCAT(ContactTable.name.distinct(), ContactSchema.SEPARATER_NAME_EMAIL, ContactTable.email, python_v... | AuditList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuditList:
def get(self):
"""Get audit list"""
<|body_0|>
def post(self):
"""Register new audit"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
schema = AuditListInputSchema()
params, errors = schema.load(request.args)
if errors:
... | stack_v2_sparse_classes_36k_train_002778 | 18,857 | no_license | [
{
"docstring": "Get audit list",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Register new audit",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005848 | Implement the Python class `AuditList` described below.
Class description:
Implement the AuditList class.
Method signatures and docstrings:
- def get(self): Get audit list
- def post(self): Register new audit | Implement the Python class `AuditList` described below.
Class description:
Implement the AuditList class.
Method signatures and docstrings:
- def get(self): Get audit list
- def post(self): Register new audit
<|skeleton|>
class AuditList:
def get(self):
"""Get audit list"""
<|body_0|>
def p... | 7b67aa682d73c8a8d7f0f19b2a90e69c40761c58 | <|skeleton|>
class AuditList:
def get(self):
"""Get audit list"""
<|body_0|>
def post(self):
"""Register new audit"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuditList:
def get(self):
"""Get audit list"""
schema = AuditListInputSchema()
params, errors = schema.load(request.args)
if errors:
abort(400, errors)
audit_query = AuditTable.select(AuditTable, fn.GROUP_CONCAT(ContactTable.name.distinct(), ContactSchema.SE... | the_stack_v2_python_sparse | rem/apis/audit.py | recruit-tech/casval | train | 6 | |
6be13e3da098fb78ed8d0d84db58d4d65237bcd9 | [
"bases = self._bases_\nif not bases or not issubclass(bases[0], AbstractSubSystem):\n from .base_subsystem import SubSystem\n bases = (SubSystem,) + bases\nreturn bases",
"if self._descriptor_type_ is None:\n from .base_subsystem import SubSystemDescriptor\n dsc_type = SubSystemDescriptor\nelse:\n ... | <|body_start_0|>
bases = self._bases_
if not bases or not issubclass(bases[0], AbstractSubSystem):
from .base_subsystem import SubSystem
bases = (SubSystem,) + bases
return bases
<|end_body_0|>
<|body_start_1|>
if self._descriptor_type_ is None:
from ... | Sentinel used to collect declarations or modifications for a subsystem. Parameters ---------- bases : class or tuple of classes, optional Class or classes to use as base class when no matching subpart exists on the driver. checks : str, optional Booelan tests to execute before anything else when attempting use a Featur... | subsystem | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class subsystem:
"""Sentinel used to collect declarations or modifications for a subsystem. Parameters ---------- bases : class or tuple of classes, optional Class or classes to use as base class when no matching subpart exists on the driver. checks : str, optional Booelan tests to execute before anyth... | stack_v2_sparse_classes_36k_train_002779 | 19,444 | permissive | [
{
"docstring": "Add SubSystem in the base classes if necessary. The first class should always be a SubSystem subclass so prepend if it is not so.",
"name": "compute_base_classes",
"signature": "def compute_base_classes(self) -> Tuple[type, ...]"
},
{
"docstring": "Build the descriptor that will ... | 2 | stack_v2_sparse_classes_30k_train_019957 | Implement the Python class `subsystem` described below.
Class description:
Sentinel used to collect declarations or modifications for a subsystem. Parameters ---------- bases : class or tuple of classes, optional Class or classes to use as base class when no matching subpart exists on the driver. checks : str, optiona... | Implement the Python class `subsystem` described below.
Class description:
Sentinel used to collect declarations or modifications for a subsystem. Parameters ---------- bases : class or tuple of classes, optional Class or classes to use as base class when no matching subpart exists on the driver. checks : str, optiona... | 6f004d3e2ee2b788fb4693606cc4092147655ce1 | <|skeleton|>
class subsystem:
"""Sentinel used to collect declarations or modifications for a subsystem. Parameters ---------- bases : class or tuple of classes, optional Class or classes to use as base class when no matching subpart exists on the driver. checks : str, optional Booelan tests to execute before anyth... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class subsystem:
"""Sentinel used to collect declarations or modifications for a subsystem. Parameters ---------- bases : class or tuple of classes, optional Class or classes to use as base class when no matching subpart exists on the driver. checks : str, optional Booelan tests to execute before anything else when... | the_stack_v2_python_sparse | i3py/core/declarative.py | Exopy/i3py | train | 1 |
d69baf0d22806ab3c48a4974095f51d7c249e278 | [
"self.secretWord = word\nself.randomword = [x for x in word]\nself.currentStatus = '_ ' * len(word)\nself.guessedChars = []\nself.numTries = 0",
"print('단어 완성 상태 : ', self.currentStatus)\nprint('사용한 알파벳 : ', self.guessedChars)\nprint('실패한 횟수 : ', self.numTries)\npass",
"self.guessedChars.append(character)\nwhil... | <|body_start_0|>
self.secretWord = word
self.randomword = [x for x in word]
self.currentStatus = '_ ' * len(word)
self.guessedChars = []
self.numTries = 0
<|end_body_0|>
<|body_start_1|>
print('단어 완성 상태 : ', self.currentStatus)
print('사용한 알파벳 : ', self.guessedCha... | Guess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Guess:
def __init__(self, word):
"""선택된 단어 선택한것 파라미터로 받음 1. 단어의 길이에 알맞게 빈 '_' 만들기 2. 입력한 알파벳 적어 넣을 리스트 초기화 3. 실패한 기회 변수 선언"""
<|body_0|>
def display(self):
"""알아낸 글자들과 그 위치를 가리키는 데이터 화면에 출력 + 실패한 횟수와 행맨 상태도 화면에 출력"""
<|body_1|>
def guess(self, character)... | stack_v2_sparse_classes_36k_train_002780 | 1,914 | no_license | [
{
"docstring": "선택된 단어 선택한것 파라미터로 받음 1. 단어의 길이에 알맞게 빈 '_' 만들기 2. 입력한 알파벳 적어 넣을 리스트 초기화 3. 실패한 기회 변수 선언",
"name": "__init__",
"signature": "def __init__(self, word)"
},
{
"docstring": "알아낸 글자들과 그 위치를 가리키는 데이터 화면에 출력 + 실패한 횟수와 행맨 상태도 화면에 출력",
"name": "display",
"signature": "def display(se... | 3 | stack_v2_sparse_classes_30k_train_019780 | Implement the Python class `Guess` described below.
Class description:
Implement the Guess class.
Method signatures and docstrings:
- def __init__(self, word): 선택된 단어 선택한것 파라미터로 받음 1. 단어의 길이에 알맞게 빈 '_' 만들기 2. 입력한 알파벳 적어 넣을 리스트 초기화 3. 실패한 기회 변수 선언
- def display(self): 알아낸 글자들과 그 위치를 가리키는 데이터 화면에 출력 + 실패한 횟수와 행맨 상태도 화면... | Implement the Python class `Guess` described below.
Class description:
Implement the Guess class.
Method signatures and docstrings:
- def __init__(self, word): 선택된 단어 선택한것 파라미터로 받음 1. 단어의 길이에 알맞게 빈 '_' 만들기 2. 입력한 알파벳 적어 넣을 리스트 초기화 3. 실패한 기회 변수 선언
- def display(self): 알아낸 글자들과 그 위치를 가리키는 데이터 화면에 출력 + 실패한 횟수와 행맨 상태도 화면... | bd60fbf3a4d1fb05fef8a40bb8edbe097a9fc324 | <|skeleton|>
class Guess:
def __init__(self, word):
"""선택된 단어 선택한것 파라미터로 받음 1. 단어의 길이에 알맞게 빈 '_' 만들기 2. 입력한 알파벳 적어 넣을 리스트 초기화 3. 실패한 기회 변수 선언"""
<|body_0|>
def display(self):
"""알아낸 글자들과 그 위치를 가리키는 데이터 화면에 출력 + 실패한 횟수와 행맨 상태도 화면에 출력"""
<|body_1|>
def guess(self, character)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Guess:
def __init__(self, word):
"""선택된 단어 선택한것 파라미터로 받음 1. 단어의 길이에 알맞게 빈 '_' 만들기 2. 입력한 알파벳 적어 넣을 리스트 초기화 3. 실패한 기회 변수 선언"""
self.secretWord = word
self.randomword = [x for x in word]
self.currentStatus = '_ ' * len(word)
self.guessedChars = []
self.numTries = ... | the_stack_v2_python_sparse | hangmancod/동설아_guess.py | hj9097/4jo | train | 0 | |
000d5e7d275381ba33b370cb0a33ed75f347656d | [
"if hasattr(self, '_readonly') and self._readonly:\n raise xml.dom.NoModificationAllowedErr('%s is readonly.' % self.__class__)\n return True\nreturn False",
"if not t:\n return ''\nelif isinstance(t, str):\n return t\nelse:\n return ''.join([x[1] for x in t])"
] | <|body_start_0|>
if hasattr(self, '_readonly') and self._readonly:
raise xml.dom.NoModificationAllowedErr('%s is readonly.' % self.__class__)
return True
return False
<|end_body_0|>
<|body_start_1|>
if not t:
return ''
elif isinstance(t, str):
... | Base class for Base, Base2 and _NewBase. **Base and Base2 will be removed in the future!** | _BaseClass | [
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _BaseClass:
"""Base class for Base, Base2 and _NewBase. **Base and Base2 will be removed in the future!**"""
def _checkReadonly(self):
"""Raise xml.dom.NoModificationAllowedErr if rule/... is readonly"""
<|body_0|>
def _valuestr(self, t):
"""Return string value o... | stack_v2_sparse_classes_36k_train_002781 | 30,734 | permissive | [
{
"docstring": "Raise xml.dom.NoModificationAllowedErr if rule/... is readonly",
"name": "_checkReadonly",
"signature": "def _checkReadonly(self)"
},
{
"docstring": "Return string value of t (t may be a string, a list of token tuples or a single tuple in format (type, value, line, col). Mainly u... | 2 | stack_v2_sparse_classes_30k_train_000980 | Implement the Python class `_BaseClass` described below.
Class description:
Base class for Base, Base2 and _NewBase. **Base and Base2 will be removed in the future!**
Method signatures and docstrings:
- def _checkReadonly(self): Raise xml.dom.NoModificationAllowedErr if rule/... is readonly
- def _valuestr(self, t): ... | Implement the Python class `_BaseClass` described below.
Class description:
Base class for Base, Base2 and _NewBase. **Base and Base2 will be removed in the future!**
Method signatures and docstrings:
- def _checkReadonly(self): Raise xml.dom.NoModificationAllowedErr if rule/... is readonly
- def _valuestr(self, t): ... | eff2d6f5442676c04a221a62139864658208f57e | <|skeleton|>
class _BaseClass:
"""Base class for Base, Base2 and _NewBase. **Base and Base2 will be removed in the future!**"""
def _checkReadonly(self):
"""Raise xml.dom.NoModificationAllowedErr if rule/... is readonly"""
<|body_0|>
def _valuestr(self, t):
"""Return string value o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _BaseClass:
"""Base class for Base, Base2 and _NewBase. **Base and Base2 will be removed in the future!**"""
def _checkReadonly(self):
"""Raise xml.dom.NoModificationAllowedErr if rule/... is readonly"""
if hasattr(self, '_readonly') and self._readonly:
raise xml.dom.NoModific... | the_stack_v2_python_sparse | ramdisk/target/common/usr/lib/python3.7/site-packages/cssutils/util.py | BM1880-BIRD/bm1880-system-sdk | train | 29 |
ed6f6866ffbf9b036a82bc82d1ffc47ca6a03fb1 | [
"li = []\nfor index in range(len(s)):\n ch = s[index]\n t = -1\n for i in range(len(li)):\n if li[i][0] == ch:\n t = i\n break\n if t != -1:\n li[t][1].append(index)\n else:\n li.append([ch, [index]])\nfor el in li:\n if len(el[1]) == 1:\n return e... | <|body_start_0|>
li = []
for index in range(len(s)):
ch = s[index]
t = -1
for i in range(len(li)):
if li[i][0] == ch:
t = i
break
if t != -1:
li[t][1].append(index)
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def firstUniqChar1(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def firstUniqChar(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
li = []
for index in range(len(s)):
ch = s[i... | stack_v2_sparse_classes_36k_train_002782 | 1,033 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "firstUniqChar1",
"signature": "def firstUniqChar1(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "firstUniqChar",
"signature": "def firstUniqChar(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009243 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstUniqChar1(self, s): :type s: str :rtype: int
- def firstUniqChar(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstUniqChar1(self, s): :type s: str :rtype: int
- def firstUniqChar(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def firstUniqChar1(self, s):
... | 478bb4019ed38d489171428dced8cbc6f9b3eb52 | <|skeleton|>
class Solution:
def firstUniqChar1(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def firstUniqChar(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def firstUniqChar1(self, s):
""":type s: str :rtype: int"""
li = []
for index in range(len(s)):
ch = s[index]
t = -1
for i in range(len(li)):
if li[i][0] == ch:
t = i
break
... | the_stack_v2_python_sparse | First Unique Character in a String.py | harshittiwari/LeetCode | train | 0 | |
8213e342e7a4f9aea455ea5ad46b3a82f221ccb6 | [
"if self.name is None:\n raise ValueError('can not get feature from unnamed Dataset')\nret = []\nfor i, (shape, types) in enumerate(zip(self.data_shapes, self.data_types)):\n ret.append(L.data('%s_placeholder_%d' % (self.name, i), shape=shape, append_batch_size=False, dtype=types))\nreturn ret",
"if self.na... | <|body_start_0|>
if self.name is None:
raise ValueError('can not get feature from unnamed Dataset')
ret = []
for i, (shape, types) in enumerate(zip(self.data_shapes, self.data_types)):
ret.append(L.data('%s_placeholder_%d' % (self.name, i), shape=shape, append_batch_size=... | Pyreader based Dataset | Dataset | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dataset:
"""Pyreader based Dataset"""
def placeholders(self):
"""doc"""
<|body_0|>
def features(self):
"""start point of net building. call this in a program scope"""
<|body_1|>
def start(self, places=None):
"""start Pyreader"""
<|bod... | stack_v2_sparse_classes_36k_train_002783 | 2,715 | permissive | [
{
"docstring": "doc",
"name": "placeholders",
"signature": "def placeholders(self)"
},
{
"docstring": "start point of net building. call this in a program scope",
"name": "features",
"signature": "def features(self)"
},
{
"docstring": "start Pyreader",
"name": "start",
"s... | 3 | null | Implement the Python class `Dataset` described below.
Class description:
Pyreader based Dataset
Method signatures and docstrings:
- def placeholders(self): doc
- def features(self): start point of net building. call this in a program scope
- def start(self, places=None): start Pyreader | Implement the Python class `Dataset` described below.
Class description:
Pyreader based Dataset
Method signatures and docstrings:
- def placeholders(self): doc
- def features(self): start point of net building. call this in a program scope
- def start(self, places=None): start Pyreader
<|skeleton|>
class Dataset:
... | e6ab0261eb719c21806bbadfd94001ecfe27de45 | <|skeleton|>
class Dataset:
"""Pyreader based Dataset"""
def placeholders(self):
"""doc"""
<|body_0|>
def features(self):
"""start point of net building. call this in a program scope"""
<|body_1|>
def start(self, places=None):
"""start Pyreader"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dataset:
"""Pyreader based Dataset"""
def placeholders(self):
"""doc"""
if self.name is None:
raise ValueError('can not get feature from unnamed Dataset')
ret = []
for i, (shape, types) in enumerate(zip(self.data_shapes, self.data_types)):
ret.appen... | the_stack_v2_python_sparse | competition/ogbg_molhiv/propeller/paddle/data/functional.py | PaddlePaddle/PaddleHelix | train | 771 |
e7f2bdf4ed29a2a57c82c75843a286abf2086bd4 | [
"send_mock = self.PatchObject(alerts.SmtpServer, 'Send')\nalerts.SendEmailLog('mail', 'root@localhost')\nself.assertEqual(send_mock.call_count, 1)",
"send_mock = self.PatchObject(alerts.GmailServer, 'Send')\nalerts.SendEmailLog('mail', 'root@localhost', server=alerts.GmailServer(token_cache_file='fakefile'))\nsel... | <|body_start_0|>
send_mock = self.PatchObject(alerts.SmtpServer, 'Send')
alerts.SendEmailLog('mail', 'root@localhost')
self.assertEqual(send_mock.call_count, 1)
<|end_body_0|>
<|body_start_1|>
send_mock = self.PatchObject(alerts.GmailServer, 'Send')
alerts.SendEmailLog('mail', '... | Tests for SendEmailLog(). | SendEmailLogTest | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SendEmailLogTest:
"""Tests for SendEmailLog()."""
def testSmtp(self):
"""Smtp sanity check."""
<|body_0|>
def testGmail(self):
"""Gmail sanity check."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
send_mock = self.PatchObject(alerts.SmtpServer,... | stack_v2_sparse_classes_36k_train_002784 | 6,312 | permissive | [
{
"docstring": "Smtp sanity check.",
"name": "testSmtp",
"signature": "def testSmtp(self)"
},
{
"docstring": "Gmail sanity check.",
"name": "testGmail",
"signature": "def testGmail(self)"
}
] | 2 | null | Implement the Python class `SendEmailLogTest` described below.
Class description:
Tests for SendEmailLog().
Method signatures and docstrings:
- def testSmtp(self): Smtp sanity check.
- def testGmail(self): Gmail sanity check. | Implement the Python class `SendEmailLogTest` described below.
Class description:
Tests for SendEmailLog().
Method signatures and docstrings:
- def testSmtp(self): Smtp sanity check.
- def testGmail(self): Gmail sanity check.
<|skeleton|>
class SendEmailLogTest:
"""Tests for SendEmailLog()."""
def testSmtp(... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class SendEmailLogTest:
"""Tests for SendEmailLog()."""
def testSmtp(self):
"""Smtp sanity check."""
<|body_0|>
def testGmail(self):
"""Gmail sanity check."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SendEmailLogTest:
"""Tests for SendEmailLog()."""
def testSmtp(self):
"""Smtp sanity check."""
send_mock = self.PatchObject(alerts.SmtpServer, 'Send')
alerts.SendEmailLog('mail', 'root@localhost')
self.assertEqual(send_mock.call_count, 1)
def testGmail(self):
... | the_stack_v2_python_sparse | third_party/chromite/lib/alerts_unittest.py | metux/chromium-suckless | train | 5 |
082a2f2d20ee3f5f917d5ebd666e3f806ea84c4a | [
"logger = logging.getLogger('mliyweb.auth')\ntry:\n function = loadFunction('cleanAuthUsername', AUTH_PLUGIN, {})\n username = function(username)\nexcept NameError:\n logger.debug('did not find auth implementation')\nreturn username",
"logger = logging.getLogger('mliyweb.auth')\ntry:\n function = load... | <|body_start_0|>
logger = logging.getLogger('mliyweb.auth')
try:
function = loadFunction('cleanAuthUsername', AUTH_PLUGIN, {})
username = function(username)
except NameError:
logger.debug('did not find auth implementation')
return username
<|end_body_0... | Implements custom auth backend to centralize parsing of isso http headers | MliyBackend | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MliyBackend:
"""Implements custom auth backend to centralize parsing of isso http headers"""
def clean_username(self, username):
"""remove isso trailing stuff from the user name"""
<|body_0|>
def configure_user(self, user):
"""add additional isso information to u... | stack_v2_sparse_classes_36k_train_002785 | 3,576 | permissive | [
{
"docstring": "remove isso trailing stuff from the user name",
"name": "clean_username",
"signature": "def clean_username(self, username)"
},
{
"docstring": "add additional isso information to user object so it behaves as much like a conventional user object as possible. The problem here is tha... | 2 | stack_v2_sparse_classes_30k_train_012346 | Implement the Python class `MliyBackend` described below.
Class description:
Implements custom auth backend to centralize parsing of isso http headers
Method signatures and docstrings:
- def clean_username(self, username): remove isso trailing stuff from the user name
- def configure_user(self, user): add additional ... | Implement the Python class `MliyBackend` described below.
Class description:
Implements custom auth backend to centralize parsing of isso http headers
Method signatures and docstrings:
- def clean_username(self, username): remove isso trailing stuff from the user name
- def configure_user(self, user): add additional ... | a6fd56ad8a0de97d9862569d02e5d0f65c181acf | <|skeleton|>
class MliyBackend:
"""Implements custom auth backend to centralize parsing of isso http headers"""
def clean_username(self, username):
"""remove isso trailing stuff from the user name"""
<|body_0|>
def configure_user(self, user):
"""add additional isso information to u... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MliyBackend:
"""Implements custom auth backend to centralize parsing of isso http headers"""
def clean_username(self, username):
"""remove isso trailing stuff from the user name"""
logger = logging.getLogger('mliyweb.auth')
try:
function = loadFunction('cleanAuthUserna... | the_stack_v2_python_sparse | mliyweb/auth.py | FINRAOS/MLiy | train | 13 |
45c2f4a015d86df7d02d32ff5484c3cc1501fc7a | [
"def check(codename):\n r = check_object_permission(user_obj, codename, obj)\n if r is None:\n return True\n return r\nif not isinstance(codenames, (list, tuple)):\n codenames = (codenames,)\nreturn any((check(codename) for codename in codenames))",
"if perm not in ('django_comments.add_comment... | <|body_start_0|>
def check(codename):
r = check_object_permission(user_obj, codename, obj)
if r is None:
return True
return r
if not isinstance(codenames, (list, tuple)):
codenames = (codenames,)
return any((check(codename) for code... | CommentPermissionLogic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentPermissionLogic:
def _check_object_permissions(self, user_obj, codenames, obj):
"""指定されたユーザーが指定された省略形パーミッションのどれか一つでも 対象オブジェクトに対して持つか調べる Args: user_obj (user instance): 対象ユーザー codenames (list or tuple): 省略形パーミッションリスト obj (model instance): 対象オブジェクト Returns: bool"""
<|body_0|... | stack_v2_sparse_classes_36k_train_002786 | 3,580 | no_license | [
{
"docstring": "指定されたユーザーが指定された省略形パーミッションのどれか一つでも 対象オブジェクトに対して持つか調べる Args: user_obj (user instance): 対象ユーザー codenames (list or tuple): 省略形パーミッションリスト obj (model instance): 対象オブジェクト Returns: bool",
"name": "_check_object_permissions",
"signature": "def _check_object_permissions(self, user_obj, codenames, ... | 2 | null | Implement the Python class `CommentPermissionLogic` described below.
Class description:
Implement the CommentPermissionLogic class.
Method signatures and docstrings:
- def _check_object_permissions(self, user_obj, codenames, obj): 指定されたユーザーが指定された省略形パーミッションのどれか一つでも 対象オブジェクトに対して持つか調べる Args: user_obj (user instance): 対象... | Implement the Python class `CommentPermissionLogic` described below.
Class description:
Implement the CommentPermissionLogic class.
Method signatures and docstrings:
- def _check_object_permissions(self, user_obj, codenames, obj): 指定されたユーザーが指定された省略形パーミッションのどれか一つでも 対象オブジェクトに対して持つか調べる Args: user_obj (user instance): 対象... | 8f9a850c4df41b0fc1da5b73189772552d5cd531 | <|skeleton|>
class CommentPermissionLogic:
def _check_object_permissions(self, user_obj, codenames, obj):
"""指定されたユーザーが指定された省略形パーミッションのどれか一つでも 対象オブジェクトに対して持つか調べる Args: user_obj (user instance): 対象ユーザー codenames (list or tuple): 省略形パーミッションリスト obj (model instance): 対象オブジェクト Returns: bool"""
<|body_0|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommentPermissionLogic:
def _check_object_permissions(self, user_obj, codenames, obj):
"""指定されたユーザーが指定された省略形パーミッションのどれか一つでも 対象オブジェクトに対して持つか調べる Args: user_obj (user instance): 対象ユーザー codenames (list or tuple): 省略形パーミッションリスト obj (model instance): 対象オブジェクト Returns: bool"""
def check(codename):
... | the_stack_v2_python_sparse | src/kawaz/core/comments/perms.py | kawazrepos/Kawaz3rd | train | 7 | |
73dfd60aae18ce455bdc3908d8c3c58fa22f1d19 | [
"path = self.SUB_BASEURL + '/' + account + '/' + name\nurl = build_url(choice(self.list_hosts), path=path)\nif retroactive:\n raise NotImplementedError('Retroactive mode is not implemented')\nif filter_ and (not isinstance(filter_, dict)):\n raise TypeError('filter should be a dict')\nif replication_rules and... | <|body_start_0|>
path = self.SUB_BASEURL + '/' + account + '/' + name
url = build_url(choice(self.list_hosts), path=path)
if retroactive:
raise NotImplementedError('Retroactive mode is not implemented')
if filter_ and (not isinstance(filter_, dict)):
raise TypeErr... | SubscriptionClient class for working with subscriptions | SubscriptionClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubscriptionClient:
"""SubscriptionClient class for working with subscriptions"""
def add_subscription(self, name, account, filter_, replication_rules, comments, lifetime, retroactive, dry_run, priority=3):
"""Adds a new subscription which will be verified against every new added fil... | stack_v2_sparse_classes_36k_train_002787 | 7,980 | permissive | [
{
"docstring": "Adds a new subscription which will be verified against every new added file and dataset :param name: Name of the subscription :type: String :param account: Account identifier :type account: String :param filter_: Dictionary of attributes by which the input data should be filtered **Example**: ``... | 4 | stack_v2_sparse_classes_30k_train_002030 | Implement the Python class `SubscriptionClient` described below.
Class description:
SubscriptionClient class for working with subscriptions
Method signatures and docstrings:
- def add_subscription(self, name, account, filter_, replication_rules, comments, lifetime, retroactive, dry_run, priority=3): Adds a new subscr... | Implement the Python class `SubscriptionClient` described below.
Class description:
SubscriptionClient class for working with subscriptions
Method signatures and docstrings:
- def add_subscription(self, name, account, filter_, replication_rules, comments, lifetime, retroactive, dry_run, priority=3): Adds a new subscr... | 7f0d229ac0b3bc7dec12c6e158bea2b82d414a3b | <|skeleton|>
class SubscriptionClient:
"""SubscriptionClient class for working with subscriptions"""
def add_subscription(self, name, account, filter_, replication_rules, comments, lifetime, retroactive, dry_run, priority=3):
"""Adds a new subscription which will be verified against every new added fil... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubscriptionClient:
"""SubscriptionClient class for working with subscriptions"""
def add_subscription(self, name, account, filter_, replication_rules, comments, lifetime, retroactive, dry_run, priority=3):
"""Adds a new subscription which will be verified against every new added file and dataset... | the_stack_v2_python_sparse | lib/rucio/client/subscriptionclient.py | rucio/rucio | train | 232 |
c6c022bbcca9e7d99d7ed86a9ffff789df0f7855 | [
"try:\n backend = self.backends[backend_name]\nexcept KeyError:\n return False\nreturn backend._config.get('router.celery.eager', False)",
"eager = self.is_eager(msg.connections[0].backend.name)\nif eager:\n logger.debug('Executing in current process')\n receive_async(msg.text, msg.connections[0].pk, ... | <|body_start_0|>
try:
backend = self.backends[backend_name]
except KeyError:
return False
return backend._config.get('router.celery.eager', False)
<|end_body_0|>
<|body_start_1|>
eager = self.is_eager(msg.connections[0].backend.name)
if eager:
... | Skeleton router only used to execute the Celery task. | CeleryRouter | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CeleryRouter:
"""Skeleton router only used to execute the Celery task."""
def is_eager(self, backend_name):
"""Return whether this backend is eager, meaning it runs tasks synchronously rather than queueing them to celery. A backend configures its eagerness by setting the backend conf... | stack_v2_sparse_classes_36k_train_002788 | 2,063 | permissive | [
{
"docstring": "Return whether this backend is eager, meaning it runs tasks synchronously rather than queueing them to celery. A backend configures its eagerness by setting the backend configuration value ``router.celery.eager`` to True or False. The default is False.",
"name": "is_eager",
"signature": ... | 3 | null | Implement the Python class `CeleryRouter` described below.
Class description:
Skeleton router only used to execute the Celery task.
Method signatures and docstrings:
- def is_eager(self, backend_name): Return whether this backend is eager, meaning it runs tasks synchronously rather than queueing them to celery. A bac... | Implement the Python class `CeleryRouter` described below.
Class description:
Skeleton router only used to execute the Celery task.
Method signatures and docstrings:
- def is_eager(self, backend_name): Return whether this backend is eager, meaning it runs tasks synchronously rather than queueing them to celery. A bac... | aaa2ddab68e19d979525c3823c3ec0e646e92c83 | <|skeleton|>
class CeleryRouter:
"""Skeleton router only used to execute the Celery task."""
def is_eager(self, backend_name):
"""Return whether this backend is eager, meaning it runs tasks synchronously rather than queueing them to celery. A backend configures its eagerness by setting the backend conf... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CeleryRouter:
"""Skeleton router only used to execute the Celery task."""
def is_eager(self, backend_name):
"""Return whether this backend is eager, meaning it runs tasks synchronously rather than queueing them to celery. A backend configures its eagerness by setting the backend configuration val... | the_stack_v2_python_sparse | rapidsms/router/celery/router.py | rapidsms/rapidsms | train | 409 |
68ec0ec0f91b43203cf0411516d4bc84b1851001 | [
"thisgroup = cls._groups[group]\nif strict and name in thisgroup:\n msg = 'Factory already registered for the `%s` widget in the `%s` widget group.'\n raise ValueError(msg % (name, group))\nthisgroup[name] = factory",
"thesegroups = cls._groups\nfor group in groups:\n if group in thesegroups:\n th... | <|body_start_0|>
thisgroup = cls._groups[group]
if strict and name in thisgroup:
msg = 'Factory already registered for the `%s` widget in the `%s` widget group.'
raise ValueError(msg % (name, group))
thisgroup[name] = factory
<|end_body_0|>
<|body_start_1|>
these... | A class for registering Wx widget factories. This is a process-widget registry class. Interaction is done through the two classmethods `register` and `lookup`. | WxWidgetRegistry | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WxWidgetRegistry:
"""A class for registering Wx widget factories. This is a process-widget registry class. Interaction is done through the two classmethods `register` and `lookup`."""
def register(cls, name, factory, group, strict=False):
"""Registery a widget factory. Parameters ---... | stack_v2_sparse_classes_36k_train_002789 | 2,274 | permissive | [
{
"docstring": "Registery a widget factory. Parameters ---------- name : str The name of the Enaml widget class which is implemented by the class returned by the given factory. factory : callable A callable which takes no arguments and returns the class which implements the widget. group : str The widget group ... | 2 | null | Implement the Python class `WxWidgetRegistry` described below.
Class description:
A class for registering Wx widget factories. This is a process-widget registry class. Interaction is done through the two classmethods `register` and `lookup`.
Method signatures and docstrings:
- def register(cls, name, factory, group, ... | Implement the Python class `WxWidgetRegistry` described below.
Class description:
A class for registering Wx widget factories. This is a process-widget registry class. Interaction is done through the two classmethods `register` and `lookup`.
Method signatures and docstrings:
- def register(cls, name, factory, group, ... | 424bba29219de58fe9e47196de6763de8b2009f2 | <|skeleton|>
class WxWidgetRegistry:
"""A class for registering Wx widget factories. This is a process-widget registry class. Interaction is done through the two classmethods `register` and `lookup`."""
def register(cls, name, factory, group, strict=False):
"""Registery a widget factory. Parameters ---... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WxWidgetRegistry:
"""A class for registering Wx widget factories. This is a process-widget registry class. Interaction is done through the two classmethods `register` and `lookup`."""
def register(cls, name, factory, group, strict=False):
"""Registery a widget factory. Parameters ---------- name ... | the_stack_v2_python_sparse | enaml/wx/wx_widget_registry.py | enthought/enaml | train | 17 |
93c737d3f5578565390a21f9365cb03d3161f42c | [
"if self.id.text:\n match = BLOG_ID_PATTERN.match(self.id.text)\n if match:\n return match.group(2)\n else:\n return BLOG_ID2_PATTERN.match(self.id.text).group(2)\nreturn None",
"for link in self.link:\n if link.rel == 'alternate':\n return urllib.parse.urlparse(link.href)[1].spli... | <|body_start_0|>
if self.id.text:
match = BLOG_ID_PATTERN.match(self.id.text)
if match:
return match.group(2)
else:
return BLOG_ID2_PATTERN.match(self.id.text).group(2)
return None
<|end_body_0|>
<|body_start_1|>
for link in se... | Adds convenience methods inherited by all Blogger entries. | BloggerEntry | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BloggerEntry:
"""Adds convenience methods inherited by all Blogger entries."""
def get_blog_id(self):
"""Extracts the Blogger id of this blog. This method is useful when contructing URLs by hand. The blog id is often used in blogger operation URLs. This should not be confused with th... | stack_v2_sparse_classes_36k_train_002790 | 4,559 | permissive | [
{
"docstring": "Extracts the Blogger id of this blog. This method is useful when contructing URLs by hand. The blog id is often used in blogger operation URLs. This should not be confused with the id member of a BloggerBlog. The id element is the Atom id XML element. The blog id which this method returns is a p... | 2 | null | Implement the Python class `BloggerEntry` described below.
Class description:
Adds convenience methods inherited by all Blogger entries.
Method signatures and docstrings:
- def get_blog_id(self): Extracts the Blogger id of this blog. This method is useful when contructing URLs by hand. The blog id is often used in bl... | Implement the Python class `BloggerEntry` described below.
Class description:
Adds convenience methods inherited by all Blogger entries.
Method signatures and docstrings:
- def get_blog_id(self): Extracts the Blogger id of this blog. This method is useful when contructing URLs by hand. The blog id is often used in bl... | 26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891 | <|skeleton|>
class BloggerEntry:
"""Adds convenience methods inherited by all Blogger entries."""
def get_blog_id(self):
"""Extracts the Blogger id of this blog. This method is useful when contructing URLs by hand. The blog id is often used in blogger operation URLs. This should not be confused with th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BloggerEntry:
"""Adds convenience methods inherited by all Blogger entries."""
def get_blog_id(self):
"""Extracts the Blogger id of this blog. This method is useful when contructing URLs by hand. The blog id is often used in blogger operation URLs. This should not be confused with the id member o... | the_stack_v2_python_sparse | python3-alpha/python-libs/gdata/blogger/data.py | kuri65536/python-for-android | train | 280 |
539a8d22b45701b95509a9a63e1078678f03030a | [
"uri = '/sunxing-customer-service/api/v1/im/init'\nallure.attach(SX_PC_kf_API + uri, '地址', allure.attachment_type.TEXT)\nheaders = SX_PC_IM_headers\nallure.attach(json.dumps(headers, ensure_ascii=False, indent=4), '请求头', allure.attachment_type.TEXT)\ncommon = Common()\ndata = {'accountName': accountName, 'name': na... | <|body_start_0|>
uri = '/sunxing-customer-service/api/v1/im/init'
allure.attach(SX_PC_kf_API + uri, '地址', allure.attachment_type.TEXT)
headers = SX_PC_IM_headers
allure.attach(json.dumps(headers, ensure_ascii=False, indent=4), '请求头', allure.attachment_type.TEXT)
common = Common()... | Test_case | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_case:
def test_im_init(self, accountName, name, userType, phone, email, loginType, case):
"""初始化登陆接口 :return:"""
<|body_0|>
def test_im_init_disconnect(self, fromAccount, to, userType, case):
"""结束会话 :return:"""
<|body_1|>
def test_im_updateCustomer... | stack_v2_sparse_classes_36k_train_002791 | 11,282 | no_license | [
{
"docstring": "初始化登陆接口 :return:",
"name": "test_im_init",
"signature": "def test_im_init(self, accountName, name, userType, phone, email, loginType, case)"
},
{
"docstring": "结束会话 :return:",
"name": "test_im_init_disconnect",
"signature": "def test_im_init_disconnect(self, fromAccount, ... | 3 | null | Implement the Python class `Test_case` described below.
Class description:
Implement the Test_case class.
Method signatures and docstrings:
- def test_im_init(self, accountName, name, userType, phone, email, loginType, case): 初始化登陆接口 :return:
- def test_im_init_disconnect(self, fromAccount, to, userType, case): 结束会话 ... | Implement the Python class `Test_case` described below.
Class description:
Implement the Test_case class.
Method signatures and docstrings:
- def test_im_init(self, accountName, name, userType, phone, email, loginType, case): 初始化登陆接口 :return:
- def test_im_init_disconnect(self, fromAccount, to, userType, case): 结束会话 ... | a184161fdbf4b35dbca8e9b050ad049c05b003ff | <|skeleton|>
class Test_case:
def test_im_init(self, accountName, name, userType, phone, email, loginType, case):
"""初始化登陆接口 :return:"""
<|body_0|>
def test_im_init_disconnect(self, fromAccount, to, userType, case):
"""结束会话 :return:"""
<|body_1|>
def test_im_updateCustomer... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_case:
def test_im_init(self, accountName, name, userType, phone, email, loginType, case):
"""初始化登陆接口 :return:"""
uri = '/sunxing-customer-service/api/v1/im/init'
allure.attach(SX_PC_kf_API + uri, '地址', allure.attachment_type.TEXT)
headers = SX_PC_IM_headers
allure.... | the_stack_v2_python_sparse | TestSuite/pc_customer_service_center/test_im.py | liuchengxu11/IM | train | 0 | |
684710d8b3e5fda9ec855ba73efbd6443531772d | [
"super(DelayAuto, self).__init__()\nself.a = array_check(a, 1)\nself.tau = None",
"self.tau = int_check(tau, 0)\nn = self.a.size\n_sum = 0\nfor i in range(n - self.tau):\n _sum += (self.a[i] - self.a.mean()) * (self.a[i + self.tau] - self.a.mean()) / self.a.var()\nself.statistics = _sum / (n - self.tau)\nretur... | <|body_start_0|>
super(DelayAuto, self).__init__()
self.a = array_check(a, 1)
self.tau = None
<|end_body_0|>
<|body_start_1|>
self.tau = int_check(tau, 0)
n = self.a.size
_sum = 0
for i in range(n - self.tau):
_sum += (self.a[i] - self.a.mean()) * (se... | Auto correlation coefficient and t-test | DelayAuto | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DelayAuto:
"""Auto correlation coefficient and t-test"""
def __init__(self, a: array_like):
""":param a: array_like"""
<|body_0|>
def __call__(self, tau: int):
"""Calculate auto correlation. :param tau: int delay length :return: class self"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_002792 | 8,613 | no_license | [
{
"docstring": ":param a: array_like",
"name": "__init__",
"signature": "def __init__(self, a: array_like)"
},
{
"docstring": "Calculate auto correlation. :param tau: int delay length :return: class self",
"name": "__call__",
"signature": "def __call__(self, tau: int)"
},
{
"docs... | 3 | null | Implement the Python class `DelayAuto` described below.
Class description:
Auto correlation coefficient and t-test
Method signatures and docstrings:
- def __init__(self, a: array_like): :param a: array_like
- def __call__(self, tau: int): Calculate auto correlation. :param tau: int delay length :return: class self
- ... | Implement the Python class `DelayAuto` described below.
Class description:
Auto correlation coefficient and t-test
Method signatures and docstrings:
- def __init__(self, a: array_like): :param a: array_like
- def __call__(self, tau: int): Calculate auto correlation. :param tau: int delay length :return: class self
- ... | 1c8d5fbf3676dc81e9f143e93ee2564359519b11 | <|skeleton|>
class DelayAuto:
"""Auto correlation coefficient and t-test"""
def __init__(self, a: array_like):
""":param a: array_like"""
<|body_0|>
def __call__(self, tau: int):
"""Calculate auto correlation. :param tau: int delay length :return: class self"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DelayAuto:
"""Auto correlation coefficient and t-test"""
def __init__(self, a: array_like):
""":param a: array_like"""
super(DelayAuto, self).__init__()
self.a = array_check(a, 1)
self.tau = None
def __call__(self, tau: int):
"""Calculate auto correlation. :pa... | the_stack_v2_python_sparse | statistics/correlation.py | qliu0/PythonInAirSeaScience | train | 0 |
b0b80f2a2d689048e5cdcdc3dd8b68a429a42e36 | [
"self.db = mydb\nself.username = username\nself.password = password\nself.username = username\nself.email = email\nself.name = name",
"self.cur2 = self.db.cursor()\nself.cur2.execute('SELECT Username FROM Users WHERE Username=%s', (self.username,))\nself.result = self.cur2.fetchone()\nif self.result:\n return ... | <|body_start_0|>
self.db = mydb
self.username = username
self.password = password
self.username = username
self.email = email
self.name = name
<|end_body_0|>
<|body_start_1|>
self.cur2 = self.db.cursor()
self.cur2.execute('SELECT Username FROM Users WHERE... | Reg | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Reg:
def __init__(self, username, name, email, password):
"""Args: username (STRING): Username of User of Protekt name (STRING): Name of User of Protekt email (STRING): Email of User of Protekt password (STRING): Password of User of Protekt"""
<|body_0|>
def check(self):
... | stack_v2_sparse_classes_36k_train_002793 | 1,304 | no_license | [
{
"docstring": "Args: username (STRING): Username of User of Protekt name (STRING): Name of User of Protekt email (STRING): Email of User of Protekt password (STRING): Password of User of Protekt",
"name": "__init__",
"signature": "def __init__(self, username, name, email, password)"
},
{
"docst... | 3 | stack_v2_sparse_classes_30k_train_018439 | Implement the Python class `Reg` described below.
Class description:
Implement the Reg class.
Method signatures and docstrings:
- def __init__(self, username, name, email, password): Args: username (STRING): Username of User of Protekt name (STRING): Name of User of Protekt email (STRING): Email of User of Protekt pa... | Implement the Python class `Reg` described below.
Class description:
Implement the Reg class.
Method signatures and docstrings:
- def __init__(self, username, name, email, password): Args: username (STRING): Username of User of Protekt name (STRING): Name of User of Protekt email (STRING): Email of User of Protekt pa... | 79f533454dcb07c03aec1511b936d7a92ba1fa26 | <|skeleton|>
class Reg:
def __init__(self, username, name, email, password):
"""Args: username (STRING): Username of User of Protekt name (STRING): Name of User of Protekt email (STRING): Email of User of Protekt password (STRING): Password of User of Protekt"""
<|body_0|>
def check(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Reg:
def __init__(self, username, name, email, password):
"""Args: username (STRING): Username of User of Protekt name (STRING): Name of User of Protekt email (STRING): Email of User of Protekt password (STRING): Password of User of Protekt"""
self.db = mydb
self.username = username
... | the_stack_v2_python_sparse | DBregister.py | pushkarhax/PyProject | train | 0 | |
3c26419e5d29474b3dff3181b455a9518d5c97ad | [
"storage = get_storage()\nstorage.add_role_to_user(user_id, role_id)\nreturn ('', 204)",
"storage = get_storage()\nstorage.remove_role_from_user(user_id, role_id)\nreturn ('', 204)"
] | <|body_start_0|>
storage = get_storage()
storage.add_role_to_user(user_id, role_id)
return ('', 204)
<|end_body_0|>
<|body_start_1|>
storage = get_storage()
storage.remove_role_from_user(user_id, role_id)
return ('', 204)
<|end_body_1|>
| UserRolesManagementView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserRolesManagementView:
def post(self, user_id, role_id):
"""--- summary: Add a Role to a User. parameters: - user_id - role_id tags: - Users - Roles responses: 204: description: Role Added Successfully. 401: $ref: '#/components/responses/401-Unauthorized' 404: $ref: '#/components/respo... | stack_v2_sparse_classes_36k_train_002794 | 12,608 | permissive | [
{
"docstring": "--- summary: Add a Role to a User. parameters: - user_id - role_id tags: - Users - Roles responses: 204: description: Role Added Successfully. 401: $ref: '#/components/responses/401-Unauthorized' 404: $ref: '#/components/responses/404-NotFound'",
"name": "post",
"signature": "def post(se... | 2 | stack_v2_sparse_classes_30k_train_021213 | Implement the Python class `UserRolesManagementView` described below.
Class description:
Implement the UserRolesManagementView class.
Method signatures and docstrings:
- def post(self, user_id, role_id): --- summary: Add a Role to a User. parameters: - user_id - role_id tags: - Users - Roles responses: 204: descripti... | Implement the Python class `UserRolesManagementView` described below.
Class description:
Implement the UserRolesManagementView class.
Method signatures and docstrings:
- def post(self, user_id, role_id): --- summary: Add a Role to a User. parameters: - user_id - role_id tags: - Users - Roles responses: 204: descripti... | 280800c73eb7cfd49029462b352887e78f1ff91b | <|skeleton|>
class UserRolesManagementView:
def post(self, user_id, role_id):
"""--- summary: Add a Role to a User. parameters: - user_id - role_id tags: - Users - Roles responses: 204: description: Role Added Successfully. 401: $ref: '#/components/responses/401-Unauthorized' 404: $ref: '#/components/respo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserRolesManagementView:
def post(self, user_id, role_id):
"""--- summary: Add a Role to a User. parameters: - user_id - role_id tags: - Users - Roles responses: 204: description: Role Added Successfully. 401: $ref: '#/components/responses/401-Unauthorized' 404: $ref: '#/components/responses/404-NotFo... | the_stack_v2_python_sparse | sfa_api/users.py | SolarArbiter/solarforecastarbiter-api | train | 9 | |
5399670195a90da9244284fba0df02658a1034bc | [
"orchestrate(obj=self, config=stencil_factory.config.dace_config)\nself._no_compute = False\nif (damp_c.view[:] <= 0.0001).all():\n self._no_compute = True\nelif (damp_c.view[:-1] <= 0.0001).any():\n raise NotImplementedError('damp_c currently must be always greater than 10^-4 for delnflux')\ngrid_indexing = ... | <|body_start_0|>
orchestrate(obj=self, config=stencil_factory.config.dace_config)
self._no_compute = False
if (damp_c.view[:] <= 0.0001).all():
self._no_compute = True
elif (damp_c.view[:-1] <= 0.0001).any():
raise NotImplementedError('damp_c currently must be alw... | Fortran name is deln_flux The test class is DelnFlux This class computes the fluxes for damping and also applies them. | DelnFlux | [
"Apache-2.0",
"GPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DelnFlux:
"""Fortran name is deln_flux The test class is DelnFlux This class computes the fluxes for damping and also applies them."""
def __init__(self, stencil_factory: StencilFactory, quantity_factory: pace.util.QuantityFactory, damping_coefficients: DampingCoefficients, rarea: pace.util.... | stack_v2_sparse_classes_36k_train_002795 | 45,540 | permissive | [
{
"docstring": "nord sets the order of damping to apply: nord = 0: del-2 nord = 1: del-4 nord = 2: del-6 nord and damp_c define the damping coefficient used in DelnFluxNoSG",
"name": "__init__",
"signature": "def __init__(self, stencil_factory: StencilFactory, quantity_factory: pace.util.QuantityFactory... | 2 | null | Implement the Python class `DelnFlux` described below.
Class description:
Fortran name is deln_flux The test class is DelnFlux This class computes the fluxes for damping and also applies them.
Method signatures and docstrings:
- def __init__(self, stencil_factory: StencilFactory, quantity_factory: pace.util.QuantityF... | Implement the Python class `DelnFlux` described below.
Class description:
Fortran name is deln_flux The test class is DelnFlux This class computes the fluxes for damping and also applies them.
Method signatures and docstrings:
- def __init__(self, stencil_factory: StencilFactory, quantity_factory: pace.util.QuantityF... | c543e8ec478d46d88b48cdd3beaaa1717a95b935 | <|skeleton|>
class DelnFlux:
"""Fortran name is deln_flux The test class is DelnFlux This class computes the fluxes for damping and also applies them."""
def __init__(self, stencil_factory: StencilFactory, quantity_factory: pace.util.QuantityFactory, damping_coefficients: DampingCoefficients, rarea: pace.util.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DelnFlux:
"""Fortran name is deln_flux The test class is DelnFlux This class computes the fluxes for damping and also applies them."""
def __init__(self, stencil_factory: StencilFactory, quantity_factory: pace.util.QuantityFactory, damping_coefficients: DampingCoefficients, rarea: pace.util.Quantity, nor... | the_stack_v2_python_sparse | fv3core/pace/fv3core/stencils/delnflux.py | ai2cm/pace | train | 27 |
60fe26ac79915b57231af5608d6ae7a7ad047c37 | [
"if not hasattr(cls, _mangle(cls, 'instance')):\n setattr(cls, _mangle(cls, 'instance'), super().__new__(cls))\n setattr(cls, _mangle(cls, 'initialized'), False)\nreturn getattr(cls, _mangle(cls, 'instance'))",
"if cls.__init__ != object.__init__:\n old_init = cls.__init__\n\n def new_init(self, *args... | <|body_start_0|>
if not hasattr(cls, _mangle(cls, 'instance')):
setattr(cls, _mangle(cls, 'instance'), super().__new__(cls))
setattr(cls, _mangle(cls, 'initialized'), False)
return getattr(cls, _mangle(cls, 'instance'))
<|end_body_0|>
<|body_start_1|>
if cls.__init__ != ... | Class that is only constructed and initialized once, then future constructions return the already constructed class. When used in a class hierarchy, all children of a singleton can call their parent's constructors exactly once | Singleton | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Singleton:
"""Class that is only constructed and initialized once, then future constructions return the already constructed class. When used in a class hierarchy, all children of a singleton can call their parent's constructors exactly once"""
def __new__(cls, *args, **kwargs):
"""Co... | stack_v2_sparse_classes_36k_train_002796 | 9,712 | permissive | [
{
"docstring": "Construct a new Singleton. Checks for an instance, if one doesn't exist, creates one :param args: Ignored :param kwargs: Ignored :return: New or existing instance",
"name": "__new__",
"signature": "def __new__(cls, *args, **kwargs)"
},
{
"docstring": "Prepare a subclass to only h... | 2 | stack_v2_sparse_classes_30k_train_003675 | Implement the Python class `Singleton` described below.
Class description:
Class that is only constructed and initialized once, then future constructions return the already constructed class. When used in a class hierarchy, all children of a singleton can call their parent's constructors exactly once
Method signature... | Implement the Python class `Singleton` described below.
Class description:
Class that is only constructed and initialized once, then future constructions return the already constructed class. When used in a class hierarchy, all children of a singleton can call their parent's constructors exactly once
Method signature... | 4bf155feec7cb983e8d283d93552902ec85178a2 | <|skeleton|>
class Singleton:
"""Class that is only constructed and initialized once, then future constructions return the already constructed class. When used in a class hierarchy, all children of a singleton can call their parent's constructors exactly once"""
def __new__(cls, *args, **kwargs):
"""Co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Singleton:
"""Class that is only constructed and initialized once, then future constructions return the already constructed class. When used in a class hierarchy, all children of a singleton can call their parent's constructors exactly once"""
def __new__(cls, *args, **kwargs):
"""Construct a new... | the_stack_v2_python_sparse | spidertools/common/clstools.py | CraftSpider/SpiderTools | train | 6 |
595e0d3083730c2e865dc4b94896b48a1696e87c | [
"cls.api_url = cls.enum.get('test_api')\ncls.data_tmp = cls.enum.get('data')\ncls.schema_path = cls.enum.get('schema_path')",
"resp = self.get(self.api_url, params=self.data_tmp).json()\nself.assertEqual(resp.get('reason'), '请求成功')\nself.assertEqual(resp.get('error_code'), 0)\nself.assertEqual(self.get_value(resp... | <|body_start_0|>
cls.api_url = cls.enum.get('test_api')
cls.data_tmp = cls.enum.get('data')
cls.schema_path = cls.enum.get('schema_path')
<|end_body_0|>
<|body_start_1|>
resp = self.get(self.api_url, params=self.data_tmp).json()
self.assertEqual(resp.get('reason'), '请求成功')
... | pass | WeChatApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeChatApi:
"""pass"""
def setUpClass(cls):
"""pass"""
<|body_0|>
def test_wechat_api_is_ok_method_get(self):
"""pass"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cls.api_url = cls.enum.get('test_api')
cls.data_tmp = cls.enum.get('data... | stack_v2_sparse_classes_36k_train_002797 | 906 | no_license | [
{
"docstring": "pass",
"name": "setUpClass",
"signature": "def setUpClass(cls)"
},
{
"docstring": "pass",
"name": "test_wechat_api_is_ok_method_get",
"signature": "def test_wechat_api_is_ok_method_get(self)"
}
] | 2 | null | Implement the Python class `WeChatApi` described below.
Class description:
pass
Method signatures and docstrings:
- def setUpClass(cls): pass
- def test_wechat_api_is_ok_method_get(self): pass | Implement the Python class `WeChatApi` described below.
Class description:
pass
Method signatures and docstrings:
- def setUpClass(cls): pass
- def test_wechat_api_is_ok_method_get(self): pass
<|skeleton|>
class WeChatApi:
"""pass"""
def setUpClass(cls):
"""pass"""
<|body_0|>
def test_w... | d04fa050cd65d73c9d1207f251d7fe95ec15fa24 | <|skeleton|>
class WeChatApi:
"""pass"""
def setUpClass(cls):
"""pass"""
<|body_0|>
def test_wechat_api_is_ok_method_get(self):
"""pass"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WeChatApi:
"""pass"""
def setUpClass(cls):
"""pass"""
cls.api_url = cls.enum.get('test_api')
cls.data_tmp = cls.enum.get('data')
cls.schema_path = cls.enum.get('schema_path')
def test_wechat_api_is_ok_method_get(self):
"""pass"""
resp = self.get(self.a... | the_stack_v2_python_sparse | ForthWeek/second_day/ApiTestProject/case/test_wechat_api.py | PeiyaoL/LearnPythonWithWalkers | train | 0 |
5051ac5be5a764f665200709ab56a62295318e55 | [
"if 'password' in values and confirm_password != values['password']:\n raise ValueError(\"doesn't match to password\")\nreturn confirm_password",
"if not MIN_FIELD_LENGTH < len(username) < MAX_FIELD_LENGTH:\n raise ValueError('must contain between 3 to 20 charactars')\nreturn username",
"if not MIN_FIELD_... | <|body_start_0|>
if 'password' in values and confirm_password != values['password']:
raise ValueError("doesn't match to password")
return confirm_password
<|end_body_0|>
<|body_start_1|>
if not MIN_FIELD_LENGTH < len(username) < MAX_FIELD_LENGTH:
raise ValueError('must c... | Validating fields types | UserCreate | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserCreate:
"""Validating fields types"""
def passwords_match(cls, confirm_password: str, values: UserBase) -> Union[ValueError, str]:
"""Validating passwords fields identical."""
<|body_0|>
def username_length(cls, username: str) -> Union[ValueError, str]:
"""Va... | stack_v2_sparse_classes_36k_train_002798 | 2,838 | permissive | [
{
"docstring": "Validating passwords fields identical.",
"name": "passwords_match",
"signature": "def passwords_match(cls, confirm_password: str, values: UserBase) -> Union[ValueError, str]"
},
{
"docstring": "Validating username length is legal",
"name": "username_length",
"signature": ... | 4 | null | Implement the Python class `UserCreate` described below.
Class description:
Validating fields types
Method signatures and docstrings:
- def passwords_match(cls, confirm_password: str, values: UserBase) -> Union[ValueError, str]: Validating passwords fields identical.
- def username_length(cls, username: str) -> Union... | Implement the Python class `UserCreate` described below.
Class description:
Validating fields types
Method signatures and docstrings:
- def passwords_match(cls, confirm_password: str, values: UserBase) -> Union[ValueError, str]: Validating passwords fields identical.
- def username_length(cls, username: str) -> Union... | 23a33703a0038d0eae8ce7299a93ad172c8f68e9 | <|skeleton|>
class UserCreate:
"""Validating fields types"""
def passwords_match(cls, confirm_password: str, values: UserBase) -> Union[ValueError, str]:
"""Validating passwords fields identical."""
<|body_0|>
def username_length(cls, username: str) -> Union[ValueError, str]:
"""Va... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserCreate:
"""Validating fields types"""
def passwords_match(cls, confirm_password: str, values: UserBase) -> Union[ValueError, str]:
"""Validating passwords fields identical."""
if 'password' in values and confirm_password != values['password']:
raise ValueError("doesn't mat... | the_stack_v2_python_sparse | app/database/schemas.py | ofir96/calendar | train | 1 |
b6f040fe060a85c20f36c908383f83f2092bd707 | [
"user = User.objects.get(username='alsal')\ngoogle_id = GoogleSignIn.objects.get(user=user).google_id\nwith mock.patch.object(views, '_get_user_id') as mock_id:\n mock_id.return_value = google_id\n resp = self.client.post('/google-auth/', data=json.dumps({'id_token': 'mysecretidtoken', 'google_client_id': goo... | <|body_start_0|>
user = User.objects.get(username='alsal')
google_id = GoogleSignIn.objects.get(user=user).google_id
with mock.patch.object(views, '_get_user_id') as mock_id:
mock_id.return_value = google_id
resp = self.client.post('/google-auth/', data=json.dumps({'id_to... | GoogleSignInTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoogleSignInTest:
def test_existing_signin(self):
"""Test signing in an existing user."""
<|body_0|>
def test_new_user_signin(self, mock_uuid):
"""Test registering a user using Google credentials."""
<|body_1|>
def test_link_existing_user(self):
... | stack_v2_sparse_classes_36k_train_002799 | 3,920 | permissive | [
{
"docstring": "Test signing in an existing user.",
"name": "test_existing_signin",
"signature": "def test_existing_signin(self)"
},
{
"docstring": "Test registering a user using Google credentials.",
"name": "test_new_user_signin",
"signature": "def test_new_user_signin(self, mock_uuid)... | 4 | stack_v2_sparse_classes_30k_train_014094 | Implement the Python class `GoogleSignInTest` described below.
Class description:
Implement the GoogleSignInTest class.
Method signatures and docstrings:
- def test_existing_signin(self): Test signing in an existing user.
- def test_new_user_signin(self, mock_uuid): Test registering a user using Google credentials.
-... | Implement the Python class `GoogleSignInTest` described below.
Class description:
Implement the GoogleSignInTest class.
Method signatures and docstrings:
- def test_existing_signin(self): Test signing in an existing user.
- def test_new_user_signin(self, mock_uuid): Test registering a user using Google credentials.
-... | 46c4a1fe409a45e8595210a5cf242425d40d4b41 | <|skeleton|>
class GoogleSignInTest:
def test_existing_signin(self):
"""Test signing in an existing user."""
<|body_0|>
def test_new_user_signin(self, mock_uuid):
"""Test registering a user using Google credentials."""
<|body_1|>
def test_link_existing_user(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GoogleSignInTest:
def test_existing_signin(self):
"""Test signing in an existing user."""
user = User.objects.get(username='alsal')
google_id = GoogleSignIn.objects.get(user=user).google_id
with mock.patch.object(views, '_get_user_id') as mock_id:
mock_id.return_val... | the_stack_v2_python_sparse | apps/accounts/tests.py | tractiming/trac-gae | train | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.