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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5fea1b69b688322c6e64fbc4afe002af1b92a4fe | [
"flags.GetSpannerMigrationSourceFlag().AddToParser(parser)\nflags.GetSpannerMigrationPrefixFlag().AddToParser(parser)\nflags.GetSpannerMigrationSkipForeignKeysFlag().AddToParser(parser)\nflags.GetSpannerMigrationSourceProfileFlag().AddToParser(parser)\nflags.GetSpannerMigrationTargetFlag().AddToParser(parser)\nflag... | <|body_start_0|>
flags.GetSpannerMigrationSourceFlag().AddToParser(parser)
flags.GetSpannerMigrationPrefixFlag().AddToParser(parser)
flags.GetSpannerMigrationSkipForeignKeysFlag().AddToParser(parser)
flags.GetSpannerMigrationSourceProfileFlag().AddToParser(parser)
flags.GetSpanne... | Migrate data from a source database to Cloud Spanner given a schema. | SchemaAndData | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchemaAndData:
"""Migrate data from a source database to Cloud Spanner given a schema."""
def Args(parser):
"""Register the flags for this command."""
<|body_0|>
def Run(self, args):
"""Run the schema-and-data command."""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_000300 | 2,811 | permissive | [
{
"docstring": "Register the flags for this command.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "Run the schema-and-data command.",
"name": "Run",
"signature": "def Run(self, args)"
}
] | 2 | null | Implement the Python class `SchemaAndData` described below.
Class description:
Migrate data from a source database to Cloud Spanner given a schema.
Method signatures and docstrings:
- def Args(parser): Register the flags for this command.
- def Run(self, args): Run the schema-and-data command. | Implement the Python class `SchemaAndData` described below.
Class description:
Migrate data from a source database to Cloud Spanner given a schema.
Method signatures and docstrings:
- def Args(parser): Register the flags for this command.
- def Run(self, args): Run the schema-and-data command.
<|skeleton|>
class Sch... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class SchemaAndData:
"""Migrate data from a source database to Cloud Spanner given a schema."""
def Args(parser):
"""Register the flags for this command."""
<|body_0|>
def Run(self, args):
"""Run the schema-and-data command."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SchemaAndData:
"""Migrate data from a source database to Cloud Spanner given a schema."""
def Args(parser):
"""Register the flags for this command."""
flags.GetSpannerMigrationSourceFlag().AddToParser(parser)
flags.GetSpannerMigrationPrefixFlag().AddToParser(parser)
flags.... | the_stack_v2_python_sparse | lib/surface/spanner/migrate/schema_and_data.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
166d255aab158dab1c97c2b8db277b8e6a76c206 | [
"n = len(nums)\nresult = []\n\ndef backtrack(first=0):\n if first == n:\n result.append(nums[:])\n for i in range(first, n):\n nums[first], nums[i] = (nums[i], nums[first])\n backtrack(first + 1)\n nums[first], nums[i] = (nums[i], nums[first])\nbacktrack()\nreturn result",
"def b... | <|body_start_0|>
n = len(nums)
result = []
def backtrack(first=0):
if first == n:
result.append(nums[:])
for i in range(first, n):
nums[first], nums[i] = (nums[i], nums[first])
backtrack(first + 1)
nums[firs... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
"""46. 全排列 给定一个 没有重复 数字的序列,返回其所有可能的全排列。"""
<|body_0|>
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
"""47. 全排列 II 给定一个可包含重复数字的序列,返回所有不重复的全排列。"""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_36k_train_000301 | 1,593 | no_license | [
{
"docstring": "46. 全排列 给定一个 没有重复 数字的序列,返回其所有可能的全排列。",
"name": "permute",
"signature": "def permute(self, nums: List[int]) -> List[List[int]]"
},
{
"docstring": "47. 全排列 II 给定一个可包含重复数字的序列,返回所有不重复的全排列。",
"name": "permuteUnique",
"signature": "def permuteUnique(self, nums: List[int]) -> Li... | 2 | stack_v2_sparse_classes_30k_train_018545 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def permute(self, nums: List[int]) -> List[List[int]]: 46. 全排列 给定一个 没有重复 数字的序列,返回其所有可能的全排列。
- def permuteUnique(self, nums: List[int]) -> List[List[int]]: 47. 全排列 II 给定一个可包含重复数字的... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def permute(self, nums: List[int]) -> List[List[int]]: 46. 全排列 给定一个 没有重复 数字的序列,返回其所有可能的全排列。
- def permuteUnique(self, nums: List[int]) -> List[List[int]]: 47. 全排列 II 给定一个可包含重复数字的... | 6580c7fd9a62494f82cedf69edda793865b5bd2d | <|skeleton|>
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
"""46. 全排列 给定一个 没有重复 数字的序列,返回其所有可能的全排列。"""
<|body_0|>
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
"""47. 全排列 II 给定一个可包含重复数字的序列,返回所有不重复的全排列。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
"""46. 全排列 给定一个 没有重复 数字的序列,返回其所有可能的全排列。"""
n = len(nums)
result = []
def backtrack(first=0):
if first == n:
result.append(nums[:])
for i in range(first, n):
... | the_stack_v2_python_sparse | Week_03/permutations.py | ZGingko/algorithm008-class02 | train | 0 | |
979947af88a7b47b20e96db8c7fb17839cca7fb9 | [
"self.data_dir = data_dir\nself.gray = gray\nself.use_scale = use_scale\nself.flatten = flatten\nself.class_dict = dict()",
"if read_cache:\n if os.path.exists(os.path.join(self.data_dir, 'data_cache.pkl')):\n with open(os.path.join(self.data_dir, 'data_cache.pkl'), 'rb') as reader:\n return ... | <|body_start_0|>
self.data_dir = data_dir
self.gray = gray
self.use_scale = use_scale
self.flatten = flatten
self.class_dict = dict()
<|end_body_0|>
<|body_start_1|>
if read_cache:
if os.path.exists(os.path.join(self.data_dir, 'data_cache.pkl')):
... | 数据集载入控制类,传入参数为目录,并且目录满足以下特征: 1. 目录下所有文件都是两级结构,比如 class1/file1.png 2. 所有文件都为图片类型,可被计算机读取 3. 同一类图片需要放在同一个目录下 在生成数据的同时会解析标签字典,其过程为: 1. 将1级目录排序 2. 按照顺序生成标签,从0开始 3. 记录标签到目录名的字典返回class_dict | ImageHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageHandler:
"""数据集载入控制类,传入参数为目录,并且目录满足以下特征: 1. 目录下所有文件都是两级结构,比如 class1/file1.png 2. 所有文件都为图片类型,可被计算机读取 3. 同一类图片需要放在同一个目录下 在生成数据的同时会解析标签字典,其过程为: 1. 将1级目录排序 2. 按照顺序生成标签,从0开始 3. 记录标签到目录名的字典返回class_dict"""
def __init__(self, data_dir, gray=False, use_scale=False, flatten=False):
""":pa... | stack_v2_sparse_classes_36k_train_000302 | 3,851 | no_license | [
{
"docstring": ":param data_dir: 根目录 :param gray: 是否以灰度化格式读入图片 :param use_scale: 是否/255. :param flatten: 数据结果是否需要拉伸为1维",
"name": "__init__",
"signature": "def __init__(self, data_dir, gray=False, use_scale=False, flatten=False)"
},
{
"docstring": "读取数据 :param ratio: 数据拆分比例 :param read_cache: 是否使... | 4 | stack_v2_sparse_classes_30k_train_014311 | Implement the Python class `ImageHandler` described below.
Class description:
数据集载入控制类,传入参数为目录,并且目录满足以下特征: 1. 目录下所有文件都是两级结构,比如 class1/file1.png 2. 所有文件都为图片类型,可被计算机读取 3. 同一类图片需要放在同一个目录下 在生成数据的同时会解析标签字典,其过程为: 1. 将1级目录排序 2. 按照顺序生成标签,从0开始 3. 记录标签到目录名的字典返回class_dict
Method signatures and docstrings:
- def __init__(self, d... | Implement the Python class `ImageHandler` described below.
Class description:
数据集载入控制类,传入参数为目录,并且目录满足以下特征: 1. 目录下所有文件都是两级结构,比如 class1/file1.png 2. 所有文件都为图片类型,可被计算机读取 3. 同一类图片需要放在同一个目录下 在生成数据的同时会解析标签字典,其过程为: 1. 将1级目录排序 2. 按照顺序生成标签,从0开始 3. 记录标签到目录名的字典返回class_dict
Method signatures and docstrings:
- def __init__(self, d... | 9f234a996b99c8e94d8259cd875e69af8ffa9a5c | <|skeleton|>
class ImageHandler:
"""数据集载入控制类,传入参数为目录,并且目录满足以下特征: 1. 目录下所有文件都是两级结构,比如 class1/file1.png 2. 所有文件都为图片类型,可被计算机读取 3. 同一类图片需要放在同一个目录下 在生成数据的同时会解析标签字典,其过程为: 1. 将1级目录排序 2. 按照顺序生成标签,从0开始 3. 记录标签到目录名的字典返回class_dict"""
def __init__(self, data_dir, gray=False, use_scale=False, flatten=False):
""":pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageHandler:
"""数据集载入控制类,传入参数为目录,并且目录满足以下特征: 1. 目录下所有文件都是两级结构,比如 class1/file1.png 2. 所有文件都为图片类型,可被计算机读取 3. 同一类图片需要放在同一个目录下 在生成数据的同时会解析标签字典,其过程为: 1. 将1级目录排序 2. 按照顺序生成标签,从0开始 3. 记录标签到目录名的字典返回class_dict"""
def __init__(self, data_dir, gray=False, use_scale=False, flatten=False):
""":param data_dir:... | the_stack_v2_python_sparse | enet/data/image_controller.py | bighead-123/neural_network | train | 0 |
c03146f9a05b1b8db4f179a7c9349ea55c24e0fe | [
"if len(arguments) == 0:\n raise Exception('error, need arguments')\nif arguments[0][0] not in valid_seq:\n raise Exception(f'error, the first argument need to start with one of the following: {valid_seq}')\nseq = dna_data.get_dna_data(arguments[0])\nif seq is None:\n raise Exception('error, the seq not fo... | <|body_start_0|>
if len(arguments) == 0:
raise Exception('error, need arguments')
if arguments[0][0] not in valid_seq:
raise Exception(f'error, the first argument need to start with one of the following: {valid_seq}')
seq = dna_data.get_dna_data(arguments[0])
if s... | functions that uses in Analysis Command | IAnalysisCommand | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IAnalysisCommand:
"""functions that uses in Analysis Command"""
def get_base_seq(self, arguments, dna_data, valid_seq):
"""get the sequence that need to be analysis :param arguments: command's args :param dna_data: DNA DB :param valid_seq: the chars that need to appear before the nam... | stack_v2_sparse_classes_36k_train_000303 | 1,998 | no_license | [
{
"docstring": "get the sequence that need to be analysis :param arguments: command's args :param dna_data: DNA DB :param valid_seq: the chars that need to appear before the name of the sequence :return: the sequence if found",
"name": "get_base_seq",
"signature": "def get_base_seq(self, arguments, dna_... | 3 | stack_v2_sparse_classes_30k_train_000639 | Implement the Python class `IAnalysisCommand` described below.
Class description:
functions that uses in Analysis Command
Method signatures and docstrings:
- def get_base_seq(self, arguments, dna_data, valid_seq): get the sequence that need to be analysis :param arguments: command's args :param dna_data: DNA DB :para... | Implement the Python class `IAnalysisCommand` described below.
Class description:
functions that uses in Analysis Command
Method signatures and docstrings:
- def get_base_seq(self, arguments, dna_data, valid_seq): get the sequence that need to be analysis :param arguments: command's args :param dna_data: DNA DB :para... | 7cd9e7fb352d3771a4147f073130c10948277aaf | <|skeleton|>
class IAnalysisCommand:
"""functions that uses in Analysis Command"""
def get_base_seq(self, arguments, dna_data, valid_seq):
"""get the sequence that need to be analysis :param arguments: command's args :param dna_data: DNA DB :param valid_seq: the chars that need to appear before the nam... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IAnalysisCommand:
"""functions that uses in Analysis Command"""
def get_base_seq(self, arguments, dna_data, valid_seq):
"""get the sequence that need to be analysis :param arguments: command's args :param dna_data: DNA DB :param valid_seq: the chars that need to appear before the name of the sequ... | the_stack_v2_python_sparse | Commands/seqAnalysisCommand/IAnalysisCommand.py | OryanTamsut/DNA-Analyzer | train | 2 |
c94aef0fbd65bedd39dff72490bb640c55ff51c9 | [
"ret = []\n\ndef swap(i, j):\n if i == j:\n return\n print('swap({},{})'.format(i, j))\n temp = nums[i]\n nums[i] = nums[j]\n nums[j] = temp\n\ndef isduplicate(start, end):\n return nums[end] in nums[start:end]\n\ndef permute_rec(start):\n if start == len(nums) - 1:\n ret.append(n... | <|body_start_0|>
ret = []
def swap(i, j):
if i == j:
return
print('swap({},{})'.format(i, j))
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
def isduplicate(start, end):
return nums[end] in nums[start:end]... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def permuteUnique(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def permuteUnique_vt(self, nums):
"""solution with visit_table"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ret = []
def swap(i, j):
... | stack_v2_sparse_classes_36k_train_000304 | 2,669 | permissive | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "permuteUnique",
"signature": "def permuteUnique(self, nums)"
},
{
"docstring": "solution with visit_table",
"name": "permuteUnique_vt",
"signature": "def permuteUnique_vt(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014716 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def permuteUnique(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def permuteUnique_vt(self, nums): solution with visit_table | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def permuteUnique(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def permuteUnique_vt(self, nums): solution with visit_table
<|skeleton|>
class Solution:
def ... | bf03743a3676ca9a8c107f92cf3858b6887d0308 | <|skeleton|>
class Solution:
def permuteUnique(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def permuteUnique_vt(self, nums):
"""solution with visit_table"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def permuteUnique(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
ret = []
def swap(i, j):
if i == j:
return
print('swap({},{})'.format(i, j))
temp = nums[i]
nums[i] = nums[j]
nums[j... | the_stack_v2_python_sparse | python/47_permutations.py | liaison/LeetCode | train | 17 | |
b5bfd2d7071f2a010750ef63eec39e40dd5c553e | [
"try:\n doc = Document.objects.get(id=doc_id)\nexcept Document.DoesNotExist:\n raise Http404('Document does not exists')\npage_nums = request.GET.getlist('pages[]')\npage_nums = [int(number) for number in page_nums]\ndoc.delete_pages(page_numbers=page_nums)\nreturn Response(status=status.HTTP_204_NO_CONTENT)"... | <|body_start_0|>
try:
doc = Document.objects.get(id=doc_id)
except Document.DoesNotExist:
raise Http404('Document does not exists')
page_nums = request.GET.getlist('pages[]')
page_nums = [int(number) for number in page_nums]
doc.delete_pages(page_numbers=p... | PagesView | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PagesView:
def delete(self, request, doc_id):
"""Deletes Pages from doc_id document"""
<|body_0|>
def post(self, request, doc_id):
"""Reorders pages from doc_id document"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
doc = Document... | stack_v2_sparse_classes_36k_train_000305 | 3,021 | permissive | [
{
"docstring": "Deletes Pages from doc_id document",
"name": "delete",
"signature": "def delete(self, request, doc_id)"
},
{
"docstring": "Reorders pages from doc_id document",
"name": "post",
"signature": "def post(self, request, doc_id)"
}
] | 2 | null | Implement the Python class `PagesView` described below.
Class description:
Implement the PagesView class.
Method signatures and docstrings:
- def delete(self, request, doc_id): Deletes Pages from doc_id document
- def post(self, request, doc_id): Reorders pages from doc_id document | Implement the Python class `PagesView` described below.
Class description:
Implement the PagesView class.
Method signatures and docstrings:
- def delete(self, request, doc_id): Deletes Pages from doc_id document
- def post(self, request, doc_id): Reorders pages from doc_id document
<|skeleton|>
class PagesView:
... | d177f1af331214e0f62407624e7029ce4953bd9b | <|skeleton|>
class PagesView:
def delete(self, request, doc_id):
"""Deletes Pages from doc_id document"""
<|body_0|>
def post(self, request, doc_id):
"""Reorders pages from doc_id document"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PagesView:
def delete(self, request, doc_id):
"""Deletes Pages from doc_id document"""
try:
doc = Document.objects.get(id=doc_id)
except Document.DoesNotExist:
raise Http404('Document does not exists')
page_nums = request.GET.getlist('pages[]')
p... | the_stack_v2_python_sparse | papermerge/core/views/api.py | ebdavison/papermerge | train | 0 | |
a81bad7345a4aa2679aa41d099d2ec7c53a0c3f5 | [
"if root is None:\n return []\nq = []\nres = []\nq.append(root)\nwhile len(q) > 0:\n for _ in range(len(q)):\n node = q.pop(0)\n for next_node in [node.left, node.right]:\n if next_node is not None:\n q.append(next_node)\n res.append(node.val)\nreturn res",
"if roo... | <|body_start_0|>
if root is None:
return []
q = []
res = []
q.append(root)
while len(q) > 0:
for _ in range(len(q)):
node = q.pop(0)
for next_node in [node.left, node.right]:
if next_node is not None:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rightSideView2(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def rightSideView(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root is None:
r... | stack_v2_sparse_classes_36k_train_000306 | 1,365 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "rightSideView2",
"signature": "def rightSideView2(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "rightSideView",
"signature": "def rightSideView(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020624 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rightSideView2(self, root): :type root: TreeNode :rtype: List[int]
- def rightSideView(self, root): :type root: TreeNode :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rightSideView2(self, root): :type root: TreeNode :rtype: List[int]
- def rightSideView(self, root): :type root: TreeNode :rtype: List[int]
<|skeleton|>
class Solution:
... | 70cb1ee0cdc1ddec93861aef56610f7def1472e1 | <|skeleton|>
class Solution:
def rightSideView2(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def rightSideView(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rightSideView2(self, root):
""":type root: TreeNode :rtype: List[int]"""
if root is None:
return []
q = []
res = []
q.append(root)
while len(q) > 0:
for _ in range(len(q)):
node = q.pop(0)
for... | the_stack_v2_python_sparse | trees/bfs/right_side_view.py | medesiv/ds_algo | train | 0 | |
13faae550a4f408fcabffbe45a858c3803a2f863 | [
"templates = mall_models.ProductPropertyTemplate.objects.filter(owner=request.manager)\nfor template in templates:\n template.properties = []\nid2templates = dict([(template.id, template) for template in templates])\ntemplate_ids = [template.id for template in templates]\nproperties = mall_models.TemplatePropert... | <|body_start_0|>
templates = mall_models.ProductPropertyTemplate.objects.filter(owner=request.manager)
for template in templates:
template.properties = []
id2templates = dict([(template.id, template) for template in templates])
template_ids = [template.id for template in temp... | PropertyList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PropertyList:
def get(request):
"""商品属性模板列表页面."""
<|body_0|>
def api_get(request):
"""获得属性模板中的属性集合 Args: id: 属性模板id Return json: Example: [{ id: 1, name: "属性1", value: "属性1的描述" }, { ...... }]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
templates... | stack_v2_sparse_classes_36k_train_000307 | 5,912 | no_license | [
{
"docstring": "商品属性模板列表页面.",
"name": "get",
"signature": "def get(request)"
},
{
"docstring": "获得属性模板中的属性集合 Args: id: 属性模板id Return json: Example: [{ id: 1, name: \"属性1\", value: \"属性1的描述\" }, { ...... }]",
"name": "api_get",
"signature": "def api_get(request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001431 | Implement the Python class `PropertyList` described below.
Class description:
Implement the PropertyList class.
Method signatures and docstrings:
- def get(request): 商品属性模板列表页面.
- def api_get(request): 获得属性模板中的属性集合 Args: id: 属性模板id Return json: Example: [{ id: 1, name: "属性1", value: "属性1的描述" }, { ...... }] | Implement the Python class `PropertyList` described below.
Class description:
Implement the PropertyList class.
Method signatures and docstrings:
- def get(request): 商品属性模板列表页面.
- def api_get(request): 获得属性模板中的属性集合 Args: id: 属性模板id Return json: Example: [{ id: 1, name: "属性1", value: "属性1的描述" }, { ...... }]
<|skeleto... | 8b2f7befe92841bcc35e0e60cac5958ef3f3af54 | <|skeleton|>
class PropertyList:
def get(request):
"""商品属性模板列表页面."""
<|body_0|>
def api_get(request):
"""获得属性模板中的属性集合 Args: id: 属性模板id Return json: Example: [{ id: 1, name: "属性1", value: "属性1的描述" }, { ...... }]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PropertyList:
def get(request):
"""商品属性模板列表页面."""
templates = mall_models.ProductPropertyTemplate.objects.filter(owner=request.manager)
for template in templates:
template.properties = []
id2templates = dict([(template.id, template) for template in templates])
... | the_stack_v2_python_sparse | weapp/mall/product/properties.py | chengdg/weizoom | train | 1 | |
19f3d75afccca7ed2b5fce7e8c3562179220b31d | [
"sig = inspect.signature(cls)\nclskwds = {}\nfor name, param in list(sig.parameters.items()):\n if param.kind in (param.POSITIONAL_OR_KEYWORD, param.KEYWORD_ONLY):\n try:\n clskwds[name] = kwargs.pop(name)\n except KeyError:\n pass\nreturn (cls(*args, **clskwds), kwargs)",
"... | <|body_start_0|>
sig = inspect.signature(cls)
clskwds = {}
for name, param in list(sig.parameters.items()):
if param.kind in (param.POSITIONAL_OR_KEYWORD, param.KEYWORD_ONLY):
try:
clskwds[name] = kwargs.pop(name)
except KeyError:
... | A base class for composable components. This class helps propagating, sharing, and intercepting arguments (initialization parameters) in a unified manner so that classes can pass arguments to their sub-components reliably. For a basic usage, `BaseComponent` only requires its subclass to *not* have keyword arguments (``... | BaseComponent | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseComponent:
"""A base class for composable components. This class helps propagating, sharing, and intercepting arguments (initialization parameters) in a unified manner so that classes can pass arguments to their sub-components reliably. For a basic usage, `BaseComponent` only requires its sub... | stack_v2_sparse_classes_36k_train_000308 | 8,935 | permissive | [
{
"docstring": "Instantiate `cls` using a subset of `kwargs` and return the rest. Returns ------- self : cls The result of ``cls(*args, **clskwds)`` where `clskwds` is a subset of `kwargs`. It is determined by the call signature of `cls.__init__`. rest : dict A subset of `kwargs` not used by `cls.__init__`; i.e... | 3 | null | Implement the Python class `BaseComponent` described below.
Class description:
A base class for composable components. This class helps propagating, sharing, and intercepting arguments (initialization parameters) in a unified manner so that classes can pass arguments to their sub-components reliably. For a basic usage... | Implement the Python class `BaseComponent` described below.
Class description:
A base class for composable components. This class helps propagating, sharing, and intercepting arguments (initialization parameters) in a unified manner so that classes can pass arguments to their sub-components reliably. For a basic usage... | 06c549e8ae74bc6af62fddeed698565ea1f548c5 | <|skeleton|>
class BaseComponent:
"""A base class for composable components. This class helps propagating, sharing, and intercepting arguments (initialization parameters) in a unified manner so that classes can pass arguments to their sub-components reliably. For a basic usage, `BaseComponent` only requires its sub... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseComponent:
"""A base class for composable components. This class helps propagating, sharing, and intercepting arguments (initialization parameters) in a unified manner so that classes can pass arguments to their sub-components reliably. For a basic usage, `BaseComponent` only requires its subclass to *not... | the_stack_v2_python_sparse | tc_gan/core.py | ahmadianlab/tc-gan | train | 4 |
0a84b4b2b81fc0a0568cbaae984cdb85159c8a34 | [
"user = self.context['request'].user\nif not user.check_password(attrs['password']):\n raise serializers.ValidationError({'error': '旧密码输入错误!'})\nif user.check_password(attrs['password1']):\n raise serializers.ValidationError({'error': '新密码与旧密码相同!'})\nif attrs['password1'] != attrs['password2']:\n raise ser... | <|body_start_0|>
user = self.context['request'].user
if not user.check_password(attrs['password']):
raise serializers.ValidationError({'error': '旧密码输入错误!'})
if user.check_password(attrs['password1']):
raise serializers.ValidationError({'error': '新密码与旧密码相同!'})
if a... | 用户修改密码序列化器 | UserCheckPasswordSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserCheckPasswordSerializer:
"""用户修改密码序列化器"""
def validate(self, attrs):
"""校验数据"""
<|body_0|>
def update(self, instance, validated_data):
"""更新密码 :param instance: 根据pk对应的User模型对象 :param validated_data: 验证完成以后的数据 :return:"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_000309 | 19,382 | no_license | [
{
"docstring": "校验数据",
"name": "validate",
"signature": "def validate(self, attrs)"
},
{
"docstring": "更新密码 :param instance: 根据pk对应的User模型对象 :param validated_data: 验证完成以后的数据 :return:",
"name": "update",
"signature": "def update(self, instance, validated_data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015665 | Implement the Python class `UserCheckPasswordSerializer` described below.
Class description:
用户修改密码序列化器
Method signatures and docstrings:
- def validate(self, attrs): 校验数据
- def update(self, instance, validated_data): 更新密码 :param instance: 根据pk对应的User模型对象 :param validated_data: 验证完成以后的数据 :return: | Implement the Python class `UserCheckPasswordSerializer` described below.
Class description:
用户修改密码序列化器
Method signatures and docstrings:
- def validate(self, attrs): 校验数据
- def update(self, instance, validated_data): 更新密码 :param instance: 根据pk对应的User模型对象 :param validated_data: 验证完成以后的数据 :return:
<|skeleton|>
class ... | c4d9b124a50e96ce01dfd83073cbe4435cb07266 | <|skeleton|>
class UserCheckPasswordSerializer:
"""用户修改密码序列化器"""
def validate(self, attrs):
"""校验数据"""
<|body_0|>
def update(self, instance, validated_data):
"""更新密码 :param instance: 根据pk对应的User模型对象 :param validated_data: 验证完成以后的数据 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserCheckPasswordSerializer:
"""用户修改密码序列化器"""
def validate(self, attrs):
"""校验数据"""
user = self.context['request'].user
if not user.check_password(attrs['password']):
raise serializers.ValidationError({'error': '旧密码输入错误!'})
if user.check_password(attrs['passwor... | the_stack_v2_python_sparse | apps/users/serializer/serializers_front.py | wuhaihua1989/magic1 | train | 0 |
389000f9d32172b45788ff2bf0ce85670c2c60ea | [
"GstBase.BaseTransform.__init__(self)\nself.blk_q = blk_q\nlogger.debug('Initialize GstPlugin.')",
"timestamp = Gst.TIME_ARGS(buf.pts)\nlogger.debug('timestamp(buffer):%s queue(buffer):%s' % (timestamp, self.blk_q.qsize()))\nres, bmap = buf.map(Gst.MapFlags.READ)\nself.blk_q.put((timestamp, bmap.data))\nreturn Gs... | <|body_start_0|>
GstBase.BaseTransform.__init__(self)
self.blk_q = blk_q
logger.debug('Initialize GstPlugin.')
<|end_body_0|>
<|body_start_1|>
timestamp = Gst.TIME_ARGS(buf.pts)
logger.debug('timestamp(buffer):%s queue(buffer):%s' % (timestamp, self.blk_q.qsize()))
res, ... | GstPlugin that extracts blocks from Gst pipeline into a queue. | StreamExtractor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StreamExtractor:
"""GstPlugin that extracts blocks from Gst pipeline into a queue."""
def __init__(self, blk_q=None):
"""Initialize the Gst Plugin."""
<|body_0|>
def do_transform_ip(self, buf):
"""Call each time buffer is received from pipeline. As block data can... | stack_v2_sparse_classes_36k_train_000310 | 2,058 | no_license | [
{
"docstring": "Initialize the Gst Plugin.",
"name": "__init__",
"signature": "def __init__(self, blk_q=None)"
},
{
"docstring": "Call each time buffer is received from pipeline. As block data cannot be written back into stream, we must instead queue it and use it from a different thread.",
... | 2 | stack_v2_sparse_classes_30k_train_010778 | Implement the Python class `StreamExtractor` described below.
Class description:
GstPlugin that extracts blocks from Gst pipeline into a queue.
Method signatures and docstrings:
- def __init__(self, blk_q=None): Initialize the Gst Plugin.
- def do_transform_ip(self, buf): Call each time buffer is received from pipeli... | Implement the Python class `StreamExtractor` described below.
Class description:
GstPlugin that extracts blocks from Gst pipeline into a queue.
Method signatures and docstrings:
- def __init__(self, blk_q=None): Initialize the Gst Plugin.
- def do_transform_ip(self, buf): Call each time buffer is received from pipeli... | 72ae7258c0cd1cce789e8f891a593841e6ab8277 | <|skeleton|>
class StreamExtractor:
"""GstPlugin that extracts blocks from Gst pipeline into a queue."""
def __init__(self, blk_q=None):
"""Initialize the Gst Plugin."""
<|body_0|>
def do_transform_ip(self, buf):
"""Call each time buffer is received from pipeline. As block data can... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StreamExtractor:
"""GstPlugin that extracts blocks from Gst pipeline into a queue."""
def __init__(self, blk_q=None):
"""Initialize the Gst Plugin."""
GstBase.BaseTransform.__init__(self)
self.blk_q = blk_q
logger.debug('Initialize GstPlugin.')
def do_transform_ip(sel... | the_stack_v2_python_sparse | gst/python/streamextractor.py | cilsat/scribe | train | 0 |
34b298a541fd26cfecc15d23d25cc5bfd9fa9857 | [
"self.clf_name = clf_name\nif self.clf_name == 'One-Class SVM':\n self.clf = svm.OneClassSVM(nu=0.1, kernel='rbf', gamma=0.1)\nelif self.clf_name == 'Robust covariance':\n self.clf = EllipticEnvelope()\nelif self.clf_name == 'Isolation Forest':\n self.clf = IsolationForest()\nelif self.clf_name == 'Local O... | <|body_start_0|>
self.clf_name = clf_name
if self.clf_name == 'One-Class SVM':
self.clf = svm.OneClassSVM(nu=0.1, kernel='rbf', gamma=0.1)
elif self.clf_name == 'Robust covariance':
self.clf = EllipticEnvelope()
elif self.clf_name == 'Isolation Forest':
... | An simple LDA using sklearn. Inspired by the following: - http://scikit-learn.org/stable/auto_examples/svm/plot_oneclass.html | BuildSimpleOutliersDetectionMethod | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BuildSimpleOutliersDetectionMethod:
"""An simple LDA using sklearn. Inspired by the following: - http://scikit-learn.org/stable/auto_examples/svm/plot_oneclass.html"""
def __init__(self, clf_name):
"""Build Traditional Outliers classifier."""
<|body_0|>
def train(self, t... | stack_v2_sparse_classes_36k_train_000311 | 15,799 | permissive | [
{
"docstring": "Build Traditional Outliers classifier.",
"name": "__init__",
"signature": "def __init__(self, clf_name)"
},
{
"docstring": "Fit the SVM model. :param train_data: :param save_model: :param test_saved_model: :param model_dir_path: :param iteration_number: :return:",
"name": "tr... | 2 | stack_v2_sparse_classes_30k_train_005393 | Implement the Python class `BuildSimpleOutliersDetectionMethod` described below.
Class description:
An simple LDA using sklearn. Inspired by the following: - http://scikit-learn.org/stable/auto_examples/svm/plot_oneclass.html
Method signatures and docstrings:
- def __init__(self, clf_name): Build Traditional Outliers... | Implement the Python class `BuildSimpleOutliersDetectionMethod` described below.
Class description:
An simple LDA using sklearn. Inspired by the following: - http://scikit-learn.org/stable/auto_examples/svm/plot_oneclass.html
Method signatures and docstrings:
- def __init__(self, clf_name): Build Traditional Outliers... | a6b27c6847262e9703a0f3404c85c135415c1d4c | <|skeleton|>
class BuildSimpleOutliersDetectionMethod:
"""An simple LDA using sklearn. Inspired by the following: - http://scikit-learn.org/stable/auto_examples/svm/plot_oneclass.html"""
def __init__(self, clf_name):
"""Build Traditional Outliers classifier."""
<|body_0|>
def train(self, t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BuildSimpleOutliersDetectionMethod:
"""An simple LDA using sklearn. Inspired by the following: - http://scikit-learn.org/stable/auto_examples/svm/plot_oneclass.html"""
def __init__(self, clf_name):
"""Build Traditional Outliers classifier."""
self.clf_name = clf_name
if self.clf_n... | the_stack_v2_python_sparse | DAE_Method/ae_utilities.py | proy3/Abnormal_Trajectory_Classifier | train | 9 |
ea7d6cf30c80ce311f36a518cc10b97bbab23111 | [
"if isinstance(size, int):\n size = (size, size)\nself.mean = mean\nself.size = size\nself.out_augpos = out_augpos\nself.augment = A.Compose([A.Resize(size[0], size[1], interpolation=cv2.INTER_CUBIC, p=1), A.Normalize(mean=mean, std=std, p=1.0), ToTensor_albu()])\nif self.out_augpos is True:\n self.augment = ... | <|body_start_0|>
if isinstance(size, int):
size = (size, size)
self.mean = mean
self.size = size
self.out_augpos = out_augpos
self.augment = A.Compose([A.Resize(size[0], size[1], interpolation=cv2.INTER_CUBIC, p=1), A.Normalize(mean=mean, std=std, p=1.0), ToTensor_alb... | TestAugmentation_albu | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAugmentation_albu:
def __init__(self, size, mean=0, std=1.0, out_augpos=False):
"""Args: size: the size the of final image. mean: mean pixel value per channel."""
<|body_0|>
def __call__(self, img):
"""Args: img: the output of cv.imread in RGB layout. labels: lab... | stack_v2_sparse_classes_36k_train_000312 | 11,992 | permissive | [
{
"docstring": "Args: size: the size the of final image. mean: mean pixel value per channel.",
"name": "__init__",
"signature": "def __init__(self, size, mean=0, std=1.0, out_augpos=False)"
},
{
"docstring": "Args: img: the output of cv.imread in RGB layout. labels: labels of boxes.",
"name"... | 2 | null | Implement the Python class `TestAugmentation_albu` described below.
Class description:
Implement the TestAugmentation_albu class.
Method signatures and docstrings:
- def __init__(self, size, mean=0, std=1.0, out_augpos=False): Args: size: the size the of final image. mean: mean pixel value per channel.
- def __call__... | Implement the Python class `TestAugmentation_albu` described below.
Class description:
Implement the TestAugmentation_albu class.
Method signatures and docstrings:
- def __init__(self, size, mean=0, std=1.0, out_augpos=False): Args: size: the size the of final image. mean: mean pixel value per channel.
- def __call__... | e6c09414c49e695b0f4221a3c6245ae3929a1788 | <|skeleton|>
class TestAugmentation_albu:
def __init__(self, size, mean=0, std=1.0, out_augpos=False):
"""Args: size: the size the of final image. mean: mean pixel value per channel."""
<|body_0|>
def __call__(self, img):
"""Args: img: the output of cv.imread in RGB layout. labels: lab... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestAugmentation_albu:
def __init__(self, size, mean=0, std=1.0, out_augpos=False):
"""Args: size: the size the of final image. mean: mean pixel value per channel."""
if isinstance(size, int):
size = (size, size)
self.mean = mean
self.size = size
self.out_au... | the_stack_v2_python_sparse | data/transforms/data_preprocessing.py | zyxwvu321/Classifer_SSL_Longtail | train | 0 | |
d87861f102c5457c10b5e163c603a331a2382ca7 | [
"self.dict = defaultdict(list)\nfor x in dictionary:\n if len(x) > 2:\n key = x[0] + str(len(x) - 2) + x[-1]\n if x not in self.dict[key]:\n self.dict[key].append(x)",
"if len(word) <= 2:\n return True\nelse:\n key = word[0] + str(len(word) - 2) + word[-1]\n if key in self.dic... | <|body_start_0|>
self.dict = defaultdict(list)
for x in dictionary:
if len(x) > 2:
key = x[0] + str(len(x) - 2) + x[-1]
if x not in self.dict[key]:
self.dict[key].append(x)
<|end_body_0|>
<|body_start_1|>
if len(word) <= 2:
... | ValidWordAbbr | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
""":type dictionary: List[str]"""
<|body_0|>
def isUnique(self, word):
""":type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.dict = defaultdict(list)
for x in dict... | stack_v2_sparse_classes_36k_train_000313 | 3,100 | no_license | [
{
"docstring": ":type dictionary: List[str]",
"name": "__init__",
"signature": "def __init__(self, dictionary)"
},
{
"docstring": ":type word: str :rtype: bool",
"name": "isUnique",
"signature": "def isUnique(self, word)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000982 | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): :type dictionary: List[str]
- def isUnique(self, word): :type word: str :rtype: bool | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): :type dictionary: List[str]
- def isUnique(self, word): :type word: str :rtype: bool
<|skeleton|>
class ValidWordAbbr:
def __init_... | 824b9442852a7369885e1813ba6bfdb88168f1eb | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
""":type dictionary: List[str]"""
<|body_0|>
def isUnique(self, word):
""":type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValidWordAbbr:
def __init__(self, dictionary):
""":type dictionary: List[str]"""
self.dict = defaultdict(list)
for x in dictionary:
if len(x) > 2:
key = x[0] + str(len(x) - 2) + x[-1]
if x not in self.dict[key]:
self.dict[... | the_stack_v2_python_sparse | Dictionary/validWordAbbreviation.py | xingyazhou/Data-Structure-And-Algorithm | train | 0 | |
c54acc25dc59c76968832f307ed9334ae1e10a16 | [
"super().__init__(qubits)\nself.set_experiment_options(trials=trials)\nif not isinstance(seed, Generator):\n self._rng = default_rng(seed=seed)\nelse:\n self._rng = seed\nif not simulation_backend and HAS_SIMULATION_BACKEND:\n self._simulation_backend = Aer.get_backend('aer_simulator')\nelse:\n self._si... | <|body_start_0|>
super().__init__(qubits)
self.set_experiment_options(trials=trials)
if not isinstance(seed, Generator):
self._rng = default_rng(seed=seed)
else:
self._rng = seed
if not simulation_backend and HAS_SIMULATION_BACKEND:
self._simul... | Quantum Volume Experiment class. # section: overview Quantum Volume (QV) is a single-number metric that can be measured using a concrete protocol on near-term quantum computers of modest size. The QV method quantifies the largest random circuit of equal width and depth that the computer successfully implements. Quantum... | QuantumVolume | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuantumVolume:
"""Quantum Volume Experiment class. # section: overview Quantum Volume (QV) is a single-number metric that can be measured using a concrete protocol on near-term quantum computers of modest size. The QV method quantifies the largest random circuit of equal width and depth that the ... | stack_v2_sparse_classes_36k_train_000314 | 7,130 | permissive | [
{
"docstring": "Initialize a quantum volume experiment. Args: qubits: The number of qubits or list of physical qubits for the experiment. trials: The number of trials to run the quantum volume circuit. seed: Seed or generator object for random number generation. If None default_rng will be used. simulation_back... | 4 | stack_v2_sparse_classes_30k_train_005932 | Implement the Python class `QuantumVolume` described below.
Class description:
Quantum Volume Experiment class. # section: overview Quantum Volume (QV) is a single-number metric that can be measured using a concrete protocol on near-term quantum computers of modest size. The QV method quantifies the largest random cir... | Implement the Python class `QuantumVolume` described below.
Class description:
Quantum Volume Experiment class. # section: overview Quantum Volume (QV) is a single-number metric that can be measured using a concrete protocol on near-term quantum computers of modest size. The QV method quantifies the largest random cir... | 22b1598b290464e59a12853efa1eb99b1b36513a | <|skeleton|>
class QuantumVolume:
"""Quantum Volume Experiment class. # section: overview Quantum Volume (QV) is a single-number metric that can be measured using a concrete protocol on near-term quantum computers of modest size. The QV method quantifies the largest random circuit of equal width and depth that the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuantumVolume:
"""Quantum Volume Experiment class. # section: overview Quantum Volume (QV) is a single-number metric that can be measured using a concrete protocol on near-term quantum computers of modest size. The QV method quantifies the largest random circuit of equal width and depth that the computer succ... | the_stack_v2_python_sparse | qiskit_experiments/library/quantum_volume/qv_experiment.py | huggingworld/qiskit-experiments | train | 0 |
3d53c1aec4a26c471e66d8c60b20d73e7b36de34 | [
"self.SUBJECT = 'MOSJA00297'\nsuper(OASEMailUserLocked, self).__init__(self.MAILACC, addr_to, self.SUBJECT, '', inquiry_url, login_url, charset)\nself.create_mail_text(login_id, locked_url)",
"self.MAILTEXT = get_message('MOSJA00298', self.lang_mode, showMsgId=False, login_id=login_id, locked_url=locked_url)\nsel... | <|body_start_0|>
self.SUBJECT = 'MOSJA00297'
super(OASEMailUserLocked, self).__init__(self.MAILACC, addr_to, self.SUBJECT, '', inquiry_url, login_url, charset)
self.create_mail_text(login_id, locked_url)
<|end_body_0|>
<|body_start_1|>
self.MAILTEXT = get_message('MOSJA00298', self.lang... | [クラス概要] ユーザロック通知メール | OASEMailUserLocked | [
"Apache-2.0",
"BSD-3-Clause",
"LGPL-3.0-only",
"MIT",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OASEMailUserLocked:
"""[クラス概要] ユーザロック通知メール"""
def __init__(self, addr_to, login_id, locked_url, inquiry_url, login_url, charset='utf-8'):
"""[メソッド概要] 初期化処理 [引数] addr_to : str 宛先メールアドレス user_name : str 宛先ユーザ名 login_id : str ユーザロックされたログインID locked_url : str アカウントロックユーザ画面 inquiry_url : ... | stack_v2_sparse_classes_36k_train_000315 | 20,173 | permissive | [
{
"docstring": "[メソッド概要] 初期化処理 [引数] addr_to : str 宛先メールアドレス user_name : str 宛先ユーザ名 login_id : str ユーザロックされたログインID locked_url : str アカウントロックユーザ画面 inquiry_url : str お問い合わせ画面 login_url : str ログイン画面 charset : str 文字コード",
"name": "__init__",
"signature": "def __init__(self, addr_to, login_id, locked_url, inq... | 2 | null | Implement the Python class `OASEMailUserLocked` described below.
Class description:
[クラス概要] ユーザロック通知メール
Method signatures and docstrings:
- def __init__(self, addr_to, login_id, locked_url, inquiry_url, login_url, charset='utf-8'): [メソッド概要] 初期化処理 [引数] addr_to : str 宛先メールアドレス user_name : str 宛先ユーザ名 login_id : str ユーザロ... | Implement the Python class `OASEMailUserLocked` described below.
Class description:
[クラス概要] ユーザロック通知メール
Method signatures and docstrings:
- def __init__(self, addr_to, login_id, locked_url, inquiry_url, login_url, charset='utf-8'): [メソッド概要] 初期化処理 [引数] addr_to : str 宛先メールアドレス user_name : str 宛先ユーザ名 login_id : str ユーザロ... | c00ea4fe1bf4b4a18d545aabeaaf1d95c7664b94 | <|skeleton|>
class OASEMailUserLocked:
"""[クラス概要] ユーザロック通知メール"""
def __init__(self, addr_to, login_id, locked_url, inquiry_url, login_url, charset='utf-8'):
"""[メソッド概要] 初期化処理 [引数] addr_to : str 宛先メールアドレス user_name : str 宛先ユーザ名 login_id : str ユーザロックされたログインID locked_url : str アカウントロックユーザ画面 inquiry_url : ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OASEMailUserLocked:
"""[クラス概要] ユーザロック通知メール"""
def __init__(self, addr_to, login_id, locked_url, inquiry_url, login_url, charset='utf-8'):
"""[メソッド概要] 初期化処理 [引数] addr_to : str 宛先メールアドレス user_name : str 宛先ユーザ名 login_id : str ユーザロックされたログインID locked_url : str アカウントロックユーザ画面 inquiry_url : str お問い合わせ画面 ... | the_stack_v2_python_sparse | oase-root/libs/webcommonlibs/oase_mail.py | exastro-suite/oase | train | 10 |
f98e92f72564d29b42703ef3a9f6ba4e905a2962 | [
"self.sensor = Sensor('127.0.0.1', 8000)\nself.pump = Pump('127.0.0.1', 8000)\nself.pump.set_state = MagicMock(return_value=True)\nself.decider = Decider(100, 0.05)\nself.controller = Controller(self.sensor, self.pump, self.decider)\nself.outcomes_high_or_low = {(self.pump.PUMP_IN, 90): self.pump.PUMP_IN, (self.pum... | <|body_start_0|>
self.sensor = Sensor('127.0.0.1', 8000)
self.pump = Pump('127.0.0.1', 8000)
self.pump.set_state = MagicMock(return_value=True)
self.decider = Decider(100, 0.05)
self.controller = Controller(self.sensor, self.pump, self.decider)
self.outcomes_high_or_low =... | Unit tests for the Controller class | ControllerTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""Create the sensor, pump, decider, and controller. The sensor is not really needed, and the pump isn't either except for its constants. The decider specifies the target height and the margin, while the cont... | stack_v2_sparse_classes_36k_train_000316 | 5,926 | no_license | [
{
"docstring": "Create the sensor, pump, decider, and controller. The sensor is not really needed, and the pump isn't either except for its constants. The decider specifies the target height and the margin, while the controller is mainly needed for its constants (captured in a dict) as well.",
"name": "setU... | 3 | stack_v2_sparse_classes_30k_train_009778 | Implement the Python class `ControllerTests` described below.
Class description:
Unit tests for the Controller class
Method signatures and docstrings:
- def setUp(self): Create the sensor, pump, decider, and controller. The sensor is not really needed, and the pump isn't either except for its constants. The decider s... | Implement the Python class `ControllerTests` described below.
Class description:
Unit tests for the Controller class
Method signatures and docstrings:
- def setUp(self): Create the sensor, pump, decider, and controller. The sensor is not really needed, and the pump isn't either except for its constants. The decider s... | b1fea0309b3495b3e1dc167d7029bc9e4b6f00f1 | <|skeleton|>
class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""Create the sensor, pump, decider, and controller. The sensor is not really needed, and the pump isn't either except for its constants. The decider specifies the target height and the margin, while the cont... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""Create the sensor, pump, decider, and controller. The sensor is not really needed, and the pump isn't either except for its constants. The decider specifies the target height and the margin, while the controller is mai... | the_stack_v2_python_sparse | students/Craig_Morton/Lesson06/water-regulation/waterregulation/test.py | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | train | 4 |
0c9ca10416ad1839b4707750e461e70b22a5a01d | [
"super(Collider, self).update()\nif self.overlapping_sprites:\n for sprite in self.overlapping_sprites:\n sprite.die()\n self.die()",
"new_explosion = Explosion(x=self.x, y=self.y)\ngames.screen.add(new_explosion)\nself.destroy()"
] | <|body_start_0|>
super(Collider, self).update()
if self.overlapping_sprites:
for sprite in self.overlapping_sprites:
sprite.die()
self.die()
<|end_body_0|>
<|body_start_1|>
new_explosion = Explosion(x=self.x, y=self.y)
games.screen.add(new_explosi... | Погибатель. Огибатель, который может сталкиваться с другими объектами и гибнуть. | Collider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Collider:
"""Погибатель. Огибатель, который может сталкиваться с другими объектами и гибнуть."""
def update(self):
"""Проверяет, нет ли спрайтов, визуально перекрывающийся с данным."""
<|body_0|>
def die(self):
"""Разрушает объект со взрывом."""
<|body_1|... | stack_v2_sparse_classes_36k_train_000317 | 8,486 | no_license | [
{
"docstring": "Проверяет, нет ли спрайтов, визуально перекрывающийся с данным.",
"name": "update",
"signature": "def update(self)"
},
{
"docstring": "Разрушает объект со взрывом.",
"name": "die",
"signature": "def die(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013834 | Implement the Python class `Collider` described below.
Class description:
Погибатель. Огибатель, который может сталкиваться с другими объектами и гибнуть.
Method signatures and docstrings:
- def update(self): Проверяет, нет ли спрайтов, визуально перекрывающийся с данным.
- def die(self): Разрушает объект со взрывом. | Implement the Python class `Collider` described below.
Class description:
Погибатель. Огибатель, который может сталкиваться с другими объектами и гибнуть.
Method signatures and docstrings:
- def update(self): Проверяет, нет ли спрайтов, визуально перекрывающийся с данным.
- def die(self): Разрушает объект со взрывом.... | 8301d0d8bee63c8458aa1efaa3a983d9e6eb9043 | <|skeleton|>
class Collider:
"""Погибатель. Огибатель, который может сталкиваться с другими объектами и гибнуть."""
def update(self):
"""Проверяет, нет ли спрайтов, визуально перекрывающийся с данным."""
<|body_0|>
def die(self):
"""Разрушает объект со взрывом."""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Collider:
"""Погибатель. Огибатель, который может сталкиваться с другими объектами и гибнуть."""
def update(self):
"""Проверяет, нет ли спрайтов, визуально перекрывающийся с данным."""
super(Collider, self).update()
if self.overlapping_sprites:
for sprite in self.overl... | the_stack_v2_python_sparse | astrocrash7.py | apheyhys/Python | train | 0 |
fcbd2917c5948a09fd84096c6bea32b5e1406fdc | [
"self.filename = filename\nself.filevalid = False\nself.exifvalid = False\nimg = self.initImage()\nif self.filevalid == True:\n self.initExif(img)\n self.initDates()",
"try:\n img = Image.open(self.filename)\n self.filevalid = True\nexcept IOError:\n print('Target image not found/valid %s' % self.f... | <|body_start_0|>
self.filename = filename
self.filevalid = False
self.exifvalid = False
img = self.initImage()
if self.filevalid == True:
self.initExif(img)
self.initDates()
<|end_body_0|>
<|body_start_1|>
try:
img = Image.open(self.fi... | Photo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Photo:
def __init__(self, filename):
"""Class constructor"""
<|body_0|>
def initImage(self):
"""opens the image and confirms if valid, returns Image"""
<|body_1|>
def initExif(self, image):
"""gets any Exif data from the photo"""
<|body_2... | stack_v2_sparse_classes_36k_train_000318 | 2,822 | no_license | [
{
"docstring": "Class constructor",
"name": "__init__",
"signature": "def __init__(self, filename)"
},
{
"docstring": "opens the image and confirms if valid, returns Image",
"name": "initImage",
"signature": "def initImage(self)"
},
{
"docstring": "gets any Exif data from the pho... | 6 | null | Implement the Python class `Photo` described below.
Class description:
Implement the Photo class.
Method signatures and docstrings:
- def __init__(self, filename): Class constructor
- def initImage(self): opens the image and confirms if valid, returns Image
- def initExif(self, image): gets any Exif data from the pho... | Implement the Python class `Photo` described below.
Class description:
Implement the Photo class.
Method signatures and docstrings:
- def __init__(self, filename): Class constructor
- def initImage(self): opens the image and confirms if valid, returns Image
- def initExif(self, image): gets any Exif data from the pho... | fde65012c8358b7089d5b49e10fc4c566175e12e | <|skeleton|>
class Photo:
def __init__(self, filename):
"""Class constructor"""
<|body_0|>
def initImage(self):
"""opens the image and confirms if valid, returns Image"""
<|body_1|>
def initExif(self, image):
"""gets any Exif data from the photo"""
<|body_2... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Photo:
def __init__(self, filename):
"""Class constructor"""
self.filename = filename
self.filevalid = False
self.exifvalid = False
img = self.initImage()
if self.filevalid == True:
self.initExif(img)
self.initDates()
def initImage(s... | the_stack_v2_python_sparse | Packt/PacktRPiPython/Chapter 03/photohandler_1stpart.py | floppyinfant/RaspberryPi | train | 0 | |
497c4e04f29dca22f6ba71048e8804294d25c852 | [
"post_nodes = response.css('#archive .floated-thumb .post-thumb a')\nfor post_node in post_nodes:\n image_url = post_node.css('img::attr(src)').extract_first('')\n post_url = post_node.css('::attr(href)').extract_first('')\n yield Request(url=parse.urljoin(response.url, post_url), meta={'front_image_url': ... | <|body_start_0|>
post_nodes = response.css('#archive .floated-thumb .post-thumb a')
for post_node in post_nodes:
image_url = post_node.css('img::attr(src)').extract_first('')
post_url = post_node.css('::attr(href)').extract_first('')
yield Request(url=parse.urljoin(re... | JobboleSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JobboleSpider:
def parse(self, response):
"""1. 获取文章列表的url进行解析 2. 获取下一页的url并交给scrapy下载,完成后交给parse"""
<|body_0|>
def parse_detail(self, response):
"""# 实例化一个jobboleitem article_item = JobBoleArticleItem() # 获取meta,获取到Request的封面图提取出来 front_image_url = response.meta.get... | stack_v2_sparse_classes_36k_train_000319 | 5,949 | no_license | [
{
"docstring": "1. 获取文章列表的url进行解析 2. 获取下一页的url并交给scrapy下载,完成后交给parse",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "# 实例化一个jobboleitem article_item = JobBoleArticleItem() # 获取meta,获取到Request的封面图提取出来 front_image_url = response.meta.get('front_image_url', '') ------... | 2 | stack_v2_sparse_classes_30k_train_006720 | Implement the Python class `JobboleSpider` described below.
Class description:
Implement the JobboleSpider class.
Method signatures and docstrings:
- def parse(self, response): 1. 获取文章列表的url进行解析 2. 获取下一页的url并交给scrapy下载,完成后交给parse
- def parse_detail(self, response): # 实例化一个jobboleitem article_item = JobBoleArticleItem... | Implement the Python class `JobboleSpider` described below.
Class description:
Implement the JobboleSpider class.
Method signatures and docstrings:
- def parse(self, response): 1. 获取文章列表的url进行解析 2. 获取下一页的url并交给scrapy下载,完成后交给parse
- def parse_detail(self, response): # 实例化一个jobboleitem article_item = JobBoleArticleItem... | 5e84bb83d46454b06ab65b819fd0f962b4d40421 | <|skeleton|>
class JobboleSpider:
def parse(self, response):
"""1. 获取文章列表的url进行解析 2. 获取下一页的url并交给scrapy下载,完成后交给parse"""
<|body_0|>
def parse_detail(self, response):
"""# 实例化一个jobboleitem article_item = JobBoleArticleItem() # 获取meta,获取到Request的封面图提取出来 front_image_url = response.meta.get... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JobboleSpider:
def parse(self, response):
"""1. 获取文章列表的url进行解析 2. 获取下一页的url并交给scrapy下载,完成后交给parse"""
post_nodes = response.css('#archive .floated-thumb .post-thumb a')
for post_node in post_nodes:
image_url = post_node.css('img::attr(src)').extract_first('')
pos... | the_stack_v2_python_sparse | 爬虫 新scrape/爬虫 新scrape/scrapy_learn_bole-master/scrapy_learn_bole-master/ArticleSpider/spiders/jobbole.py | xzbuku/16219111133-qimo-work | train | 1 | |
3c97afd04c89080e44b74f9142464ac11cd81a10 | [
"if len(symbols) % 2 == 1:\n return False\nstack = []\nfor symbol in symbols:\n if symbol == '(' or symbol == '[' or symbol == '{':\n stack.append(symbol)\n else:\n if len(stack) == 0:\n return False\n popped = stack.pop()\n if popped == '(' and symbol != ')':\n ... | <|body_start_0|>
if len(symbols) % 2 == 1:
return False
stack = []
for symbol in symbols:
if symbol == '(' or symbol == '[' or symbol == '{':
stack.append(symbol)
else:
if len(stack) == 0:
return False
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isValid(self, symbols):
""":type symbols: str :rtype: bool"""
<|body_0|>
def isValid(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(symbols) % 2 == 1:
return False
stac... | stack_v2_sparse_classes_36k_train_000320 | 2,501 | no_license | [
{
"docstring": ":type symbols: str :rtype: bool",
"name": "isValid",
"signature": "def isValid(self, symbols)"
},
{
"docstring": ":type s: str :rtype: bool",
"name": "isValid",
"signature": "def isValid(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValid(self, symbols): :type symbols: str :rtype: bool
- def isValid(self, s): :type s: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValid(self, symbols): :type symbols: str :rtype: bool
- def isValid(self, s): :type s: str :rtype: bool
<|skeleton|>
class Solution:
def isValid(self, symbols):
... | 844f502da4d6fb9cd69cf0a1ef71da3385a4d2b4 | <|skeleton|>
class Solution:
def isValid(self, symbols):
""":type symbols: str :rtype: bool"""
<|body_0|>
def isValid(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isValid(self, symbols):
""":type symbols: str :rtype: bool"""
if len(symbols) % 2 == 1:
return False
stack = []
for symbol in symbols:
if symbol == '(' or symbol == '[' or symbol == '{':
stack.append(symbol)
else... | the_stack_v2_python_sparse | 20-valid_parentheses.py | stevestar888/leetcode-problems | train | 2 | |
cf2c02595365efd00b1628a9c11ab5e178f75920 | [
"if getattr(spec, 'project_id', None) and getattr(spec, 'labels', None):\n raise exceptions.ApiValueError(\"Can't set labels to a task inside a project. Tasks inside a project use project's labels.\", ['labels'])\ntask = self.create(spec=spec)\nself._client.logger.info('Created task ID: %s NAME: %s', task.id, ta... | <|body_start_0|>
if getattr(spec, 'project_id', None) and getattr(spec, 'labels', None):
raise exceptions.ApiValueError("Can't set labels to a task inside a project. Tasks inside a project use project's labels.", ['labels'])
task = self.create(spec=spec)
self._client.logger.info('Cre... | TasksRepo | [
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TasksRepo:
def create_from_data(self, spec: models.ITaskWriteRequest, resources: Sequence[StrPath], *, resource_type: ResourceType=ResourceType.LOCAL, data_params: Optional[Dict[str, Any]]=None, annotation_path: str='', annotation_format: str='CVAT XML 1.1', status_check_period: int=None, datase... | stack_v2_sparse_classes_36k_train_000321 | 14,269 | permissive | [
{
"docstring": "Create a new task with the given name and labels JSON and add the files to it. Returns: id of the created task",
"name": "create_from_data",
"signature": "def create_from_data(self, spec: models.ITaskWriteRequest, resources: Sequence[StrPath], *, resource_type: ResourceType=ResourceType.... | 3 | stack_v2_sparse_classes_30k_train_020574 | Implement the Python class `TasksRepo` described below.
Class description:
Implement the TasksRepo class.
Method signatures and docstrings:
- def create_from_data(self, spec: models.ITaskWriteRequest, resources: Sequence[StrPath], *, resource_type: ResourceType=ResourceType.LOCAL, data_params: Optional[Dict[str, Any]... | Implement the Python class `TasksRepo` described below.
Class description:
Implement the TasksRepo class.
Method signatures and docstrings:
- def create_from_data(self, spec: models.ITaskWriteRequest, resources: Sequence[StrPath], *, resource_type: ResourceType=ResourceType.LOCAL, data_params: Optional[Dict[str, Any]... | 899c9fd75146744def061efd7ab1b1c6c9f6942f | <|skeleton|>
class TasksRepo:
def create_from_data(self, spec: models.ITaskWriteRequest, resources: Sequence[StrPath], *, resource_type: ResourceType=ResourceType.LOCAL, data_params: Optional[Dict[str, Any]]=None, annotation_path: str='', annotation_format: str='CVAT XML 1.1', status_check_period: int=None, datase... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TasksRepo:
def create_from_data(self, spec: models.ITaskWriteRequest, resources: Sequence[StrPath], *, resource_type: ResourceType=ResourceType.LOCAL, data_params: Optional[Dict[str, Any]]=None, annotation_path: str='', annotation_format: str='CVAT XML 1.1', status_check_period: int=None, dataset_repository_u... | the_stack_v2_python_sparse | cvat-sdk/cvat_sdk/core/proxies/tasks.py | opencv/cvat | train | 6,558 | |
f9388c25b30a2c91e3dc6c31b945f6e137a77ff0 | [
"if len(coins) == 0:\n return -1\nif amount == 0:\n return 0\ncoins.sort()\ndp = [amount + 1] * (amount + 1)\nfor i in range(1, amount + 1):\n for c in coins:\n if i == c:\n dp[i] = 1\n elif i - c > 0 and dp[i - c] > 0:\n dp[i] = min(dp[i], dp[i - c] + 1)\n else:\... | <|body_start_0|>
if len(coins) == 0:
return -1
if amount == 0:
return 0
coins.sort()
dp = [amount + 1] * (amount + 1)
for i in range(1, amount + 1):
for c in coins:
if i == c:
dp[i] = 1
elif i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_0|>
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_000322 | 2,034 | no_license | [
{
"docstring": ":type coins: List[int] :type amount: int :rtype: int",
"name": "coinChange",
"signature": "def coinChange(self, coins, amount)"
},
{
"docstring": ":type coins: List[int] :type amount: int :rtype: int",
"name": "coinChange",
"signature": "def coinChange(self, coins, amount... | 2 | stack_v2_sparse_classes_30k_train_014114 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: int
- def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: int
- def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: ... | 63b7eedc720c1ce14880b80744dcd5ef7107065c | <|skeleton|>
class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_0|>
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
if len(coins) == 0:
return -1
if amount == 0:
return 0
coins.sort()
dp = [amount + 1] * (amount + 1)
for i in range(1, amount + 1):
... | the_stack_v2_python_sparse | problems/coinChange.py | joddiy/leetcode | train | 1 | |
7a4fec98df3d9b843373fdc1c8592dacbe431905 | [
"self._expression = expression\nif validate:\n self.is_valid(expression)\nself._transformer = self.EvaluateTree()\nself._parser = Lark(self.EXPRESSION_GRAMMAR, parser='lalr', transformer=self._transformer)",
"try:\n Lark(cls.EXPRESSION_GRAMMAR, parser='lalr').parse(expression)\nexcept UnexpectedToken as e:\... | <|body_start_0|>
self._expression = expression
if validate:
self.is_valid(expression)
self._transformer = self.EvaluateTree()
self._parser = Lark(self.EXPRESSION_GRAMMAR, parser='lalr', transformer=self._transformer)
<|end_body_0|>
<|body_start_1|>
try:
L... | Wrapper class providing repeated evaluation expressions with different parameters | ExpressionEvaluator | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExpressionEvaluator:
"""Wrapper class providing repeated evaluation expressions with different parameters"""
def __init__(self, expression: str, validate: bool=True):
"""Construct an expression evaluator. :param expression: str :param validate: bool, optional"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_000323 | 14,029 | permissive | [
{
"docstring": "Construct an expression evaluator. :param expression: str :param validate: bool, optional",
"name": "__init__",
"signature": "def __init__(self, expression: str, validate: bool=True)"
},
{
"docstring": "Validate the expression. Raises an InvalidExpression exception if invalid :pa... | 3 | null | Implement the Python class `ExpressionEvaluator` described below.
Class description:
Wrapper class providing repeated evaluation expressions with different parameters
Method signatures and docstrings:
- def __init__(self, expression: str, validate: bool=True): Construct an expression evaluator. :param expression: str... | Implement the Python class `ExpressionEvaluator` described below.
Class description:
Wrapper class providing repeated evaluation expressions with different parameters
Method signatures and docstrings:
- def __init__(self, expression: str, validate: bool=True): Construct an expression evaluator. :param expression: str... | 680b6a2b45f3c568d779d8ac86553a0b08c384c8 | <|skeleton|>
class ExpressionEvaluator:
"""Wrapper class providing repeated evaluation expressions with different parameters"""
def __init__(self, expression: str, validate: bool=True):
"""Construct an expression evaluator. :param expression: str :param validate: bool, optional"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExpressionEvaluator:
"""Wrapper class providing repeated evaluation expressions with different parameters"""
def __init__(self, expression: str, validate: bool=True):
"""Construct an expression evaluator. :param expression: str :param validate: bool, optional"""
self._expression = express... | the_stack_v2_python_sparse | seed/models/derived_columns.py | SEED-platform/seed | train | 108 |
f9e60960a5cf11441200ec474a266ed766c36a45 | [
"self.data_train = tfds.load('ted_hrlr_translate/pt_to_en', split='train', as_supervised=True)\nself.data_valid = tfds.load('ted_hrlr_translate/pt_to_en', split='validation', as_supervised=True)\ntokenizer_pt, tokenizer_en = self.tokenize_dataset(self.data_train)\nself.tokenizer_pt = tokenizer_pt\nself.tokenizer_en... | <|body_start_0|>
self.data_train = tfds.load('ted_hrlr_translate/pt_to_en', split='train', as_supervised=True)
self.data_valid = tfds.load('ted_hrlr_translate/pt_to_en', split='validation', as_supervised=True)
tokenizer_pt, tokenizer_en = self.tokenize_dataset(self.data_train)
self.token... | class dataset | Dataset | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dataset:
"""class dataset"""
def __init__(self):
"""constructor instance attributes: data_train: contains the ted_hrlr_translate/pt_to_en tf.data.Dataset train split, loaded as_supervided data_valid: contains the ted_hrlr_translate/pt_to_en tf.data.Dataset validate split, loaded as_s... | stack_v2_sparse_classes_36k_train_000324 | 1,987 | no_license | [
{
"docstring": "constructor instance attributes: data_train: contains the ted_hrlr_translate/pt_to_en tf.data.Dataset train split, loaded as_supervided data_valid: contains the ted_hrlr_translate/pt_to_en tf.data.Dataset validate split, loaded as_supervided tokenizer_pt: is the Portuguese tokenizer created from... | 2 | stack_v2_sparse_classes_30k_train_019193 | Implement the Python class `Dataset` described below.
Class description:
class dataset
Method signatures and docstrings:
- def __init__(self): constructor instance attributes: data_train: contains the ted_hrlr_translate/pt_to_en tf.data.Dataset train split, loaded as_supervided data_valid: contains the ted_hrlr_trans... | Implement the Python class `Dataset` described below.
Class description:
class dataset
Method signatures and docstrings:
- def __init__(self): constructor instance attributes: data_train: contains the ted_hrlr_translate/pt_to_en tf.data.Dataset train split, loaded as_supervided data_valid: contains the ted_hrlr_trans... | ff1af62484620b599cc3813068770db03b37036d | <|skeleton|>
class Dataset:
"""class dataset"""
def __init__(self):
"""constructor instance attributes: data_train: contains the ted_hrlr_translate/pt_to_en tf.data.Dataset train split, loaded as_supervided data_valid: contains the ted_hrlr_translate/pt_to_en tf.data.Dataset validate split, loaded as_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dataset:
"""class dataset"""
def __init__(self):
"""constructor instance attributes: data_train: contains the ted_hrlr_translate/pt_to_en tf.data.Dataset train split, loaded as_supervided data_valid: contains the ted_hrlr_translate/pt_to_en tf.data.Dataset validate split, loaded as_supervided tok... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/0-dataset.py | paurbano/holbertonschool-machine_learning | train | 0 |
4042b2b1fd6ef6652ca7cf655e1179c6e89d6144 | [
"g.sort()\ns.sort()\nchild = cookie = 0\nnum_cookies = len(s)\nnum_children = len(g)\nwhile cookie < num_cookies and child < num_children:\n if s[cookie] >= g[child]:\n child += 1\n cookie += 1\nreturn child",
"heapq.heapify(s)\ncount = 0\ng.sort()\nfor child in g:\n if not s:\n return coun... | <|body_start_0|>
g.sort()
s.sort()
child = cookie = 0
num_cookies = len(s)
num_children = len(g)
while cookie < num_cookies and child < num_children:
if s[cookie] >= g[child]:
child += 1
cookie += 1
return child
<|end_body_0... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findContentChildren(self, g, s):
"""Purpose: Given greed factor g[i] of each child, returns the max. number of children that are content after distributing cookies of size s[i]. Note: A child is content if they eat a cookie that has size greater than or equal to their greed... | stack_v2_sparse_classes_36k_train_000325 | 1,204 | no_license | [
{
"docstring": "Purpose: Given greed factor g[i] of each child, returns the max. number of children that are content after distributing cookies of size s[i]. Note: A child is content if they eat a cookie that has size greater than or equal to their greed factor. Sample Input: g = [1,2,3], s= [1,1] Sample Output... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findContentChildren(self, g, s): Purpose: Given greed factor g[i] of each child, returns the max. number of children that are content after distributing cookies of size s[i].... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findContentChildren(self, g, s): Purpose: Given greed factor g[i] of each child, returns the max. number of children that are content after distributing cookies of size s[i].... | 95a86cbbca28d0c0f6d72d28a2f1cb5a86327934 | <|skeleton|>
class Solution:
def findContentChildren(self, g, s):
"""Purpose: Given greed factor g[i] of each child, returns the max. number of children that are content after distributing cookies of size s[i]. Note: A child is content if they eat a cookie that has size greater than or equal to their greed... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findContentChildren(self, g, s):
"""Purpose: Given greed factor g[i] of each child, returns the max. number of children that are content after distributing cookies of size s[i]. Note: A child is content if they eat a cookie that has size greater than or equal to their greed factor. Sampl... | the_stack_v2_python_sparse | assignCookies.py | tashakim/puzzles_python | train | 8 | |
b58b0dbd0d8180852362bbe7fa889fbc8506e80b | [
"super().__init__(self.PROBLEM_NAME)\nself.input_string = input_string\nself.pattern = pattern",
"print('Solving {} problem ...'.format(self.PROBLEM_NAME))\ninput_string_length = len(self.input_string)\npattern_length = len(self.pattern)\nmatch_matrix = [[False] * (input_string_length + 1) for _ in range(pattern_... | <|body_start_0|>
super().__init__(self.PROBLEM_NAME)
self.input_string = input_string
self.pattern = pattern
<|end_body_0|>
<|body_start_1|>
print('Solving {} problem ...'.format(self.PROBLEM_NAME))
input_string_length = len(self.input_string)
pattern_length = len(self.p... | WildcardMatching | WildcardMatching | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WildcardMatching:
"""WildcardMatching"""
def __init__(self, input_string, pattern):
"""StrStr Args: input_string: haystack pattern: to be searched in the haystack Returns: None Raises: None"""
<|body_0|>
def solve(self):
"""Solve the problem Note: O(mn), space co... | stack_v2_sparse_classes_36k_train_000326 | 2,662 | no_license | [
{
"docstring": "StrStr Args: input_string: haystack pattern: to be searched in the haystack Returns: None Raises: None",
"name": "__init__",
"signature": "def __init__(self, input_string, pattern)"
},
{
"docstring": "Solve the problem Note: O(mn), space complexity: O(mn), where n = len(s), m = l... | 2 | stack_v2_sparse_classes_30k_train_010454 | Implement the Python class `WildcardMatching` described below.
Class description:
WildcardMatching
Method signatures and docstrings:
- def __init__(self, input_string, pattern): StrStr Args: input_string: haystack pattern: to be searched in the haystack Returns: None Raises: None
- def solve(self): Solve the problem ... | Implement the Python class `WildcardMatching` described below.
Class description:
WildcardMatching
Method signatures and docstrings:
- def __init__(self, input_string, pattern): StrStr Args: input_string: haystack pattern: to be searched in the haystack Returns: None Raises: None
- def solve(self): Solve the problem ... | 11f4d25cb211740514c119a60962d075a0817abd | <|skeleton|>
class WildcardMatching:
"""WildcardMatching"""
def __init__(self, input_string, pattern):
"""StrStr Args: input_string: haystack pattern: to be searched in the haystack Returns: None Raises: None"""
<|body_0|>
def solve(self):
"""Solve the problem Note: O(mn), space co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WildcardMatching:
"""WildcardMatching"""
def __init__(self, input_string, pattern):
"""StrStr Args: input_string: haystack pattern: to be searched in the haystack Returns: None Raises: None"""
super().__init__(self.PROBLEM_NAME)
self.input_string = input_string
self.patter... | the_stack_v2_python_sparse | python/problems/dynamic_programming/wildcard_matching.py | santhosh-kumar/AlgorithmsAndDataStructures | train | 2 |
6ba7b4433a5e22e3dc3f9e7604701f0b05c6858f | [
"low_bound = self.action_space.low\nupper_bound = self.action_space.high\naction = low_bound + (action + 1.0) * 0.5 * (upper_bound - low_bound)\naction = np.clip(action, low_bound, upper_bound)\nreturn action",
"low_bound = self.action_space.low\nupper_bound = self.action_space.high\naction = 2 * (action - low_bo... | <|body_start_0|>
low_bound = self.action_space.low
upper_bound = self.action_space.high
action = low_bound + (action + 1.0) * 0.5 * (upper_bound - low_bound)
action = np.clip(action, low_bound, upper_bound)
return action
<|end_body_0|>
<|body_start_1|>
low_bound = self.a... | 将 action 范围重新映射 | NormalizedActions | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NormalizedActions:
"""将 action 范围重新映射"""
def action(self, action):
"""将输入给 env.step(action) 的 action 进行重新修改,从 tanh 的 [-1,1] 映射到环境 [-2,2]"""
<|body_0|>
def reverse_action(self, action):
"""将 action 进行重新修改,从 环境 [-2,2] 映射到 [-1,1] (暂未用到)"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_000327 | 2,304 | permissive | [
{
"docstring": "将输入给 env.step(action) 的 action 进行重新修改,从 tanh 的 [-1,1] 映射到环境 [-2,2]",
"name": "action",
"signature": "def action(self, action)"
},
{
"docstring": "将 action 进行重新修改,从 环境 [-2,2] 映射到 [-1,1] (暂未用到)",
"name": "reverse_action",
"signature": "def reverse_action(self, action)"
}
... | 2 | null | Implement the Python class `NormalizedActions` described below.
Class description:
将 action 范围重新映射
Method signatures and docstrings:
- def action(self, action): 将输入给 env.step(action) 的 action 进行重新修改,从 tanh 的 [-1,1] 映射到环境 [-2,2]
- def reverse_action(self, action): 将 action 进行重新修改,从 环境 [-2,2] 映射到 [-1,1] (暂未用到) | Implement the Python class `NormalizedActions` described below.
Class description:
将 action 范围重新映射
Method signatures and docstrings:
- def action(self, action): 将输入给 env.step(action) 的 action 进行重新修改,从 tanh 的 [-1,1] 映射到环境 [-2,2]
- def reverse_action(self, action): 将 action 进行重新修改,从 环境 [-2,2] 映射到 [-1,1] (暂未用到)
<|skele... | 27905f1c1890b1aff907564230b4ec0c22e60ba0 | <|skeleton|>
class NormalizedActions:
"""将 action 范围重新映射"""
def action(self, action):
"""将输入给 env.step(action) 的 action 进行重新修改,从 tanh 的 [-1,1] 映射到环境 [-2,2]"""
<|body_0|>
def reverse_action(self, action):
"""将 action 进行重新修改,从 环境 [-2,2] 映射到 [-1,1] (暂未用到)"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NormalizedActions:
"""将 action 范围重新映射"""
def action(self, action):
"""将输入给 env.step(action) 的 action 进行重新修改,从 tanh 的 [-1,1] 映射到环境 [-2,2]"""
low_bound = self.action_space.low
upper_bound = self.action_space.high
action = low_bound + (action + 1.0) * 0.5 * (upper_bound - low... | the_stack_v2_python_sparse | Independent/DDPG/env.py | FZenjoys/RL-Algorithms-Implement | train | 0 |
76aa3dd358e706c7c3fff32cc728bcac8ff3aa61 | [
"try:\n self.dmp = apps.get_app_config('django_mako_plus')\nexcept LookupError:\n raise ImproperlyConfigured('`django_mako_plus` must be listed in INSTALLED_APPS before it can be used')\nself.template_loaders = {}\ncontext_processors = []\nfor processor in itertools.chain(BUILTIN_CONTEXT_PROCESSORS, self.dmp.... | <|body_start_0|>
try:
self.dmp = apps.get_app_config('django_mako_plus')
except LookupError:
raise ImproperlyConfigured('`django_mako_plus` must be listed in INSTALLED_APPS before it can be used')
self.template_loaders = {}
context_processors = []
for proc... | The primary Mako interface that plugs into the Django templating system. This is referenced in settings.py -> TEMPLATES. | MakoTemplates | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MakoTemplates:
"""The primary Mako interface that plugs into the Django templating system. This is referenced in settings.py -> TEMPLATES."""
def __init__(self, params):
"""Constructor"""
<|body_0|>
def from_string(self, template_code):
"""Compiles a template fro... | stack_v2_sparse_classes_36k_train_000328 | 7,053 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, params)"
},
{
"docstring": "Compiles a template from the given string. This is one of the required methods of Django template engines.",
"name": "from_string",
"signature": "def from_string(self, template_... | 5 | stack_v2_sparse_classes_30k_train_010311 | Implement the Python class `MakoTemplates` described below.
Class description:
The primary Mako interface that plugs into the Django templating system. This is referenced in settings.py -> TEMPLATES.
Method signatures and docstrings:
- def __init__(self, params): Constructor
- def from_string(self, template_code): Co... | Implement the Python class `MakoTemplates` described below.
Class description:
The primary Mako interface that plugs into the Django templating system. This is referenced in settings.py -> TEMPLATES.
Method signatures and docstrings:
- def __init__(self, params): Constructor
- def from_string(self, template_code): Co... | f50c4626bcf444cb2e3fa7ebfbc149ace21af681 | <|skeleton|>
class MakoTemplates:
"""The primary Mako interface that plugs into the Django templating system. This is referenced in settings.py -> TEMPLATES."""
def __init__(self, params):
"""Constructor"""
<|body_0|>
def from_string(self, template_code):
"""Compiles a template fro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MakoTemplates:
"""The primary Mako interface that plugs into the Django templating system. This is referenced in settings.py -> TEMPLATES."""
def __init__(self, params):
"""Constructor"""
try:
self.dmp = apps.get_app_config('django_mako_plus')
except LookupError:
... | the_stack_v2_python_sparse | django_mako_plus/engine.py | doconix/django-mako-plus | train | 82 |
5a469e52af75283a16e0952d4e5f61ed85d3823c | [
"if not root:\n return ''\nlevels = []\nq = [root]\nwhile q:\n nq = []\n children = []\n for node in q:\n cs = []\n for c in node.children:\n cs.append(len(nq))\n nq.append(c)\n children.append(cs)\n s = '+'.join(['-'.join([str(v), ','.join(map(str, c))]) fo... | <|body_start_0|>
if not root:
return ''
levels = []
q = [root]
while q:
nq = []
children = []
for node in q:
cs = []
for c in node.children:
cs.append(len(nq))
nq.appen... | Codec | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_000329 | 1,731 | permissive | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root: 'Node') -> str"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def des... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | 1dbd18114ed688ddeaa3ee83181d373dcc1429e5 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
if not root:
return ''
levels = []
q = [root]
while q:
nq = []
children = []
for node in q:
... | the_stack_v2_python_sparse | source/All_Solutions/0428.序列化和反序列化N叉树/0428-序列化和反序列化N叉树.py | zhangwang0537/LeetCode-Notebook | train | 0 | |
d9eda85894984efa63770497bf5a1461efb38e92 | [
"self.xs = np.array(sorted(data))\nself.N = float(len(self.xs))\nself.ys = np.arange(1, self.N + 1) / self.N",
"if type(x) is np.float64:\n x = np.array([x])\nndx = [np.argmin(np.abs(self.xs - x[i])) for i in range(x.size)]\nreturn self.ys[ndx]"
] | <|body_start_0|>
self.xs = np.array(sorted(data))
self.N = float(len(self.xs))
self.ys = np.arange(1, self.N + 1) / self.N
<|end_body_0|>
<|body_start_1|>
if type(x) is np.float64:
x = np.array([x])
ndx = [np.argmin(np.abs(self.xs - x[i])) for i in range(x.size)]
... | CDF | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CDF:
def __init__(self, data):
"""Generate an emperical cumulative distribution function from data :param data: x-values of data in no particular order :type data: list"""
<|body_0|>
def cdf(self, x):
"""Callable cumulative emperical distribution function :param x: a... | stack_v2_sparse_classes_36k_train_000330 | 8,570 | permissive | [
{
"docstring": "Generate an emperical cumulative distribution function from data :param data: x-values of data in no particular order :type data: list",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "Callable cumulative emperical distribution function :param x: ar... | 2 | stack_v2_sparse_classes_30k_test_000945 | Implement the Python class `CDF` described below.
Class description:
Implement the CDF class.
Method signatures and docstrings:
- def __init__(self, data): Generate an emperical cumulative distribution function from data :param data: x-values of data in no particular order :type data: list
- def cdf(self, x): Callabl... | Implement the Python class `CDF` described below.
Class description:
Implement the CDF class.
Method signatures and docstrings:
- def __init__(self, data): Generate an emperical cumulative distribution function from data :param data: x-values of data in no particular order :type data: list
- def cdf(self, x): Callabl... | e94694f298909352d7e9d912625314a1e46aa5b6 | <|skeleton|>
class CDF:
def __init__(self, data):
"""Generate an emperical cumulative distribution function from data :param data: x-values of data in no particular order :type data: list"""
<|body_0|>
def cdf(self, x):
"""Callable cumulative emperical distribution function :param x: a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CDF:
def __init__(self, data):
"""Generate an emperical cumulative distribution function from data :param data: x-values of data in no particular order :type data: list"""
self.xs = np.array(sorted(data))
self.N = float(len(self.xs))
self.ys = np.arange(1, self.N + 1) / self.N
... | the_stack_v2_python_sparse | LLC_Membranes/timeseries/brownian_mean_first_passage_time.py | NKM-ML/LLC_Membranes | train | 0 | |
25be4c33a6df43f2b7267bca45aec9bd553fa021 | [
"url_filter_keys = []\nfor fn in htmDump['worldUpdate']['applicationPresModel']['workbookPresModel']['dashboardPresModel']['userActions']:\n if fn.get('name', '').lower().startswith('map filter'):\n _, *rest = urllib.parse.unquote(fn.get('linkSpec').get('url')).split('?')\n rest = '?'.join(rest)\n ... | <|body_start_0|>
url_filter_keys = []
for fn in htmDump['worldUpdate']['applicationPresModel']['workbookPresModel']['dashboardPresModel']['userActions']:
if fn.get('name', '').lower().startswith('map filter'):
_, *rest = urllib.parse.unquote(fn.get('linkSpec').get('url')).spl... | Defines a few commonly-used helper methods for snagging Tableau data from mapclick-driven dashboard pages specifically | TableauMapClick | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TableauMapClick:
"""Defines a few commonly-used helper methods for snagging Tableau data from mapclick-driven dashboard pages specifically"""
def getTbluMapFilter(self, htmDump) -> List:
"""Extracts the onMapClick background data filter function from a raw tableau HTML bootstrap retu... | stack_v2_sparse_classes_36k_train_000331 | 35,919 | permissive | [
{
"docstring": "Extracts the onMapClick background data filter function from a raw tableau HTML bootstrap return Parameters ---------- htmdump : json The raw json-ized output of the info field from getRawTbluPageData Returns ------- _ : List The Tableau-view-specific json filter function called onMapClick",
... | 3 | stack_v2_sparse_classes_30k_test_000387 | Implement the Python class `TableauMapClick` described below.
Class description:
Defines a few commonly-used helper methods for snagging Tableau data from mapclick-driven dashboard pages specifically
Method signatures and docstrings:
- def getTbluMapFilter(self, htmDump) -> List: Extracts the onMapClick background da... | Implement the Python class `TableauMapClick` described below.
Class description:
Defines a few commonly-used helper methods for snagging Tableau data from mapclick-driven dashboard pages specifically
Method signatures and docstrings:
- def getTbluMapFilter(self, htmDump) -> List: Extracts the onMapClick background da... | e953871679222791f751b9bc26146ea607ebd937 | <|skeleton|>
class TableauMapClick:
"""Defines a few commonly-used helper methods for snagging Tableau data from mapclick-driven dashboard pages specifically"""
def getTbluMapFilter(self, htmDump) -> List:
"""Extracts the onMapClick background data filter function from a raw tableau HTML bootstrap retu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TableauMapClick:
"""Defines a few commonly-used helper methods for snagging Tableau data from mapclick-driven dashboard pages specifically"""
def getTbluMapFilter(self, htmDump) -> List:
"""Extracts the onMapClick background data filter function from a raw tableau HTML bootstrap return Parameters... | the_stack_v2_python_sparse | can_tools/scrapers/official/base.py | mehanig/can-scrapers | train | 1 |
6bb7502c7aaa00b29a844bcbc2136ee65df69ff6 | [
"self.ngroups = 0\nself.nwings = 0\nself.area = 0.0\nngrp = 0\nself.groups = {}\nif bool(data):\n for key in sorted(data):\n self.groups[ngrp] = wing_group(data[key], key, nseg)\n self.nwings = self.nwings + self.groups[ngrp].nwings\n ngrp = ngrp + 1\n self.ngroups = ngrp",
"weights = {... | <|body_start_0|>
self.ngroups = 0
self.nwings = 0
self.area = 0.0
ngrp = 0
self.groups = {}
if bool(data):
for key in sorted(data):
self.groups[ngrp] = wing_group(data[key], key, nseg)
self.nwings = self.nwings + self.groups[ngr... | wings | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class wings:
def __init__(self, data={}, nseg=0):
"""initialization function for all wing groups"""
<|body_0|>
def weight_rollup(self, GTOW, tech_factors, redundancy, rotor):
"""function to calculate weight of all fixed wings Input: 1. GTOW : gross take-off weight in lbs 2... | stack_v2_sparse_classes_36k_train_000332 | 14,547 | permissive | [
{
"docstring": "initialization function for all wing groups",
"name": "__init__",
"signature": "def __init__(self, data={}, nseg=0)"
},
{
"docstring": "function to calculate weight of all fixed wings Input: 1. GTOW : gross take-off weight in lbs 2. tech_factors : technology factor to scale outpu... | 3 | null | Implement the Python class `wings` described below.
Class description:
Implement the wings class.
Method signatures and docstrings:
- def __init__(self, data={}, nseg=0): initialization function for all wing groups
- def weight_rollup(self, GTOW, tech_factors, redundancy, rotor): function to calculate weight of all f... | Implement the Python class `wings` described below.
Class description:
Implement the wings class.
Method signatures and docstrings:
- def __init__(self, data={}, nseg=0): initialization function for all wing groups
- def weight_rollup(self, GTOW, tech_factors, redundancy, rotor): function to calculate weight of all f... | 3f754e1bd3cebdb5b5c68c8a2d84c47be1df2f02 | <|skeleton|>
class wings:
def __init__(self, data={}, nseg=0):
"""initialization function for all wing groups"""
<|body_0|>
def weight_rollup(self, GTOW, tech_factors, redundancy, rotor):
"""function to calculate weight of all fixed wings Input: 1. GTOW : gross take-off weight in lbs 2... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class wings:
def __init__(self, data={}, nseg=0):
"""initialization function for all wing groups"""
self.ngroups = 0
self.nwings = 0
self.area = 0.0
ngrp = 0
self.groups = {}
if bool(data):
for key in sorted(data):
self.groups[ngrp]... | the_stack_v2_python_sparse | src/Python/Stage_1/wing_class.py | gkdas2/vtol_sizing | train | 0 | |
20537586c6018a6cec0a153a8e5597f63eff6a9a | [
"result = {}\nargs = PROPERTY_PUT_PARSER.parse_args()\ncurrent_app.logger.info(args)\nsection = args.get(self.section).upper()\nmodules = section.split('.')\nsubmodule = None\nif len(modules) > 1:\n submodule = modules[1]\nconfigurators = CPI_INSTANCE.get_configurators(modules[0], submodule)\nif len(configurator... | <|body_start_0|>
result = {}
args = PROPERTY_PUT_PARSER.parse_args()
current_app.logger.info(args)
section = args.get(self.section).upper()
modules = section.split('.')
submodule = None
if len(modules) > 1:
submodule = modules[1]
configurators ... | restful api for configurator, in order to provide the method of put and get | Configurator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Configurator:
"""restful api for configurator, in order to provide the method of put and get"""
def put(self):
"""calling cpi set method to set the value of the given key :param section: The section of the cpi :param key: the key to be set :param value: the value of the given key :re... | stack_v2_sparse_classes_36k_train_000333 | 5,109 | no_license | [
{
"docstring": "calling cpi set method to set the value of the given key :param section: The section of the cpi :param key: the key to be set :param value: the value of the given key :returns status: the status return by the cpi set method :returns value: the message return by the cpi set method",
"name": "... | 3 | null | Implement the Python class `Configurator` described below.
Class description:
restful api for configurator, in order to provide the method of put and get
Method signatures and docstrings:
- def put(self): calling cpi set method to set the value of the given key :param section: The section of the cpi :param key: the k... | Implement the Python class `Configurator` described below.
Class description:
restful api for configurator, in order to provide the method of put and get
Method signatures and docstrings:
- def put(self): calling cpi set method to set the value of the given key :param section: The section of the cpi :param key: the k... | 12c0ade407a991f7d11b854d4f587b1764bbc4f5 | <|skeleton|>
class Configurator:
"""restful api for configurator, in order to provide the method of put and get"""
def put(self):
"""calling cpi set method to set the value of the given key :param section: The section of the cpi :param key: the key to be set :param value: the value of the given key :re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Configurator:
"""restful api for configurator, in order to provide the method of put and get"""
def put(self):
"""calling cpi set method to set the value of the given key :param section: The section of the cpi :param key: the key to be set :param value: the value of the given key :returns status:... | the_stack_v2_python_sparse | analysis/atuned/configurator.py | openeuler-mirror/A-Tune | train | 18 |
fe851e8badd441176ab25aecc4257dc9083d6f81 | [
"if get_jwt_claims()['admin']:\n args = self.reqparser.parse_args()\n new_api_key = args['new_api_key']\n sendgrid_response = SendgridHelper.send_test_request(new_api_key)\n result, _ = SendgridHelper.handle_sendgrid_response(sendgrid_response)\n if result['api_key']:\n is_replaced, reason = s... | <|body_start_0|>
if get_jwt_claims()['admin']:
args = self.reqparser.parse_args()
new_api_key = args['new_api_key']
sendgrid_response = SendgridHelper.send_test_request(new_api_key)
result, _ = SendgridHelper.handle_sendgrid_response(sendgrid_response)
... | API endpoint, replace the current Sendgrid API key environment variable | ReplaceKey | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReplaceKey:
"""API endpoint, replace the current Sendgrid API key environment variable"""
def post(self) -> (dict, int):
"""POST request endpoint. Test whether new API key is valid and if so, replace the current Sendgrid API environment variable :return: a dictionary containing boole... | stack_v2_sparse_classes_36k_train_000334 | 6,487 | permissive | [
{
"docstring": "POST request endpoint. Test whether new API key is valid and if so, replace the current Sendgrid API environment variable :return: a dictionary containing boolean value indicating whether the replacement procedure was successful",
"name": "post",
"signature": "def post(self) -> (dict, in... | 2 | stack_v2_sparse_classes_30k_train_006951 | Implement the Python class `ReplaceKey` described below.
Class description:
API endpoint, replace the current Sendgrid API key environment variable
Method signatures and docstrings:
- def post(self) -> (dict, int): POST request endpoint. Test whether new API key is valid and if so, replace the current Sendgrid API en... | Implement the Python class `ReplaceKey` described below.
Class description:
API endpoint, replace the current Sendgrid API key environment variable
Method signatures and docstrings:
- def post(self) -> (dict, int): POST request endpoint. Test whether new API key is valid and if so, replace the current Sendgrid API en... | 5d123691d1f25d0b85e20e4e8293266bf23c9f8a | <|skeleton|>
class ReplaceKey:
"""API endpoint, replace the current Sendgrid API key environment variable"""
def post(self) -> (dict, int):
"""POST request endpoint. Test whether new API key is valid and if so, replace the current Sendgrid API environment variable :return: a dictionary containing boole... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReplaceKey:
"""API endpoint, replace the current Sendgrid API key environment variable"""
def post(self) -> (dict, int):
"""POST request endpoint. Test whether new API key is valid and if so, replace the current Sendgrid API environment variable :return: a dictionary containing boolean value indi... | the_stack_v2_python_sparse | Analytics/resources/sendgrid_management.py | thanosbnt/SharingCitiesDashboard | train | 0 |
601034d873d29dac934b7c63ff0f0a33d36bb082 | [
"super(VisualSoftDotAttention, self).__init__()\nself.linear_in_h = nn.Linear(h_dim, dot_dim, bias=True)\nself.linear_in_v = nn.Linear(v_dim, dot_dim, bias=True)\nself.sm = nn.Softmax(dim=1)",
"target = self.linear_in_h(h).unsqueeze(2)\ncontext = self.linear_in_v(visual_context)\nattn = torch.bmm(context, target)... | <|body_start_0|>
super(VisualSoftDotAttention, self).__init__()
self.linear_in_h = nn.Linear(h_dim, dot_dim, bias=True)
self.linear_in_v = nn.Linear(v_dim, dot_dim, bias=True)
self.sm = nn.Softmax(dim=1)
<|end_body_0|>
<|body_start_1|>
target = self.linear_in_h(h).unsqueeze(2)
... | Visual Dot Attention Layer. | VisualSoftDotAttention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VisualSoftDotAttention:
"""Visual Dot Attention Layer."""
def __init__(self, h_dim, v_dim, dot_dim=256):
"""Initialize layer."""
<|body_0|>
def forward(self, h, visual_context, mask=None):
"""Propagate h through the network. h: batch x h_dim visual_context: batch... | stack_v2_sparse_classes_36k_train_000335 | 22,228 | permissive | [
{
"docstring": "Initialize layer.",
"name": "__init__",
"signature": "def __init__(self, h_dim, v_dim, dot_dim=256)"
},
{
"docstring": "Propagate h through the network. h: batch x h_dim visual_context: batch x v_num x v_dim",
"name": "forward",
"signature": "def forward(self, h, visual_c... | 2 | stack_v2_sparse_classes_30k_train_003398 | Implement the Python class `VisualSoftDotAttention` described below.
Class description:
Visual Dot Attention Layer.
Method signatures and docstrings:
- def __init__(self, h_dim, v_dim, dot_dim=256): Initialize layer.
- def forward(self, h, visual_context, mask=None): Propagate h through the network. h: batch x h_dim ... | Implement the Python class `VisualSoftDotAttention` described below.
Class description:
Visual Dot Attention Layer.
Method signatures and docstrings:
- def __init__(self, h_dim, v_dim, dot_dim=256): Initialize layer.
- def forward(self, h, visual_context, mask=None): Propagate h through the network. h: batch x h_dim ... | 868fb53d6b7978bbb10439a59e65044c811ee5c2 | <|skeleton|>
class VisualSoftDotAttention:
"""Visual Dot Attention Layer."""
def __init__(self, h_dim, v_dim, dot_dim=256):
"""Initialize layer."""
<|body_0|>
def forward(self, h, visual_context, mask=None):
"""Propagate h through the network. h: batch x h_dim visual_context: batch... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VisualSoftDotAttention:
"""Visual Dot Attention Layer."""
def __init__(self, h_dim, v_dim, dot_dim=256):
"""Initialize layer."""
super(VisualSoftDotAttention, self).__init__()
self.linear_in_h = nn.Linear(h_dim, dot_dim, bias=True)
self.linear_in_v = nn.Linear(v_dim, dot_d... | the_stack_v2_python_sparse | tasks/R2R/speaker/model.py | weituo12321/PREVALENT_R2R | train | 8 |
b99ae06ab598b2f87aa2dc40d929f9f8e1f31faf | [
"super(DecoderBlock, self).__init__()\nself.mha1 = MultiHeadAttention(dm, h)\nself.mha2 = MultiHeadAttention(dm, h)\nself.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')\nself.dense_output = tf.keras.layers.Dense(dm)\nself.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.layernor... | <|body_start_0|>
super(DecoderBlock, self).__init__()
self.mha1 = MultiHeadAttention(dm, h)
self.mha2 = MultiHeadAttention(dm, h)
self.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')
self.dense_output = tf.keras.layers.Dense(dm)
self.layernorm1 = tf.keras.... | class | DecoderBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecoderBlock:
"""class"""
def __init__(self, dm, h, hidden, rate=0.1):
"""constructor"""
<|body_0|>
def call(self, x, enc_output, training, look_ahead_mask, padding_mask):
"""method"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(DecoderBl... | stack_v2_sparse_classes_36k_train_000336 | 1,573 | no_license | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self, dm, h, hidden, rate=0.1)"
},
{
"docstring": "method",
"name": "call",
"signature": "def call(self, x, enc_output, training, look_ahead_mask, padding_mask)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003256 | Implement the Python class `DecoderBlock` described below.
Class description:
class
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, rate=0.1): constructor
- def call(self, x, enc_output, training, look_ahead_mask, padding_mask): method | Implement the Python class `DecoderBlock` described below.
Class description:
class
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, rate=0.1): constructor
- def call(self, x, enc_output, training, look_ahead_mask, padding_mask): method
<|skeleton|>
class DecoderBlock:
"""class"""
def _... | b5e8f1253309567ca7be71b9575a150de1be3820 | <|skeleton|>
class DecoderBlock:
"""class"""
def __init__(self, dm, h, hidden, rate=0.1):
"""constructor"""
<|body_0|>
def call(self, x, enc_output, training, look_ahead_mask, padding_mask):
"""method"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DecoderBlock:
"""class"""
def __init__(self, dm, h, hidden, rate=0.1):
"""constructor"""
super(DecoderBlock, self).__init__()
self.mha1 = MultiHeadAttention(dm, h)
self.mha2 = MultiHeadAttention(dm, h)
self.dense_hidden = tf.keras.layers.Dense(hidden, activation='r... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/8-transformer_decoder_block.py | jadsm98/holbertonschool-machine_learning | train | 0 |
33dcf02c9328892eadce8788ca72af83e1b42e0b | [
"config = registry.get_plugin('samplelocate').plugin_config()\nconfig.active = True\nconfig.save()\nurl = reverse('api-locate-plugin')\nself.post(url, {}, expected_code=400)\nself.post(url, {'plugin': 'sampleevent'}, expected_code=400)\nself.post(url, {'plugin': 'samplelocate'}, expected_code=400)\nself.post(url, {... | <|body_start_0|>
config = registry.get_plugin('samplelocate').plugin_config()
config.active = True
config.save()
url = reverse('api-locate-plugin')
self.post(url, {}, expected_code=400)
self.post(url, {'plugin': 'sampleevent'}, expected_code=400)
self.post(url, {'... | Tests for SampleLocatePlugin. | SampleLocatePlugintests | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SampleLocatePlugintests:
"""Tests for SampleLocatePlugin."""
def test_run_locator(self):
"""Check if the event is issued."""
<|body_0|>
def test_mixin(self):
"""Test that MixinNotImplementedError is raised."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_000337 | 1,980 | permissive | [
{
"docstring": "Check if the event is issued.",
"name": "test_run_locator",
"signature": "def test_run_locator(self)"
},
{
"docstring": "Test that MixinNotImplementedError is raised.",
"name": "test_mixin",
"signature": "def test_mixin(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009377 | Implement the Python class `SampleLocatePlugintests` described below.
Class description:
Tests for SampleLocatePlugin.
Method signatures and docstrings:
- def test_run_locator(self): Check if the event is issued.
- def test_mixin(self): Test that MixinNotImplementedError is raised. | Implement the Python class `SampleLocatePlugintests` described below.
Class description:
Tests for SampleLocatePlugin.
Method signatures and docstrings:
- def test_run_locator(self): Check if the event is issued.
- def test_mixin(self): Test that MixinNotImplementedError is raised.
<|skeleton|>
class SampleLocatePlu... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class SampleLocatePlugintests:
"""Tests for SampleLocatePlugin."""
def test_run_locator(self):
"""Check if the event is issued."""
<|body_0|>
def test_mixin(self):
"""Test that MixinNotImplementedError is raised."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SampleLocatePlugintests:
"""Tests for SampleLocatePlugin."""
def test_run_locator(self):
"""Check if the event is issued."""
config = registry.get_plugin('samplelocate').plugin_config()
config.active = True
config.save()
url = reverse('api-locate-plugin')
s... | the_stack_v2_python_sparse | InvenTree/plugin/samples/locate/test_locate_sample.py | inventree/InvenTree | train | 3,077 |
e3a5984bb6451bc1244bbc0d64126ff974b7d52e | [
"parser = argparse.ArgumentParser()\nself.args = parser.parse_known_args()\nfor i in range(0, len(self.args[1])):\n curr_item = self.args[1][i]\n if i != len(self.args[1]) - 1:\n next_item = self.args[1][i + 1]\n else:\n next_item = '1'\n if '--' in curr_item and '--' in next_item:\n ... | <|body_start_0|>
parser = argparse.ArgumentParser()
self.args = parser.parse_known_args()
for i in range(0, len(self.args[1])):
curr_item = self.args[1][i]
if i != len(self.args[1]) - 1:
next_item = self.args[1][i + 1]
else:
nex... | OpenPoseProcessor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenPoseProcessor:
def __init__(self):
"""Initializes flags and starts OpenPose Wrapper"""
<|body_0|>
def run_openpose(self, imagepath, outputDirPath):
"""Runs OpenPose on an image given imagepath @params: imagepath = image path of file to be processed @params: outpu... | stack_v2_sparse_classes_36k_train_000338 | 5,558 | no_license | [
{
"docstring": "Initializes flags and starts OpenPose Wrapper",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Runs OpenPose on an image given imagepath @params: imagepath = image path of file to be processed @params: outputDirPath = directory of output file's keypoints... | 2 | stack_v2_sparse_classes_30k_train_004589 | Implement the Python class `OpenPoseProcessor` described below.
Class description:
Implement the OpenPoseProcessor class.
Method signatures and docstrings:
- def __init__(self): Initializes flags and starts OpenPose Wrapper
- def run_openpose(self, imagepath, outputDirPath): Runs OpenPose on an image given imagepath ... | Implement the Python class `OpenPoseProcessor` described below.
Class description:
Implement the OpenPoseProcessor class.
Method signatures and docstrings:
- def __init__(self): Initializes flags and starts OpenPose Wrapper
- def run_openpose(self, imagepath, outputDirPath): Runs OpenPose on an image given imagepath ... | 54705e428d67950d4d5d7cee947530bf8852e3f2 | <|skeleton|>
class OpenPoseProcessor:
def __init__(self):
"""Initializes flags and starts OpenPose Wrapper"""
<|body_0|>
def run_openpose(self, imagepath, outputDirPath):
"""Runs OpenPose on an image given imagepath @params: imagepath = image path of file to be processed @params: outpu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OpenPoseProcessor:
def __init__(self):
"""Initializes flags and starts OpenPose Wrapper"""
parser = argparse.ArgumentParser()
self.args = parser.parse_known_args()
for i in range(0, len(self.args[1])):
curr_item = self.args[1][i]
if i != len(self.args[1]... | the_stack_v2_python_sparse | src/training/preprocessing.py | relientm96/capstone2020 | train | 0 | |
09255e18225097649c1c6cb6800f9d04e0940eb5 | [
"super().__init__(CallbackOrder.External)\nself.trial = trial\nself.loader_key = loader_key\nself.metric_key = metric_key\nself.minimize = minimize\nself.is_better = MetricHandler(minimize=minimize, min_delta=min_delta)\nself.best_score = None",
"score = runner.epoch_metrics[self.loader_key][self.metric_key]\nif ... | <|body_start_0|>
super().__init__(CallbackOrder.External)
self.trial = trial
self.loader_key = loader_key
self.metric_key = metric_key
self.minimize = minimize
self.is_better = MetricHandler(minimize=minimize, min_delta=min_delta)
self.best_score = None
<|end_body... | Optuna callback for pruning unpromising runs. This callback can be used for early stopping (pruning) unpromising runs. Args: trial: Optuna.Trial for the experiment. loader_key: loader key for best model selection (based on metric score over the dataset) metric_key: metric key for best model selection (based on metric s... | OptunaPruningCallback | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptunaPruningCallback:
"""Optuna callback for pruning unpromising runs. This callback can be used for early stopping (pruning) unpromising runs. Args: trial: Optuna.Trial for the experiment. loader_key: loader key for best model selection (based on metric score over the dataset) metric_key: metri... | stack_v2_sparse_classes_36k_train_000339 | 3,003 | permissive | [
{
"docstring": "Init.",
"name": "__init__",
"signature": "def __init__(self, trial: 'optuna.Trial', loader_key: str, metric_key: str, minimize: bool, min_delta: float=1e-06)"
},
{
"docstring": "Considering prune or not to prune current run at the end of the epoch. Args: runner: runner for curren... | 2 | stack_v2_sparse_classes_30k_train_012488 | Implement the Python class `OptunaPruningCallback` described below.
Class description:
Optuna callback for pruning unpromising runs. This callback can be used for early stopping (pruning) unpromising runs. Args: trial: Optuna.Trial for the experiment. loader_key: loader key for best model selection (based on metric sc... | Implement the Python class `OptunaPruningCallback` described below.
Class description:
Optuna callback for pruning unpromising runs. This callback can be used for early stopping (pruning) unpromising runs. Args: trial: Optuna.Trial for the experiment. loader_key: loader key for best model selection (based on metric sc... | e99f90655d0efcf22559a46e928f0f98c9807ebf | <|skeleton|>
class OptunaPruningCallback:
"""Optuna callback for pruning unpromising runs. This callback can be used for early stopping (pruning) unpromising runs. Args: trial: Optuna.Trial for the experiment. loader_key: loader key for best model selection (based on metric score over the dataset) metric_key: metri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OptunaPruningCallback:
"""Optuna callback for pruning unpromising runs. This callback can be used for early stopping (pruning) unpromising runs. Args: trial: Optuna.Trial for the experiment. loader_key: loader key for best model selection (based on metric score over the dataset) metric_key: metric key for bes... | the_stack_v2_python_sparse | catalyst/callbacks/optuna.py | catalyst-team/catalyst | train | 3,038 |
9d0f0e7feb2aa7cf74f8c40c6c14b40378bf4e1f | [
"self.contents = None\nself.identifier = ''\nself.path = ''\nself.rootObject = None\nself.objects = set()\nif xcproj_path.endswith('.xcodeproj') or xcproj_path.endswith('.pbproj'):\n self.path = path_helper(xcproj_path, 'project.pbxproj')\n self.contents = plist_helper.LoadPlistFromDataAtPath(self.path.root_p... | <|body_start_0|>
self.contents = None
self.identifier = ''
self.path = ''
self.rootObject = None
self.objects = set()
if xcproj_path.endswith('.xcodeproj') or xcproj_path.endswith('.pbproj'):
self.path = path_helper(xcproj_path, 'project.pbxproj')
... | xcodeproj | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class xcodeproj:
def __init__(self, xcproj_path):
"""Pass the path to the '.xcodeproj' file to initialize the xcodeproj object."""
<|body_0|>
def objectForIdentifier(self, identifier):
"""Returns the parsed object from the project file for matching identifier, if no matchi... | stack_v2_sparse_classes_36k_train_000340 | 3,656 | permissive | [
{
"docstring": "Pass the path to the '.xcodeproj' file to initialize the xcodeproj object.",
"name": "__init__",
"signature": "def __init__(self, xcproj_path)"
},
{
"docstring": "Returns the parsed object from the project file for matching identifier, if no matching object is found it will retur... | 5 | stack_v2_sparse_classes_30k_train_013275 | Implement the Python class `xcodeproj` described below.
Class description:
Implement the xcodeproj class.
Method signatures and docstrings:
- def __init__(self, xcproj_path): Pass the path to the '.xcodeproj' file to initialize the xcodeproj object.
- def objectForIdentifier(self, identifier): Returns the parsed obje... | Implement the Python class `xcodeproj` described below.
Class description:
Implement the xcodeproj class.
Method signatures and docstrings:
- def __init__(self, xcproj_path): Pass the path to the '.xcodeproj' file to initialize the xcodeproj object.
- def objectForIdentifier(self, identifier): Returns the parsed obje... | 4f78af149127325e60e3785b6e09d6dbfeedc799 | <|skeleton|>
class xcodeproj:
def __init__(self, xcproj_path):
"""Pass the path to the '.xcodeproj' file to initialize the xcodeproj object."""
<|body_0|>
def objectForIdentifier(self, identifier):
"""Returns the parsed object from the project file for matching identifier, if no matchi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class xcodeproj:
def __init__(self, xcproj_path):
"""Pass the path to the '.xcodeproj' file to initialize the xcodeproj object."""
self.contents = None
self.identifier = ''
self.path = ''
self.rootObject = None
self.objects = set()
if xcproj_path.endswith('.xc... | the_stack_v2_python_sparse | xcparse/Xcode/xcodeproj.py | samdmarshall/xcparse | train | 60 | |
1877e23eff9562fe06931f621dc42a2468fc9911 | [
"text = actions.edit.selected_text()\nnew_lines = []\nfor line in text.split('\\n'):\n one_line_if_match = re.match('(\\\\s*)(.+?):\\\\s*((.+)=(.+))$', line)\n if one_line_if_match:\n ws, if_statement, assignment, *_ = one_line_if_match.groups()\n new_lines.append(f'{ws}{if_statement}')\n ... | <|body_start_0|>
text = actions.edit.selected_text()
new_lines = []
for line in text.split('\n'):
one_line_if_match = re.match('(\\s*)(.+?):\\s*((.+)=(.+))$', line)
if one_line_if_match:
ws, if_statement, assignment, *_ = one_line_if_match.groups()
... | Actions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Actions:
def print_all_assignments():
"""Adds a print statement below each assignment in a selected block of python code."""
<|body_0|>
def print_arguments():
"""Adds a print statement below a selected function declaration containing its arguments."""
<|body_... | stack_v2_sparse_classes_36k_train_000341 | 12,812 | no_license | [
{
"docstring": "Adds a print statement below each assignment in a selected block of python code.",
"name": "print_all_assignments",
"signature": "def print_all_assignments()"
},
{
"docstring": "Adds a print statement below a selected function declaration containing its arguments.",
"name": "... | 3 | stack_v2_sparse_classes_30k_train_008161 | Implement the Python class `Actions` described below.
Class description:
Implement the Actions class.
Method signatures and docstrings:
- def print_all_assignments(): Adds a print statement below each assignment in a selected block of python code.
- def print_arguments(): Adds a print statement below a selected funct... | Implement the Python class `Actions` described below.
Class description:
Implement the Actions class.
Method signatures and docstrings:
- def print_all_assignments(): Adds a print statement below each assignment in a selected block of python code.
- def print_arguments(): Adds a print statement below a selected funct... | 03c6479989ab4231d8ae6bbab24ac8b57c3ef809 | <|skeleton|>
class Actions:
def print_all_assignments():
"""Adds a print statement below each assignment in a selected block of python code."""
<|body_0|>
def print_arguments():
"""Adds a print statement below a selected function declaration containing its arguments."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Actions:
def print_all_assignments():
"""Adds a print statement below each assignment in a selected block of python code."""
text = actions.edit.selected_text()
new_lines = []
for line in text.split('\n'):
one_line_if_match = re.match('(\\s*)(.+?):\\s*((.+)=(.+))$',... | the_stack_v2_python_sparse | lang/python/python.py | mrob95/MR-talon | train | 15 | |
d5c7ba8da110fd4c5fa2d11e847f90e97eeb12cf | [
"graph = defaultdict(list)\nfor a, b in prerequisites:\n graph[a].append(b)\nprocessed = set()\nworking_set = set()\n\ndef dfs(n):\n \"\"\"Use DFS to traverse the graph, starting from Node n.\"\"\"\n if n in processed:\n return True\n if n in working_set:\n return False\n working_set.ad... | <|body_start_0|>
graph = defaultdict(list)
for a, b in prerequisites:
graph[a].append(b)
processed = set()
working_set = set()
def dfs(n):
"""Use DFS to traverse the graph, starting from Node n."""
if n in processed:
return Tru... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canFinish_v1(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
"""DFS with two sets. This method primarily searches for loops. - First, build a graph based on prequisites. - Given any course number n, traverse the graph use DFS. - Yet, use a working set to tra... | stack_v2_sparse_classes_36k_train_000342 | 4,834 | no_license | [
{
"docstring": "DFS with two sets. This method primarily searches for loops. - First, build a graph based on prequisites. - Given any course number n, traverse the graph use DFS. - Yet, use a working set to track all of the nodes are being process. - If DFS hits any of node in the working set, it is a loop.",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canFinish_v1(self, numCourses: int, prerequisites: List[List[int]]) -> bool: DFS with two sets. This method primarily searches for loops. - First, build a graph based on preq... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canFinish_v1(self, numCourses: int, prerequisites: List[List[int]]) -> bool: DFS with two sets. This method primarily searches for loops. - First, build a graph based on preq... | 97a2386f5e3adbd7138fd123810c3232bdf7f622 | <|skeleton|>
class Solution:
def canFinish_v1(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
"""DFS with two sets. This method primarily searches for loops. - First, build a graph based on prequisites. - Given any course number n, traverse the graph use DFS. - Yet, use a working set to tra... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canFinish_v1(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
"""DFS with two sets. This method primarily searches for loops. - First, build a graph based on prequisites. - Given any course number n, traverse the graph use DFS. - Yet, use a working set to track all of the ... | the_stack_v2_python_sparse | python3/trees_and_graphs/course_schedule.py | victorchu/algorithms | train | 0 | |
7f5bab36ccb1a90ec47904eef28bfdb806b4dadf | [
"get_appid_url = 'http://pms.elenet.me/pmo.api/module/syncall'\nresponse_obj = requests.get(get_appid_url, timeout=3)\nif response_obj.status_code == 200:\n appid_data = response_obj.json().get('resultMsg', [])\nelse:\n appid_data = []\nif not appid_data:\n return HttpResponseServerError('从PMS: \"http://pm... | <|body_start_0|>
get_appid_url = 'http://pms.elenet.me/pmo.api/module/syncall'
response_obj = requests.get(get_appid_url, timeout=3)
if response_obj.status_code == 200:
appid_data = response_obj.json().get('resultMsg', [])
else:
appid_data = []
if not appi... | 从'http://pms.elenet.me/pmo.api/module/syncall'获取所有APPID信息,并一次性更新至DB中 | AppIdInfoUpdateAPIView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AppIdInfoUpdateAPIView:
"""从'http://pms.elenet.me/pmo.api/module/syncall'获取所有APPID信息,并一次性更新至DB中"""
def get_appid_info_from_pms():
"""从pms系统中获取APPID信息 :return:"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""写入db,并响应用户 :param request: :param format: :re... | stack_v2_sparse_classes_36k_train_000343 | 7,513 | permissive | [
{
"docstring": "从pms系统中获取APPID信息 :return:",
"name": "get_appid_info_from_pms",
"signature": "def get_appid_info_from_pms()"
},
{
"docstring": "写入db,并响应用户 :param request: :param format: :return:",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014539 | Implement the Python class `AppIdInfoUpdateAPIView` described below.
Class description:
从'http://pms.elenet.me/pmo.api/module/syncall'获取所有APPID信息,并一次性更新至DB中
Method signatures and docstrings:
- def get_appid_info_from_pms(): 从pms系统中获取APPID信息 :return:
- def post(self, request, *args, **kwargs): 写入db,并响应用户 :param reques... | Implement the Python class `AppIdInfoUpdateAPIView` described below.
Class description:
从'http://pms.elenet.me/pmo.api/module/syncall'获取所有APPID信息,并一次性更新至DB中
Method signatures and docstrings:
- def get_appid_info_from_pms(): 从pms系统中获取APPID信息 :return:
- def post(self, request, *args, **kwargs): 写入db,并响应用户 :param reques... | 9a681b38ec552d5d2f5fc129bb7f2551c00424d8 | <|skeleton|>
class AppIdInfoUpdateAPIView:
"""从'http://pms.elenet.me/pmo.api/module/syncall'获取所有APPID信息,并一次性更新至DB中"""
def get_appid_info_from_pms():
"""从pms系统中获取APPID信息 :return:"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""写入db,并响应用户 :param request: :param format: :re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AppIdInfoUpdateAPIView:
"""从'http://pms.elenet.me/pmo.api/module/syncall'获取所有APPID信息,并一次性更新至DB中"""
def get_appid_info_from_pms():
"""从pms系统中获取APPID信息 :return:"""
get_appid_url = 'http://pms.elenet.me/pmo.api/module/syncall'
response_obj = requests.get(get_appid_url, timeout=3)
... | the_stack_v2_python_sparse | omni/apps/arch/views/product.py | cathywife/omni | train | 0 |
15134f02b3556dbd2a9e00e668d640d8b9a9f1bd | [
"self.sensor = sensor\nself.pump = pump\nself.decider = decider\nself.liquid_level = int()\nself.pump_status = int()\nself.control_decision = int()\nself.actions = {'PUMP_IN': pump.PUMP_IN, 'PUMP_OUT': pump.PUMP_OUT, 'PUMP_OFF': pump.PUMP_OFF}",
"self.liquid_level = self.sensor.measure()\nlogging.debug('In Contro... | <|body_start_0|>
self.sensor = sensor
self.pump = pump
self.decider = decider
self.liquid_level = int()
self.pump_status = int()
self.control_decision = int()
self.actions = {'PUMP_IN': pump.PUMP_IN, 'PUMP_OUT': pump.PUMP_OUT, 'PUMP_OFF': pump.PUMP_OFF}
<|end_body... | Encapsulates command and coordination for the water-regulation module | Controller | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Controller:
"""Encapsulates command and coordination for the water-regulation module"""
def __init__(self, sensor, pump, decider):
"""Create a new controller :param sensor: Typically an instance of sensor.Sensor :param pump: Typically an instance of pump.Pump :param decider: Typicall... | stack_v2_sparse_classes_36k_train_000344 | 2,605 | no_license | [
{
"docstring": "Create a new controller :param sensor: Typically an instance of sensor.Sensor :param pump: Typically an instance of pump.Pump :param decider: Typically an instance of decider.Decider",
"name": "__init__",
"signature": "def __init__(self, sensor, pump, decider)"
},
{
"docstring": ... | 2 | stack_v2_sparse_classes_30k_train_016389 | Implement the Python class `Controller` described below.
Class description:
Encapsulates command and coordination for the water-regulation module
Method signatures and docstrings:
- def __init__(self, sensor, pump, decider): Create a new controller :param sensor: Typically an instance of sensor.Sensor :param pump: Ty... | Implement the Python class `Controller` described below.
Class description:
Encapsulates command and coordination for the water-regulation module
Method signatures and docstrings:
- def __init__(self, sensor, pump, decider): Create a new controller :param sensor: Typically an instance of sensor.Sensor :param pump: Ty... | b1fea0309b3495b3e1dc167d7029bc9e4b6f00f1 | <|skeleton|>
class Controller:
"""Encapsulates command and coordination for the water-regulation module"""
def __init__(self, sensor, pump, decider):
"""Create a new controller :param sensor: Typically an instance of sensor.Sensor :param pump: Typically an instance of pump.Pump :param decider: Typicall... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Controller:
"""Encapsulates command and coordination for the water-regulation module"""
def __init__(self, sensor, pump, decider):
"""Create a new controller :param sensor: Typically an instance of sensor.Sensor :param pump: Typically an instance of pump.Pump :param decider: Typically an instance... | the_stack_v2_python_sparse | students/srepking/lesson06/water-regulation/waterregulation/controller.py | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | train | 4 |
eddc8eb62a93f89b2879a81c80c054cfb626ec9a | [
"t = TableFu(self.csv_file)\nself.table.pop(0)\nself.assertEqual(t.table, self.table)",
"t = TableFu(self.table)\nself.table.pop(0)\nself.assertEqual(t.table, self.table)",
"t1 = TableFu(self.csv_file)\nt2 = TableFu(self.table)\nself.assertEqual(t1.table, t2.table)"
] | <|body_start_0|>
t = TableFu(self.csv_file)
self.table.pop(0)
self.assertEqual(t.table, self.table)
<|end_body_0|>
<|body_start_1|>
t = TableFu(self.table)
self.table.pop(0)
self.assertEqual(t.table, self.table)
<|end_body_1|>
<|body_start_2|>
t1 = TableFu(self.... | BigTableTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BigTableTest:
def test_table(self):
"""Create a table from an open CSV file"""
<|body_0|>
def test_table_from_list(self):
"""Create a table from a two-dimensional list"""
<|body_1|>
def test_table_two_ways(self):
"""Two ways to create the same ta... | stack_v2_sparse_classes_36k_train_000345 | 30,557 | no_license | [
{
"docstring": "Create a table from an open CSV file",
"name": "test_table",
"signature": "def test_table(self)"
},
{
"docstring": "Create a table from a two-dimensional list",
"name": "test_table_from_list",
"signature": "def test_table_from_list(self)"
},
{
"docstring": "Two wa... | 3 | null | Implement the Python class `BigTableTest` described below.
Class description:
Implement the BigTableTest class.
Method signatures and docstrings:
- def test_table(self): Create a table from an open CSV file
- def test_table_from_list(self): Create a table from a two-dimensional list
- def test_table_two_ways(self): T... | Implement the Python class `BigTableTest` described below.
Class description:
Implement the BigTableTest class.
Method signatures and docstrings:
- def test_table(self): Create a table from an open CSV file
- def test_table_from_list(self): Create a table from a two-dimensional list
- def test_table_two_ways(self): T... | 0ac6653219c2701c13c508c5c4fc9bc3437eea06 | <|skeleton|>
class BigTableTest:
def test_table(self):
"""Create a table from an open CSV file"""
<|body_0|>
def test_table_from_list(self):
"""Create a table from a two-dimensional list"""
<|body_1|>
def test_table_two_ways(self):
"""Two ways to create the same ta... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BigTableTest:
def test_table(self):
"""Create a table from an open CSV file"""
t = TableFu(self.csv_file)
self.table.pop(0)
self.assertEqual(t.table, self.table)
def test_table_from_list(self):
"""Create a table from a two-dimensional list"""
t = TableFu(se... | the_stack_v2_python_sparse | repoData/eyeseast-python-tablefu/allPythonContent.py | aCoffeeYin/pyreco | train | 0 | |
52702024972f5e1d516e6180a7277d411697c342 | [
"try:\n account_id = lookup_account_id(request.headers['username'])\nexcept Exception:\n return make_response(jsonify({'Error': 'Invalid username or account'}), client.BAD_REQUEST)\nreturn paginate(request, DEFAULT_SUBSCRIPTIONS_TABLE, 'subscriptions', filters={'account_id': account_id})",
"registration_id ... | <|body_start_0|>
try:
account_id = lookup_account_id(request.headers['username'])
except Exception:
return make_response(jsonify({'Error': 'Invalid username or account'}), client.BAD_REQUEST)
return paginate(request, DEFAULT_SUBSCRIPTIONS_TABLE, 'subscriptions', filters={... | Handles the (webhook) subscriptions table interactions | Subscription | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Subscription:
"""Handles the (webhook) subscriptions table interactions"""
def get(self):
"""Get the user's webhook subscriptions"""
<|body_0|>
def post(self, subscription_id):
"""Creates new subscription"""
<|body_1|>
def delete(self, subscription_i... | stack_v2_sparse_classes_36k_train_000346 | 2,486 | permissive | [
{
"docstring": "Get the user's webhook subscriptions",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Creates new subscription",
"name": "post",
"signature": "def post(self, subscription_id)"
},
{
"docstring": "Deletes subscription record",
"name": "delete",
... | 3 | stack_v2_sparse_classes_30k_train_020881 | Implement the Python class `Subscription` described below.
Class description:
Handles the (webhook) subscriptions table interactions
Method signatures and docstrings:
- def get(self): Get the user's webhook subscriptions
- def post(self, subscription_id): Creates new subscription
- def delete(self, subscription_id): ... | Implement the Python class `Subscription` described below.
Class description:
Handles the (webhook) subscriptions table interactions
Method signatures and docstrings:
- def get(self): Get the user's webhook subscriptions
- def post(self, subscription_id): Creates new subscription
- def delete(self, subscription_id): ... | 1f4dc112b3293f80a7a03b339ce9b5e87386a04c | <|skeleton|>
class Subscription:
"""Handles the (webhook) subscriptions table interactions"""
def get(self):
"""Get the user's webhook subscriptions"""
<|body_0|>
def post(self, subscription_id):
"""Creates new subscription"""
<|body_1|>
def delete(self, subscription_i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Subscription:
"""Handles the (webhook) subscriptions table interactions"""
def get(self):
"""Get the user's webhook subscriptions"""
try:
account_id = lookup_account_id(request.headers['username'])
except Exception:
return make_response(jsonify({'Error': 'I... | the_stack_v2_python_sparse | pywebhooks/api/resources/v1/webhook/subscription.py | amitsaha/pywebhooks | train | 1 |
4b4a5d4e31953559c76fde6594e08e4d18842548 | [
"try:\n return self.schema[action]\nexcept KeyError:\n msg = _('{0} is not a valid action').format(action)\n raise errors.InvalidAction(msg)",
"if action not in self.validators:\n schema = self.get_schema(action)\n self.validators[action] = validators.Draft4Validator(schema)\ntry:\n self.validat... | <|body_start_0|>
try:
return self.schema[action]
except KeyError:
msg = _('{0} is not a valid action').format(action)
raise errors.InvalidAction(msg)
<|end_body_0|>
<|body_start_1|>
if action not in self.validators:
schema = self.get_schema(action... | Api | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Api:
def get_schema(self, action):
"""Returns the schema for an action :param action: Action for which params need to be validated. :type action: `str` :returns: Action's schema :rtype: dict :raises InvalidAction: if the action does not exist"""
<|body_0|>
def validate(self,... | stack_v2_sparse_classes_36k_train_000347 | 2,316 | permissive | [
{
"docstring": "Returns the schema for an action :param action: Action for which params need to be validated. :type action: `str` :returns: Action's schema :rtype: dict :raises InvalidAction: if the action does not exist",
"name": "get_schema",
"signature": "def get_schema(self, action)"
},
{
"d... | 2 | null | Implement the Python class `Api` described below.
Class description:
Implement the Api class.
Method signatures and docstrings:
- def get_schema(self, action): Returns the schema for an action :param action: Action for which params need to be validated. :type action: `str` :returns: Action's schema :rtype: dict :rais... | Implement the Python class `Api` described below.
Class description:
Implement the Api class.
Method signatures and docstrings:
- def get_schema(self, action): Returns the schema for an action :param action: Action for which params need to be validated. :type action: `str` :returns: Action's schema :rtype: dict :rais... | 169d917c3e3eaec54eeeb72859df6e4c64ef00da | <|skeleton|>
class Api:
def get_schema(self, action):
"""Returns the schema for an action :param action: Action for which params need to be validated. :type action: `str` :returns: Action's schema :rtype: dict :raises InvalidAction: if the action does not exist"""
<|body_0|>
def validate(self,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Api:
def get_schema(self, action):
"""Returns the schema for an action :param action: Action for which params need to be validated. :type action: `str` :returns: Action's schema :rtype: dict :raises InvalidAction: if the action does not exist"""
try:
return self.schema[action]
... | the_stack_v2_python_sparse | zaqar/common/api/api.py | openstack/zaqar | train | 102 | |
f9a924f67766f960eaf6d9df3624728de0aacdbf | [
"index = 0\nfor a in arr:\n if a == None:\n index = index + 1\nreturn index",
"try:\n arr.sort(key=keyFunction)\nexcept:\n raise ValueError('keyFunction无法正常调用,请确保数组arr中的每个元素都能够执行keyFunction方法,并且不会报错。arr:' + str(arr))\nmid = None\nfor i in range(len(arr)):\n if mid != arr[i]:\n mid = arr[... | <|body_start_0|>
index = 0
for a in arr:
if a == None:
index = index + 1
return index
<|end_body_0|>
<|body_start_1|>
try:
arr.sort(key=keyFunction)
except:
raise ValueError('keyFunction无法正常调用,请确保数组arr中的每个元素都能够执行keyFunction方法,并... | ArrTool | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArrTool:
def getNoneLen(arr):
"""获得一个数组中None的个数"""
<|body_0|>
def removeRepeat(arr, keyFunction=''):
"""去除掉[]中相同的元素,根据方法keyFunction。 e.g.:a=[{'name':1},{'name':3},{'name':2},{'name':1},{'name':1}] 假设要去除name为1的元素 c=removeRepeat(a,keyFunction=lambda x:x['name']) print(... | stack_v2_sparse_classes_36k_train_000348 | 10,029 | no_license | [
{
"docstring": "获得一个数组中None的个数",
"name": "getNoneLen",
"signature": "def getNoneLen(arr)"
},
{
"docstring": "去除掉[]中相同的元素,根据方法keyFunction。 e.g.:a=[{'name':1},{'name':3},{'name':2},{'name':1},{'name':1}] 假设要去除name为1的元素 c=removeRepeat(a,keyFunction=lambda x:x['name']) print(c) =>[{'name': 1}, {'nam... | 2 | null | Implement the Python class `ArrTool` described below.
Class description:
Implement the ArrTool class.
Method signatures and docstrings:
- def getNoneLen(arr): 获得一个数组中None的个数
- def removeRepeat(arr, keyFunction=''): 去除掉[]中相同的元素,根据方法keyFunction。 e.g.:a=[{'name':1},{'name':3},{'name':2},{'name':1},{'name':1}] 假设要去除name为... | Implement the Python class `ArrTool` described below.
Class description:
Implement the ArrTool class.
Method signatures and docstrings:
- def getNoneLen(arr): 获得一个数组中None的个数
- def removeRepeat(arr, keyFunction=''): 去除掉[]中相同的元素,根据方法keyFunction。 e.g.:a=[{'name':1},{'name':3},{'name':2},{'name':1},{'name':1}] 假设要去除name为... | 5eda21e66f65dd6f7f79e56441073bdcb7f18bdf | <|skeleton|>
class ArrTool:
def getNoneLen(arr):
"""获得一个数组中None的个数"""
<|body_0|>
def removeRepeat(arr, keyFunction=''):
"""去除掉[]中相同的元素,根据方法keyFunction。 e.g.:a=[{'name':1},{'name':3},{'name':2},{'name':1},{'name':1}] 假设要去除name为1的元素 c=removeRepeat(a,keyFunction=lambda x:x['name']) print(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArrTool:
def getNoneLen(arr):
"""获得一个数组中None的个数"""
index = 0
for a in arr:
if a == None:
index = index + 1
return index
def removeRepeat(arr, keyFunction=''):
"""去除掉[]中相同的元素,根据方法keyFunction。 e.g.:a=[{'name':1},{'name':3},{'name':2},{'nam... | the_stack_v2_python_sparse | _xhr_tool/_utils/RR_Comments.py | jhfwb/Web-spiders | train | 0 | |
6dbbb0165a3e7b4a8f5c1900e13b0dda93327c4f | [
"super(Shrink_RDB, self).__init__()\nself.InChan = InChannel\nself.OutChan = OutChannel\nself.G = growRate\nself.C = nConvLayers\nif self.InChan != self.G:\n self.InConv = ops.Conv2d(self.InChan, self.G, 1, padding=0, stride=1)\nif self.OutChan != self.G and self.OutChan != self.InChan:\n self.OutConv = ops.C... | <|body_start_0|>
super(Shrink_RDB, self).__init__()
self.InChan = InChannel
self.OutChan = OutChannel
self.G = growRate
self.C = nConvLayers
if self.InChan != self.G:
self.InConv = ops.Conv2d(self.InChan, self.G, 1, padding=0, stride=1)
if self.OutChan... | Shrink residual dense block. | Shrink_RDB | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Shrink_RDB:
"""Shrink residual dense block."""
def __init__(self, InChannel, OutChannel, growRate, nConvLayers, kSize=3):
"""Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: channel number of output :type OutChannel: int :param growR... | stack_v2_sparse_classes_36k_train_000349 | 14,306 | permissive | [
{
"docstring": "Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: channel number of output :type OutChannel: int :param growRate: growth rate of block :type growRate: int :param nConvLayers: the number of convlution layer :type nConvLayers: int :param kSize: ker... | 2 | null | Implement the Python class `Shrink_RDB` described below.
Class description:
Shrink residual dense block.
Method signatures and docstrings:
- def __init__(self, InChannel, OutChannel, growRate, nConvLayers, kSize=3): Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: ch... | Implement the Python class `Shrink_RDB` described below.
Class description:
Shrink residual dense block.
Method signatures and docstrings:
- def __init__(self, InChannel, OutChannel, growRate, nConvLayers, kSize=3): Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: ch... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class Shrink_RDB:
"""Shrink residual dense block."""
def __init__(self, InChannel, OutChannel, growRate, nConvLayers, kSize=3):
"""Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: channel number of output :type OutChannel: int :param growR... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Shrink_RDB:
"""Shrink residual dense block."""
def __init__(self, InChannel, OutChannel, growRate, nConvLayers, kSize=3):
"""Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: channel number of output :type OutChannel: int :param growRate: growth r... | the_stack_v2_python_sparse | zeus/networks/erdb_esr.py | huawei-noah/xingtian | train | 308 |
6ced01b005d905c3a622fc55d1629cf98e835c1c | [
"super(UnifiedFusion, self).__init__(name=name)\nself._unified_backbone = unified_backbone\nself._unified_model_kwargs = unified_model_kwargs or {}\nself.unified_backbone = uvatt_factory.build_model(backbone=self._unified_backbone, override_params=self._unified_model_kwargs)",
"txt_attn_mask = tf.where(word_ids =... | <|body_start_0|>
super(UnifiedFusion, self).__init__(name=name)
self._unified_backbone = unified_backbone
self._unified_model_kwargs = unified_model_kwargs or {}
self.unified_backbone = uvatt_factory.build_model(backbone=self._unified_backbone, override_params=self._unified_model_kwargs)... | Module to fuse audio, text and video for joint embedding learning. | UnifiedFusion | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnifiedFusion:
"""Module to fuse audio, text and video for joint embedding learning."""
def __init__(self, unified_backbone='uvatt', unified_model_kwargs=None, name='unified_fusion_model', **kwargs):
"""Initialize the UnifiedFusion class. Args: unified_backbone: The unified shared ba... | stack_v2_sparse_classes_36k_train_000350 | 7,989 | permissive | [
{
"docstring": "Initialize the UnifiedFusion class. Args: unified_backbone: The unified shared backbone for all modalities. unified_model_kwargs: Other specific parameters to pass to the module. name: graph name. **kwargs: additional model args",
"name": "__init__",
"signature": "def __init__(self, unif... | 2 | stack_v2_sparse_classes_30k_train_003754 | Implement the Python class `UnifiedFusion` described below.
Class description:
Module to fuse audio, text and video for joint embedding learning.
Method signatures and docstrings:
- def __init__(self, unified_backbone='uvatt', unified_model_kwargs=None, name='unified_fusion_model', **kwargs): Initialize the UnifiedFu... | Implement the Python class `UnifiedFusion` described below.
Class description:
Module to fuse audio, text and video for joint embedding learning.
Method signatures and docstrings:
- def __init__(self, unified_backbone='uvatt', unified_model_kwargs=None, name='unified_fusion_model', **kwargs): Initialize the UnifiedFu... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class UnifiedFusion:
"""Module to fuse audio, text and video for joint embedding learning."""
def __init__(self, unified_backbone='uvatt', unified_model_kwargs=None, name='unified_fusion_model', **kwargs):
"""Initialize the UnifiedFusion class. Args: unified_backbone: The unified shared ba... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnifiedFusion:
"""Module to fuse audio, text and video for joint embedding learning."""
def __init__(self, unified_backbone='uvatt', unified_model_kwargs=None, name='unified_fusion_model', **kwargs):
"""Initialize the UnifiedFusion class. Args: unified_backbone: The unified shared backbone for al... | the_stack_v2_python_sparse | vatt/modeling/backbones/multimodal.py | Jimmy-INL/google-research | train | 1 |
dd7e00413d68a10694d6948d05a646c9fcb96217 | [
"pins = pins or PINS\nself.touch = []\nfor gpio in pins:\n self.touch.append(Button(gpio))",
"for item in self.touch:\n if item.is_pressed:\n return True\nreturn False"
] | <|body_start_0|>
pins = pins or PINS
self.touch = []
for gpio in pins:
self.touch.append(Button(gpio))
<|end_body_0|>
<|body_start_1|>
for item in self.touch:
if item.is_pressed:
return True
return False
<|end_body_1|>
| Sensor class | Sensor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sensor:
"""Sensor class"""
def __init__(self, pins=None):
"""Constructor"""
<|body_0|>
def check_sensor(self):
"""Check sensor state"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pins = pins or PINS
self.touch = []
for gpio in ... | stack_v2_sparse_classes_36k_train_000351 | 1,508 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, pins=None)"
},
{
"docstring": "Check sensor state",
"name": "check_sensor",
"signature": "def check_sensor(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004838 | Implement the Python class `Sensor` described below.
Class description:
Sensor class
Method signatures and docstrings:
- def __init__(self, pins=None): Constructor
- def check_sensor(self): Check sensor state | Implement the Python class `Sensor` described below.
Class description:
Sensor class
Method signatures and docstrings:
- def __init__(self, pins=None): Constructor
- def check_sensor(self): Check sensor state
<|skeleton|>
class Sensor:
"""Sensor class"""
def __init__(self, pins=None):
"""Constructor... | cfba2860145978904d1dd427f2326efeccfc561a | <|skeleton|>
class Sensor:
"""Sensor class"""
def __init__(self, pins=None):
"""Constructor"""
<|body_0|>
def check_sensor(self):
"""Check sensor state"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Sensor:
"""Sensor class"""
def __init__(self, pins=None):
"""Constructor"""
pins = pins or PINS
self.touch = []
for gpio in pins:
self.touch.append(Button(gpio))
def check_sensor(self):
"""Check sensor state"""
for item in self.touch:
... | the_stack_v2_python_sparse | chapter_12/avoidance.py | packtjaniceg/Raspberry-Pi-4-Cookbook-for-Python-Programmers-Fourth-Edition | train | 0 |
dfae1ba53cc9763a742dbc7d080bef8f08712b10 | [
"self._plugins = collections.defaultdict(dict)\nself.config = config\nself.args = args\nself._exports = collections.defaultdict(dict)\nself.load_exports(args=args)",
"header = 'glances_'\nfor item in input_plugins:\n plugin = __import__(header + item)\n logger.debug('Server uses {0} plugin'.format(item))\n ... | <|body_start_0|>
self._plugins = collections.defaultdict(dict)
self.config = config
self.args = args
self._exports = collections.defaultdict(dict)
self.load_exports(args=args)
<|end_body_0|>
<|body_start_1|>
header = 'glances_'
for item in input_plugins:
... | This class stores, updates and gives stats for the client. | GlancesStatsClient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GlancesStatsClient:
"""This class stores, updates and gives stats for the client."""
def __init__(self, config=None, args=None):
"""Init the GlancesStatsClient class."""
<|body_0|>
def set_plugins(self, input_plugins):
"""Set the plugin list according to the Glan... | stack_v2_sparse_classes_36k_train_000352 | 13,959 | no_license | [
{
"docstring": "Init the GlancesStatsClient class.",
"name": "__init__",
"signature": "def __init__(self, config=None, args=None)"
},
{
"docstring": "Set the plugin list according to the Glances server.",
"name": "set_plugins",
"signature": "def set_plugins(self, input_plugins)"
},
{... | 3 | stack_v2_sparse_classes_30k_train_002799 | Implement the Python class `GlancesStatsClient` described below.
Class description:
This class stores, updates and gives stats for the client.
Method signatures and docstrings:
- def __init__(self, config=None, args=None): Init the GlancesStatsClient class.
- def set_plugins(self, input_plugins): Set the plugin list ... | Implement the Python class `GlancesStatsClient` described below.
Class description:
This class stores, updates and gives stats for the client.
Method signatures and docstrings:
- def __init__(self, config=None, args=None): Init the GlancesStatsClient class.
- def set_plugins(self, input_plugins): Set the plugin list ... | e790277ecbdda638bd0d212460a15b601c0d47dc | <|skeleton|>
class GlancesStatsClient:
"""This class stores, updates and gives stats for the client."""
def __init__(self, config=None, args=None):
"""Init the GlancesStatsClient class."""
<|body_0|>
def set_plugins(self, input_plugins):
"""Set the plugin list according to the Glan... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GlancesStatsClient:
"""This class stores, updates and gives stats for the client."""
def __init__(self, config=None, args=None):
"""Init the GlancesStatsClient class."""
self._plugins = collections.defaultdict(dict)
self.config = config
self.args = args
self._expor... | the_stack_v2_python_sparse | usr/lib/python3/dist-packages/glances/core/glances_stats.py | kojitaniguchi/isucon-summer | train | 1 |
ba1f0541e8b46fef2bfd0db2d97427bd2af88ed2 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn EducationSchool()",
"from .administrative_unit import AdministrativeUnit\nfrom .education_class import EducationClass\nfrom .education_organization import EducationOrganization\nfrom .education_user import EducationUser\nfrom .identity... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return EducationSchool()
<|end_body_0|>
<|body_start_1|>
from .administrative_unit import AdministrativeUnit
from .education_class import EducationClass
from .education_organization imp... | EducationSchool | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EducationSchool:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationSchool:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Ret... | stack_v2_sparse_classes_36k_train_000353 | 6,021 | 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: EducationSchool",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_val... | 3 | stack_v2_sparse_classes_30k_test_000383 | Implement the Python class `EducationSchool` described below.
Class description:
Implement the EducationSchool class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationSchool: Creates a new instance of the appropriate class based on discriminator... | Implement the Python class `EducationSchool` described below.
Class description:
Implement the EducationSchool class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationSchool: Creates a new instance of the appropriate class based on discriminator... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class EducationSchool:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationSchool:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EducationSchool:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationSchool:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Educatio... | the_stack_v2_python_sparse | msgraph/generated/models/education_school.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
983453f4ebee550fab0407d9e29c13d5edae2a0b | [
"super().__init__()\nself.album_template_fields['atypes'] = self._atypes\nself.config.add({'types': [('ep', 'EP'), ('single', 'Single'), ('soundtrack', 'OST'), ('live', 'Live'), ('compilation', 'Anthology'), ('remix', 'Remix')], 'ignore_va': ['compilation'], 'bracket': '[]'})",
"types = self.config['types'].as_pa... | <|body_start_0|>
super().__init__()
self.album_template_fields['atypes'] = self._atypes
self.config.add({'types': [('ep', 'EP'), ('single', 'Single'), ('soundtrack', 'OST'), ('live', 'Live'), ('compilation', 'Anthology'), ('remix', 'Remix')], 'ignore_va': ['compilation'], 'bracket': '[]'})
<|end... | Adds an album template field for formatted album types. | AlbumTypesPlugin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlbumTypesPlugin:
"""Adds an album template field for formatted album types."""
def __init__(self):
"""Init AlbumTypesPlugin."""
<|body_0|>
def _atypes(self, item: Album):
"""Returns a formatted string based on album's types."""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k_train_000354 | 2,297 | permissive | [
{
"docstring": "Init AlbumTypesPlugin.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Returns a formatted string based on album's types.",
"name": "_atypes",
"signature": "def _atypes(self, item: Album)"
}
] | 2 | null | Implement the Python class `AlbumTypesPlugin` described below.
Class description:
Adds an album template field for formatted album types.
Method signatures and docstrings:
- def __init__(self): Init AlbumTypesPlugin.
- def _atypes(self, item: Album): Returns a formatted string based on album's types. | Implement the Python class `AlbumTypesPlugin` described below.
Class description:
Adds an album template field for formatted album types.
Method signatures and docstrings:
- def __init__(self): Init AlbumTypesPlugin.
- def _atypes(self, item: Album): Returns a formatted string based on album's types.
<|skeleton|>
cl... | 0e5ade4f711dbf563d35c290affb0254eee41235 | <|skeleton|>
class AlbumTypesPlugin:
"""Adds an album template field for formatted album types."""
def __init__(self):
"""Init AlbumTypesPlugin."""
<|body_0|>
def _atypes(self, item: Album):
"""Returns a formatted string based on album's types."""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlbumTypesPlugin:
"""Adds an album template field for formatted album types."""
def __init__(self):
"""Init AlbumTypesPlugin."""
super().__init__()
self.album_template_fields['atypes'] = self._atypes
self.config.add({'types': [('ep', 'EP'), ('single', 'Single'), ('soundtra... | the_stack_v2_python_sparse | beetsplug/albumtypes.py | beetbox/beets | train | 8,977 |
f0a40a3af71c3e62f9a5088173ba528cbd731aa4 | [
"self.hyperparams = hyperparams\nself.rng = np.random.RandomState(self.hyperparams['random_seed'])\nself.kappa_proximal = self.hyperparams['kappa']",
"if self.hyperparams['method'] == 'L-BFGS':\n eps = 1e-08\n bnds = [(eps, np.inf) for _ in parameter]\n bnds[-1] = (eps, None)\n optimized = sp.optimize... | <|body_start_0|>
self.hyperparams = hyperparams
self.rng = np.random.RandomState(self.hyperparams['random_seed'])
self.kappa_proximal = self.hyperparams['kappa']
<|end_body_0|>
<|body_start_1|>
if self.hyperparams['method'] == 'L-BFGS':
eps = 1e-08
bnds = [(eps, ... | Optimizer class for monitoring the training and experimenting differents methods | Optimizer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Optimizer:
"""Optimizer class for monitoring the training and experimenting differents methods"""
def __init__(self, hyperparams):
"""Initializes the class Attributes: hyperparams (dict): dictionary of hyperparams rng (np.random.RandomState): random seed state kappa_proximal (float):... | stack_v2_sparse_classes_36k_train_000355 | 5,529 | permissive | [
{
"docstring": "Initializes the class Attributes: hyperparams (dict): dictionary of hyperparams rng (np.random.RandomState): random seed state kappa_proximal (float): regularization parameter for proximal point subproblems",
"name": "__init__",
"signature": "def __init__(self, hyperparams)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_002454 | Implement the Python class `Optimizer` described below.
Class description:
Optimizer class for monitoring the training and experimenting differents methods
Method signatures and docstrings:
- def __init__(self, hyperparams): Initializes the class Attributes: hyperparams (dict): dictionary of hyperparams rng (np.rando... | Implement the Python class `Optimizer` described below.
Class description:
Optimizer class for monitoring the training and experimenting differents methods
Method signatures and docstrings:
- def __init__(self, hyperparams): Initializes the class Attributes: hyperparams (dict): dictionary of hyperparams rng (np.rando... | 105f10eaa1c08fb5441dc1dc8b036c7a9f42ed40 | <|skeleton|>
class Optimizer:
"""Optimizer class for monitoring the training and experimenting differents methods"""
def __init__(self, hyperparams):
"""Initializes the class Attributes: hyperparams (dict): dictionary of hyperparams rng (np.random.RandomState): random seed state kappa_proximal (float):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Optimizer:
"""Optimizer class for monitoring the training and experimenting differents methods"""
def __init__(self, hyperparams):
"""Initializes the class Attributes: hyperparams (dict): dictionary of hyperparams rng (np.random.RandomState): random seed state kappa_proximal (float): regularizati... | the_stack_v2_python_sparse | src/optimizer/optimizer.py | tuantx7110/optimization-continuous-action-crm | train | 0 |
f30002293ee00204ae238b21a688fe15c48ed755 | [
"try:\n num = float(data[0])\nexcept ValueError as verr:\n print(verr)\n num = -1.0\nif len(data) > 1:\n unit = data[1]\n metric += '_' + str(unit)\nreturn (metric, num)",
"line = line.split(':')\nmetric = line[0].strip()\ndata = line[1].strip()\nurl_pattern = re.compile(ALPHANUMERIC_URL_REGEX)\nif... | <|body_start_0|>
try:
num = float(data[0])
except ValueError as verr:
print(verr)
num = -1.0
if len(data) > 1:
unit = data[1]
metric += '_' + str(unit)
return (metric, num)
<|end_body_0|>
<|body_start_1|>
line = line.sp... | Example output: Running iteration 1 --- DONE WARNING: Got 12 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_1 Running iteration 2 --- DONE WARNING: Got 15 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_2 Running iteration 3 --- DONE WARNING: Got 39 HTTP codes differ... | DjangoWorkloadParser | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DjangoWorkloadParser:
"""Example output: Running iteration 1 --- DONE WARNING: Got 12 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_1 Running iteration 2 --- DONE WARNING: Got 15 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_2 Running iterat... | stack_v2_sparse_classes_36k_train_000356 | 4,783 | permissive | [
{
"docstring": "Helper method to handle errors when extracting metrics and values",
"name": "parse_dw_data",
"signature": "def parse_dw_data(self, data, metric)"
},
{
"docstring": "Helper method to parse django-workload output into key-value data structure",
"name": "parse_dw_key_val",
"... | 3 | stack_v2_sparse_classes_30k_train_013728 | Implement the Python class `DjangoWorkloadParser` described below.
Class description:
Example output: Running iteration 1 --- DONE WARNING: Got 12 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_1 Running iteration 2 --- DONE WARNING: Got 15 HTTP codes different than 200 Please see full Siege... | Implement the Python class `DjangoWorkloadParser` described below.
Class description:
Example output: Running iteration 1 --- DONE WARNING: Got 12 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_1 Running iteration 2 --- DONE WARNING: Got 15 HTTP codes different than 200 Please see full Siege... | 70bc9fcb8dcc02c4ee70675c965c746fad7e4165 | <|skeleton|>
class DjangoWorkloadParser:
"""Example output: Running iteration 1 --- DONE WARNING: Got 12 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_1 Running iteration 2 --- DONE WARNING: Got 15 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_2 Running iterat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DjangoWorkloadParser:
"""Example output: Running iteration 1 --- DONE WARNING: Got 12 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_1 Running iteration 2 --- DONE WARNING: Got 15 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_2 Running iteration 3 --- DON... | the_stack_v2_python_sparse | benchpress/benchpress/plugins/parsers/django_workload.py | meteorfox/fbkutils | train | 1 |
0d7435c9c3f78fea8212d02288beb662458c31ff | [
"badges = get_list_or_404(Badge)\nif request.GET.get('pagination'):\n pagination = request.GET.get('pagination')\n if pagination == 'true':\n paginator = AdministratorPagination()\n results = paginator.paginate_queryset(badges, request)\n serializer = BadgeSerializer(results, many=True)\n... | <|body_start_0|>
badges = get_list_or_404(Badge)
if request.GET.get('pagination'):
pagination = request.GET.get('pagination')
if pagination == 'true':
paginator = AdministratorPagination()
results = paginator.paginate_queryset(badges, request)
... | BadgeList | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BadgeList:
def get(self, request, format=None):
"""List all badges --- serializer: administrator.serializers.BadgeSerializer parameters: - name: pagination required: false type: string paramType: query"""
<|body_0|>
def post(self, request, format=None):
"""Create new... | stack_v2_sparse_classes_36k_train_000357 | 30,608 | permissive | [
{
"docstring": "List all badges --- serializer: administrator.serializers.BadgeSerializer parameters: - name: pagination required: false type: string paramType: query",
"name": "get",
"signature": "def get(self, request, format=None)"
},
{
"docstring": "Create new badge --- serializer: administr... | 2 | stack_v2_sparse_classes_30k_train_010826 | Implement the Python class `BadgeList` described below.
Class description:
Implement the BadgeList class.
Method signatures and docstrings:
- def get(self, request, format=None): List all badges --- serializer: administrator.serializers.BadgeSerializer parameters: - name: pagination required: false type: string param... | Implement the Python class `BadgeList` described below.
Class description:
Implement the BadgeList class.
Method signatures and docstrings:
- def get(self, request, format=None): List all badges --- serializer: administrator.serializers.BadgeSerializer parameters: - name: pagination required: false type: string param... | 73728463badb3bfd4413aa0f7aeb44a9606fdfea | <|skeleton|>
class BadgeList:
def get(self, request, format=None):
"""List all badges --- serializer: administrator.serializers.BadgeSerializer parameters: - name: pagination required: false type: string paramType: query"""
<|body_0|>
def post(self, request, format=None):
"""Create new... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BadgeList:
def get(self, request, format=None):
"""List all badges --- serializer: administrator.serializers.BadgeSerializer parameters: - name: pagination required: false type: string paramType: query"""
badges = get_list_or_404(Badge)
if request.GET.get('pagination'):
pag... | the_stack_v2_python_sparse | administrator/views.py | belatrix/BackendAllStars | train | 5 | |
3384ac5a849b087d65bfe50330c11081cfdba40c | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.educationSchool'.casefold():\n from .edu... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | EducationOrganization | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EducationOrganization:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationOrganization:
"""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 th... | stack_v2_sparse_classes_36k_train_000358 | 3,598 | 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: EducationOrganization",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminat... | 3 | stack_v2_sparse_classes_30k_train_001841 | Implement the Python class `EducationOrganization` described below.
Class description:
Implement the EducationOrganization class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationOrganization: Creates a new instance of the appropriate class base... | Implement the Python class `EducationOrganization` described below.
Class description:
Implement the EducationOrganization class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationOrganization: Creates a new instance of the appropriate class base... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class EducationOrganization:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationOrganization:
"""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 th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EducationOrganization:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationOrganization:
"""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 Retur... | the_stack_v2_python_sparse | msgraph/generated/models/education_organization.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
dc297c2479f93801a920f3453a00e7ee69a81b36 | [
"if 'register' in self.user.apps:\n return html.a('New User?', href='/register')\nreturn ''",
"if 'forgot' in self.user.apps:\n return load_content('views/forgot_password.pug')\nreturn ''",
"remember_me = zoom.system.site.config.get('site', 'remember_me', True)\nif remember_me in zoom.utils.POSITIVE:\n ... | <|body_start_0|>
if 'register' in self.user.apps:
return html.a('New User?', href='/register')
return ''
<|end_body_0|>
<|body_start_1|>
if 'forgot' in self.user.apps:
return load_content('views/forgot_password.pug')
return ''
<|end_body_1|>
<|body_start_2|>
... | LoginForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoginForm:
def registration_link(self):
"""returns registration link for new users"""
<|body_0|>
def forgot_password(self):
"""returns link to password recovery app"""
<|body_1|>
def remember_me_checkbox(self):
"""return Remember Me checkbox"""
... | stack_v2_sparse_classes_36k_train_000359 | 3,089 | permissive | [
{
"docstring": "returns registration link for new users",
"name": "registration_link",
"signature": "def registration_link(self)"
},
{
"docstring": "returns link to password recovery app",
"name": "forgot_password",
"signature": "def forgot_password(self)"
},
{
"docstring": "retu... | 3 | stack_v2_sparse_classes_30k_train_007685 | Implement the Python class `LoginForm` described below.
Class description:
Implement the LoginForm class.
Method signatures and docstrings:
- def registration_link(self): returns registration link for new users
- def forgot_password(self): returns link to password recovery app
- def remember_me_checkbox(self): return... | Implement the Python class `LoginForm` described below.
Class description:
Implement the LoginForm class.
Method signatures and docstrings:
- def registration_link(self): returns registration link for new users
- def forgot_password(self): returns link to password recovery app
- def remember_me_checkbox(self): return... | b34cb4b2ee7cc40b2c99015f05bfcc12d4b49065 | <|skeleton|>
class LoginForm:
def registration_link(self):
"""returns registration link for new users"""
<|body_0|>
def forgot_password(self):
"""returns link to password recovery app"""
<|body_1|>
def remember_me_checkbox(self):
"""return Remember Me checkbox"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoginForm:
def registration_link(self):
"""returns registration link for new users"""
if 'register' in self.user.apps:
return html.a('New User?', href='/register')
return ''
def forgot_password(self):
"""returns link to password recovery app"""
if 'forg... | the_stack_v2_python_sparse | zoom/_assets/standard_apps/login/index.py | dsilabs/zoom | train | 9 | |
3d298b52eda0cc5ae0f6f056f631ad9f50ae34c9 | [
"length = len(nums)\nn = 1\nwhile n < length:\n n *= 2\nself.n = n\nself.d = [0] * (2 * n - 1)\nfor i in range(length):\n self.update(i, nums[i])",
"p = i + self.n - 1\nself.d[p] = val\nwhile p > 0:\n p = (p - 1) // 2\n self.d[p] = self.d[2 * p + 1] + self.d[2 * p + 2]",
"if lo <= s and hi >= t:\n ... | <|body_start_0|>
length = len(nums)
n = 1
while n < length:
n *= 2
self.n = n
self.d = [0] * (2 * n - 1)
for i in range(length):
self.update(i, nums[i])
<|end_body_0|>
<|body_start_1|>
p = i + self.n - 1
self.d[p] = val
whi... | 求和线段树, 完美二叉树版本,即 叶子结点树木是满的 所有的nums的值都位于 叶子结点, 而且二叉树的每一层的节点个数都是偶数 | segmentTree | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class segmentTree:
"""求和线段树, 完美二叉树版本,即 叶子结点树木是满的 所有的nums的值都位于 叶子结点, 而且二叉树的每一层的节点个数都是偶数"""
def __init__(self, nums) -> None:
"""d: 线段树数组 0-based nums: 索引 0-based"""
<|body_0|>
def update(self, i, val):
"""i: 0-based p: 1-based 相当于数组 nums[i] = val 那么就需要修改二叉树关联所有值,类似于 堆中的... | stack_v2_sparse_classes_36k_train_000360 | 4,234 | permissive | [
{
"docstring": "d: 线段树数组 0-based nums: 索引 0-based",
"name": "__init__",
"signature": "def __init__(self, nums) -> None"
},
{
"docstring": "i: 0-based p: 1-based 相当于数组 nums[i] = val 那么就需要修改二叉树关联所有值,类似于 堆中的 swim",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docs... | 3 | stack_v2_sparse_classes_30k_train_019725 | Implement the Python class `segmentTree` described below.
Class description:
求和线段树, 完美二叉树版本,即 叶子结点树木是满的 所有的nums的值都位于 叶子结点, 而且二叉树的每一层的节点个数都是偶数
Method signatures and docstrings:
- def __init__(self, nums) -> None: d: 线段树数组 0-based nums: 索引 0-based
- def update(self, i, val): i: 0-based p: 1-based 相当于数组 nums[i] = val 那么... | Implement the Python class `segmentTree` described below.
Class description:
求和线段树, 完美二叉树版本,即 叶子结点树木是满的 所有的nums的值都位于 叶子结点, 而且二叉树的每一层的节点个数都是偶数
Method signatures and docstrings:
- def __init__(self, nums) -> None: d: 线段树数组 0-based nums: 索引 0-based
- def update(self, i, val): i: 0-based p: 1-based 相当于数组 nums[i] = val 那么... | 65549f72c565d9f11641c86d6cef9c7988805817 | <|skeleton|>
class segmentTree:
"""求和线段树, 完美二叉树版本,即 叶子结点树木是满的 所有的nums的值都位于 叶子结点, 而且二叉树的每一层的节点个数都是偶数"""
def __init__(self, nums) -> None:
"""d: 线段树数组 0-based nums: 索引 0-based"""
<|body_0|>
def update(self, i, val):
"""i: 0-based p: 1-based 相当于数组 nums[i] = val 那么就需要修改二叉树关联所有值,类似于 堆中的... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class segmentTree:
"""求和线段树, 完美二叉树版本,即 叶子结点树木是满的 所有的nums的值都位于 叶子结点, 而且二叉树的每一层的节点个数都是偶数"""
def __init__(self, nums) -> None:
"""d: 线段树数组 0-based nums: 索引 0-based"""
length = len(nums)
n = 1
while n < length:
n *= 2
self.n = n
self.d = [0] * (2 * n - 1)... | the_stack_v2_python_sparse | utils/segmentTree.py | wisesky/LeetCode-Practice | train | 0 |
58fe5db29763d16c78a46c418836a3e2b0df15f5 | [
"context = req.environ['cinder.context']\nvolume = objects.Volume.get_by_id(context, volume_id)\ncontext.authorize(policy.ENCRYPTION_METADATA_POLICY, target_obj=volume)\nreturn db.volume_encryption_metadata_get(context, volume_id)",
"encryption_item = self.index(req, volume_id)\nif encryption_item is not None:\n ... | <|body_start_0|>
context = req.environ['cinder.context']
volume = objects.Volume.get_by_id(context, volume_id)
context.authorize(policy.ENCRYPTION_METADATA_POLICY, target_obj=volume)
return db.volume_encryption_metadata_get(context, volume_id)
<|end_body_0|>
<|body_start_1|>
enc... | The volume encryption metadata API extension. | VolumeEncryptionMetadataController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VolumeEncryptionMetadataController:
"""The volume encryption metadata API extension."""
def index(self, req, volume_id):
"""Returns the encryption metadata for a given volume."""
<|body_0|>
def show(self, req, volume_id, id):
"""Return a single encryption item.""... | stack_v2_sparse_classes_36k_train_000361 | 2,194 | permissive | [
{
"docstring": "Returns the encryption metadata for a given volume.",
"name": "index",
"signature": "def index(self, req, volume_id)"
},
{
"docstring": "Return a single encryption item.",
"name": "show",
"signature": "def show(self, req, volume_id, id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017207 | Implement the Python class `VolumeEncryptionMetadataController` described below.
Class description:
The volume encryption metadata API extension.
Method signatures and docstrings:
- def index(self, req, volume_id): Returns the encryption metadata for a given volume.
- def show(self, req, volume_id, id): Return a sing... | Implement the Python class `VolumeEncryptionMetadataController` described below.
Class description:
The volume encryption metadata API extension.
Method signatures and docstrings:
- def index(self, req, volume_id): Returns the encryption metadata for a given volume.
- def show(self, req, volume_id, id): Return a sing... | 04a5d6b8c28271f6aefe2bbae6a1e16c1c235835 | <|skeleton|>
class VolumeEncryptionMetadataController:
"""The volume encryption metadata API extension."""
def index(self, req, volume_id):
"""Returns the encryption metadata for a given volume."""
<|body_0|>
def show(self, req, volume_id, id):
"""Return a single encryption item.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VolumeEncryptionMetadataController:
"""The volume encryption metadata API extension."""
def index(self, req, volume_id):
"""Returns the encryption metadata for a given volume."""
context = req.environ['cinder.context']
volume = objects.Volume.get_by_id(context, volume_id)
... | the_stack_v2_python_sparse | cinder/api/contrib/volume_encryption_metadata.py | LINBIT/openstack-cinder | train | 9 |
523cf396d97a5ba9a88feccb2aaf9633b356a7e9 | [
"distribution = renamed_kwargs('distributions', 'distribution', distribution, kwargs)\ninstance_type = renamed_kwargs('train_instance_type', 'instance_type', kwargs.get('instance_type'), kwargs)\nvalidate_version_or_image_args(framework_version, py_version, image_uri)\nif py_version == 'py2':\n logger.warning(py... | <|body_start_0|>
distribution = renamed_kwargs('distributions', 'distribution', distribution, kwargs)
instance_type = renamed_kwargs('train_instance_type', 'instance_type', kwargs.get('instance_type'), kwargs)
validate_version_or_image_args(framework_version, py_version, image_uri)
if py... | Handle end-to-end training and deployment of custom MXNet code. | MXNet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MXNet:
"""Handle end-to-end training and deployment of custom MXNet code."""
def __init__(self, entry_point: Union[str, PipelineVariable], framework_version: Optional[str]=None, py_version: Optional[str]=None, source_dir: Optional[Union[str, PipelineVariable]]=None, hyperparameters: Optional... | stack_v2_sparse_classes_36k_train_000362 | 15,079 | permissive | [
{
"docstring": "This ``Estimator`` executes an MXNet script in a managed MXNet execution environment. The managed MXNet environment is an Amazon-built Docker container that executes functions defined in the supplied ``entry_point`` Python script. Training is started by calling :meth:`~sagemaker.amazon.estimator... | 4 | stack_v2_sparse_classes_30k_train_010319 | Implement the Python class `MXNet` described below.
Class description:
Handle end-to-end training and deployment of custom MXNet code.
Method signatures and docstrings:
- def __init__(self, entry_point: Union[str, PipelineVariable], framework_version: Optional[str]=None, py_version: Optional[str]=None, source_dir: Op... | Implement the Python class `MXNet` described below.
Class description:
Handle end-to-end training and deployment of custom MXNet code.
Method signatures and docstrings:
- def __init__(self, entry_point: Union[str, PipelineVariable], framework_version: Optional[str]=None, py_version: Optional[str]=None, source_dir: Op... | 8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85 | <|skeleton|>
class MXNet:
"""Handle end-to-end training and deployment of custom MXNet code."""
def __init__(self, entry_point: Union[str, PipelineVariable], framework_version: Optional[str]=None, py_version: Optional[str]=None, source_dir: Optional[Union[str, PipelineVariable]]=None, hyperparameters: Optional... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MXNet:
"""Handle end-to-end training and deployment of custom MXNet code."""
def __init__(self, entry_point: Union[str, PipelineVariable], framework_version: Optional[str]=None, py_version: Optional[str]=None, source_dir: Optional[Union[str, PipelineVariable]]=None, hyperparameters: Optional[Dict[str, Un... | the_stack_v2_python_sparse | src/sagemaker/mxnet/estimator.py | aws/sagemaker-python-sdk | train | 2,050 |
9adc96bd7b6fdb25b973a79394ce1289b5c0300d | [
"super(TenorNetworkModule, self).__init__()\nself.args = args\nself.setup_weights()\nself.init_parameters()",
"self.weight_matrix = torch.nn.Parameter(torch.Tensor(self.args.filters_3, self.args.filters_3, self.args.tensor_neurons))\nself.weight_matrix_block = torch.nn.Parameter(torch.Tensor(self.args.tensor_neur... | <|body_start_0|>
super(TenorNetworkModule, self).__init__()
self.args = args
self.setup_weights()
self.init_parameters()
<|end_body_0|>
<|body_start_1|>
self.weight_matrix = torch.nn.Parameter(torch.Tensor(self.args.filters_3, self.args.filters_3, self.args.tensor_neurons))
... | SimGNN Tensor Network module to calculate similarity vector. | TenorNetworkModule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TenorNetworkModule:
"""SimGNN Tensor Network module to calculate similarity vector."""
def __init__(self, args):
""":param args: Arguments object."""
<|body_0|>
def setup_weights(self):
"""Defining weights."""
<|body_1|>
def init_parameters(self):
... | stack_v2_sparse_classes_36k_train_000363 | 8,576 | no_license | [
{
"docstring": ":param args: Arguments object.",
"name": "__init__",
"signature": "def __init__(self, args)"
},
{
"docstring": "Defining weights.",
"name": "setup_weights",
"signature": "def setup_weights(self)"
},
{
"docstring": "Initializing weights.",
"name": "init_paramet... | 4 | stack_v2_sparse_classes_30k_test_001122 | Implement the Python class `TenorNetworkModule` described below.
Class description:
SimGNN Tensor Network module to calculate similarity vector.
Method signatures and docstrings:
- def __init__(self, args): :param args: Arguments object.
- def setup_weights(self): Defining weights.
- def init_parameters(self): Initia... | Implement the Python class `TenorNetworkModule` described below.
Class description:
SimGNN Tensor Network module to calculate similarity vector.
Method signatures and docstrings:
- def __init__(self, args): :param args: Arguments object.
- def setup_weights(self): Defining weights.
- def init_parameters(self): Initia... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class TenorNetworkModule:
"""SimGNN Tensor Network module to calculate similarity vector."""
def __init__(self, args):
""":param args: Arguments object."""
<|body_0|>
def setup_weights(self):
"""Defining weights."""
<|body_1|>
def init_parameters(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TenorNetworkModule:
"""SimGNN Tensor Network module to calculate similarity vector."""
def __init__(self, args):
""":param args: Arguments object."""
super(TenorNetworkModule, self).__init__()
self.args = args
self.setup_weights()
self.init_parameters()
def se... | the_stack_v2_python_sparse | generated/test_benedekrozemberczki_SimGNN.py | jansel/pytorch-jit-paritybench | train | 35 |
5cb65b2bb996e48d093c3ff169ee46193a470b88 | [
"input_lines = [\"goog.provide('package.xyz');\", '/** @suppress {extraprovide} **/', \"goog.provide('package.abcd');\"]\nexpected_lines = ['/** @suppress {extraprovide} **/', \"goog.provide('package.abcd');\", \"goog.provide('package.xyz');\"]\ntoken = testutil.TokenizeSourceAndRunEcmaPass(input_lines)\nsorter = r... | <|body_start_0|>
input_lines = ["goog.provide('package.xyz');", '/** @suppress {extraprovide} **/', "goog.provide('package.abcd');"]
expected_lines = ['/** @suppress {extraprovide} **/', "goog.provide('package.abcd');", "goog.provide('package.xyz');"]
token = testutil.TokenizeSourceAndRunEcmaPas... | Tests for RequireProvideSorter. | RequireProvideSorterTest | [
"BSD-3-Clause",
"Apache-2.0",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequireProvideSorterTest:
"""Tests for RequireProvideSorter."""
def testGetFixedProvideString(self):
"""Tests that fixed string constains proper comments also."""
<|body_0|>
def testGetFixedRequireString(self):
"""Tests that fixed string constains proper comments... | stack_v2_sparse_classes_36k_train_000364 | 5,048 | permissive | [
{
"docstring": "Tests that fixed string constains proper comments also.",
"name": "testGetFixedProvideString",
"signature": "def testGetFixedProvideString(self)"
},
{
"docstring": "Tests that fixed string constains proper comments also.",
"name": "testGetFixedRequireString",
"signature":... | 6 | stack_v2_sparse_classes_30k_train_004762 | Implement the Python class `RequireProvideSorterTest` described below.
Class description:
Tests for RequireProvideSorter.
Method signatures and docstrings:
- def testGetFixedProvideString(self): Tests that fixed string constains proper comments also.
- def testGetFixedRequireString(self): Tests that fixed string cons... | Implement the Python class `RequireProvideSorterTest` described below.
Class description:
Tests for RequireProvideSorter.
Method signatures and docstrings:
- def testGetFixedProvideString(self): Tests that fixed string constains proper comments also.
- def testGetFixedRequireString(self): Tests that fixed string cons... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class RequireProvideSorterTest:
"""Tests for RequireProvideSorter."""
def testGetFixedProvideString(self):
"""Tests that fixed string constains proper comments also."""
<|body_0|>
def testGetFixedRequireString(self):
"""Tests that fixed string constains proper comments... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RequireProvideSorterTest:
"""Tests for RequireProvideSorter."""
def testGetFixedProvideString(self):
"""Tests that fixed string constains proper comments also."""
input_lines = ["goog.provide('package.xyz');", '/** @suppress {extraprovide} **/', "goog.provide('package.abcd');"]
ex... | the_stack_v2_python_sparse | third_party/catapult/third_party/closure_linter/closure_linter/requireprovidesorter_test.py | metux/chromium-suckless | train | 5 |
bcc7f1832fedfd747b4184641e5ca057f16e70fa | [
"super().__init__(reduction=LossReduction(reduction).value)\nself.to_onehot_y = to_onehot_y\nself.num_classes = num_classes\nself.gamma = gamma\nself.delta = delta\nself.weight: float = weight\nself.asy_focal_loss = AsymmetricFocalLoss(gamma=self.gamma, delta=self.delta)\nself.asy_focal_tversky_loss = AsymmetricFoc... | <|body_start_0|>
super().__init__(reduction=LossReduction(reduction).value)
self.to_onehot_y = to_onehot_y
self.num_classes = num_classes
self.gamma = gamma
self.delta = delta
self.weight: float = weight
self.asy_focal_loss = AsymmetricFocalLoss(gamma=self.gamma, ... | AsymmetricUnifiedFocalLoss is a variant of Focal Loss. Actually, it's only supported for binary image segmentation now Reimplementation of the Asymmetric Unified Focal Tversky Loss described in: - "Unified Focal Loss: Generalising Dice and Cross Entropy-based Losses to Handle Class Imbalanced Medical Image Segmentation... | AsymmetricUnifiedFocalLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsymmetricUnifiedFocalLoss:
"""AsymmetricUnifiedFocalLoss is a variant of Focal Loss. Actually, it's only supported for binary image segmentation now Reimplementation of the Asymmetric Unified Focal Tversky Loss described in: - "Unified Focal Loss: Generalising Dice and Cross Entropy-based Losses... | stack_v2_sparse_classes_36k_train_000365 | 10,224 | permissive | [
{
"docstring": "Args: to_onehot_y : whether to convert `y` into the one-hot format. Defaults to False. num_classes : number of classes, it only supports 2 now. Defaults to 2. delta : weight of the background. Defaults to 0.7. gamma : value of the exponent gamma in the definition of the Focal loss. Defaults to 0... | 2 | stack_v2_sparse_classes_30k_train_021636 | Implement the Python class `AsymmetricUnifiedFocalLoss` described below.
Class description:
AsymmetricUnifiedFocalLoss is a variant of Focal Loss. Actually, it's only supported for binary image segmentation now Reimplementation of the Asymmetric Unified Focal Tversky Loss described in: - "Unified Focal Loss: Generalis... | Implement the Python class `AsymmetricUnifiedFocalLoss` described below.
Class description:
AsymmetricUnifiedFocalLoss is a variant of Focal Loss. Actually, it's only supported for binary image segmentation now Reimplementation of the Asymmetric Unified Focal Tversky Loss described in: - "Unified Focal Loss: Generalis... | e48c3e2c741fa3fc705c4425d17ac4a5afac6c47 | <|skeleton|>
class AsymmetricUnifiedFocalLoss:
"""AsymmetricUnifiedFocalLoss is a variant of Focal Loss. Actually, it's only supported for binary image segmentation now Reimplementation of the Asymmetric Unified Focal Tversky Loss described in: - "Unified Focal Loss: Generalising Dice and Cross Entropy-based Losses... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AsymmetricUnifiedFocalLoss:
"""AsymmetricUnifiedFocalLoss is a variant of Focal Loss. Actually, it's only supported for binary image segmentation now Reimplementation of the Asymmetric Unified Focal Tversky Loss described in: - "Unified Focal Loss: Generalising Dice and Cross Entropy-based Losses to Handle Cl... | the_stack_v2_python_sparse | monai/losses/unified_focal_loss.py | Project-MONAI/MONAI | train | 4,805 |
eb3d0df096852244ec10f099054c8f783a4b3960 | [
"if 'ticker' not in request.GET:\n return Response({'error': 'ticker is required in url parameter'})\nticker = request.GET['ticker']\nstart = datetime.datetime.strptime(request.GET['start_date'], '%Y-%m-%d') if 'start_date' in request.GET else None\nend = datetime.datetime.strptime(request.GET['end_date'], '%Y-%... | <|body_start_0|>
if 'ticker' not in request.GET:
return Response({'error': 'ticker is required in url parameter'})
ticker = request.GET['ticker']
start = datetime.datetime.strptime(request.GET['start_date'], '%Y-%m-%d') if 'start_date' in request.GET else None
end = datetime.... | StockQuoteAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StockQuoteAPI:
def get(self, request):
"""Fetches all historical stock quote data on input stock :param request: ticker (required), start_date (optional), end_date (optional) :return:"""
<|body_0|>
def post(self, request):
"""Updates input stock historical quote data... | stack_v2_sparse_classes_36k_train_000366 | 5,634 | no_license | [
{
"docstring": "Fetches all historical stock quote data on input stock :param request: ticker (required), start_date (optional), end_date (optional) :return:",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Updates input stock historical quote data from start_date to end... | 2 | stack_v2_sparse_classes_30k_train_016529 | Implement the Python class `StockQuoteAPI` described below.
Class description:
Implement the StockQuoteAPI class.
Method signatures and docstrings:
- def get(self, request): Fetches all historical stock quote data on input stock :param request: ticker (required), start_date (optional), end_date (optional) :return:
- ... | Implement the Python class `StockQuoteAPI` described below.
Class description:
Implement the StockQuoteAPI class.
Method signatures and docstrings:
- def get(self, request): Fetches all historical stock quote data on input stock :param request: ticker (required), start_date (optional), end_date (optional) :return:
- ... | 4152483b1d507da6785b830154283aa76f25cef9 | <|skeleton|>
class StockQuoteAPI:
def get(self, request):
"""Fetches all historical stock quote data on input stock :param request: ticker (required), start_date (optional), end_date (optional) :return:"""
<|body_0|>
def post(self, request):
"""Updates input stock historical quote data... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StockQuoteAPI:
def get(self, request):
"""Fetches all historical stock quote data on input stock :param request: ticker (required), start_date (optional), end_date (optional) :return:"""
if 'ticker' not in request.GET:
return Response({'error': 'ticker is required in url parameter'... | the_stack_v2_python_sparse | backend/bluedresscapital/stock_apis.py | jaysunmah/bdc_v4 | train | 0 | |
436e224b8ea1d0c749ca42911d806ed89f67dec0 | [
"author = request.user\nif literature_id:\n literature = LiteratureItem.get_by_id(literature_id)\n if literature:\n data = literature.to_dict()\n return JsonResponse(data, status=200)\n return RESPONSE_404_OBJECT_NOT_FOUND\nif item_id:\n literature = LiteratureItem.objects.filter(item_id=i... | <|body_start_0|>
author = request.user
if literature_id:
literature = LiteratureItem.get_by_id(literature_id)
if literature:
data = literature.to_dict()
return JsonResponse(data, status=200)
return RESPONSE_404_OBJECT_NOT_FOUND
... | LiteratureItem view handles GET, POST, PUT, DELETE requests. | LiteratureItemView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LiteratureItemView:
"""LiteratureItem view handles GET, POST, PUT, DELETE requests."""
def get(self, request, item_id=None, literature_id=None):
"""Handles GET request, retrieves literature from the database :param request: request from the web page :type request: http Request :param... | stack_v2_sparse_classes_36k_train_000367 | 6,617 | no_license | [
{
"docstring": "Handles GET request, retrieves literature from the database :param request: request from the web page :type request: http Request :param item_id: id of a item to return. :type item_id: int :param literature_id: id of a literature to return. :type literature_id: int :return: if literature_id retu... | 4 | stack_v2_sparse_classes_30k_train_017073 | Implement the Python class `LiteratureItemView` described below.
Class description:
LiteratureItem view handles GET, POST, PUT, DELETE requests.
Method signatures and docstrings:
- def get(self, request, item_id=None, literature_id=None): Handles GET request, retrieves literature from the database :param request: req... | Implement the Python class `LiteratureItemView` described below.
Class description:
LiteratureItem view handles GET, POST, PUT, DELETE requests.
Method signatures and docstrings:
- def get(self, request, item_id=None, literature_id=None): Handles GET request, retrieves literature from the database :param request: req... | 541ee6ae488c4be7e10d001f7d05c9f9cf269821 | <|skeleton|>
class LiteratureItemView:
"""LiteratureItem view handles GET, POST, PUT, DELETE requests."""
def get(self, request, item_id=None, literature_id=None):
"""Handles GET request, retrieves literature from the database :param request: request from the web page :type request: http Request :param... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LiteratureItemView:
"""LiteratureItem view handles GET, POST, PUT, DELETE requests."""
def get(self, request, item_id=None, literature_id=None):
"""Handles GET request, retrieves literature from the database :param request: request from the web page :type request: http Request :param item_id: id ... | the_stack_v2_python_sparse | eventually/literature/views.py | lv275python/eventually.api | train | 12 |
d4ae88850d5dbd871d0ca92f0b1e9d9d07469f1b | [
"super(SQLiteParser, self).__init__(pre_obj, config)\nself._local_zone = False\nself.db = None\nparser_filter_string = getattr(self._config, 'parsers', None)\nself._plugins = plugin.GetRegisteredPlugins(interface.SQLitePlugin, self._pre_obj, parser_filter_string)",
"with interface.SQLiteDatabase(file_entry) as da... | <|body_start_0|>
super(SQLiteParser, self).__init__(pre_obj, config)
self._local_zone = False
self.db = None
parser_filter_string = getattr(self._config, 'parsers', None)
self._plugins = plugin.GetRegisteredPlugins(interface.SQLitePlugin, self._pre_obj, parser_filter_string)
<|en... | A SQLite parser for Plaso. | SQLiteParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SQLiteParser:
"""A SQLite parser for Plaso."""
def __init__(self, pre_obj, config):
"""Initializes the parser. Args: pre_obj: pre-parsing object. config: configuration object."""
<|body_0|>
def Parse(self, file_entry):
"""Parses an SQLite database. Args: file_ent... | stack_v2_sparse_classes_36k_train_000368 | 2,847 | permissive | [
{
"docstring": "Initializes the parser. Args: pre_obj: pre-parsing object. config: configuration object.",
"name": "__init__",
"signature": "def __init__(self, pre_obj, config)"
},
{
"docstring": "Parses an SQLite database. Args: file_entry: the file entry object. Returns: A event object generat... | 2 | stack_v2_sparse_classes_30k_train_005295 | Implement the Python class `SQLiteParser` described below.
Class description:
A SQLite parser for Plaso.
Method signatures and docstrings:
- def __init__(self, pre_obj, config): Initializes the parser. Args: pre_obj: pre-parsing object. config: configuration object.
- def Parse(self, file_entry): Parses an SQLite dat... | Implement the Python class `SQLiteParser` described below.
Class description:
A SQLite parser for Plaso.
Method signatures and docstrings:
- def __init__(self, pre_obj, config): Initializes the parser. Args: pre_obj: pre-parsing object. config: configuration object.
- def Parse(self, file_entry): Parses an SQLite dat... | b4dc64b3a2d2906e8947824c493a2bc311d765c1 | <|skeleton|>
class SQLiteParser:
"""A SQLite parser for Plaso."""
def __init__(self, pre_obj, config):
"""Initializes the parser. Args: pre_obj: pre-parsing object. config: configuration object."""
<|body_0|>
def Parse(self, file_entry):
"""Parses an SQLite database. Args: file_ent... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SQLiteParser:
"""A SQLite parser for Plaso."""
def __init__(self, pre_obj, config):
"""Initializes the parser. Args: pre_obj: pre-parsing object. config: configuration object."""
super(SQLiteParser, self).__init__(pre_obj, config)
self._local_zone = False
self.db = None
... | the_stack_v2_python_sparse | plaso/parsers/sqlite.py | iwm911/plaso | train | 0 |
6b2efd05e01c9c458c11ece0a2040ff23fa9a833 | [
"logger.info('Creating root object accessor %s' % name)\nself._name = name\n\nclass AccessorImpl_(clientClass):\n \"\"\"Implementation of an specific L{OsisClient} root object\n accessor\"\"\"\n _ROOTOBJECTTYPE = type_\nself._accessorimpl = AccessorImpl_",
"accessor = obj._accessors.get(self._nam... | <|body_start_0|>
logger.info('Creating root object accessor %s' % name)
self._name = name
class AccessorImpl_(clientClass):
"""Implementation of an specific L{OsisClient} root object
accessor"""
_ROOTOBJECTTYPE = type_
self._accessorimpl = Acc... | Descriptor returning a correct L{OsisClient} instance for every root object exposed on L{OsisConnection} Every L{OsisConnection} instance got an attribute, C{_accessors}, which, for every root object type, can contain an L{OsisClient} instance which will provide the necessary methods to retrieve the corresponding root ... | RootObjectAccessor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RootObjectAccessor:
"""Descriptor returning a correct L{OsisClient} instance for every root object exposed on L{OsisConnection} Every L{OsisConnection} instance got an attribute, C{_accessors}, which, for every root object type, can contain an L{OsisClient} instance which will provide the necessa... | stack_v2_sparse_classes_36k_train_000369 | 9,963 | no_license | [
{
"docstring": "Initialize a new root object accessor @param name: Name of the accessor ('clients' in 'connection.clients') @type name: string @param type_: Root object type to provide access to @type type_: type",
"name": "__init__",
"signature": "def __init__(self, name, type_, clientClass=AccessorImp... | 2 | stack_v2_sparse_classes_30k_train_018434 | Implement the Python class `RootObjectAccessor` described below.
Class description:
Descriptor returning a correct L{OsisClient} instance for every root object exposed on L{OsisConnection} Every L{OsisConnection} instance got an attribute, C{_accessors}, which, for every root object type, can contain an L{OsisClient} ... | Implement the Python class `RootObjectAccessor` described below.
Class description:
Descriptor returning a correct L{OsisClient} instance for every root object exposed on L{OsisConnection} Every L{OsisConnection} instance got an attribute, C{_accessors}, which, for every root object type, can contain an L{OsisClient} ... | 02f1d05fd90386fe2568d7c7fd032abd9061ecb4 | <|skeleton|>
class RootObjectAccessor:
"""Descriptor returning a correct L{OsisClient} instance for every root object exposed on L{OsisConnection} Every L{OsisConnection} instance got an attribute, C{_accessors}, which, for every root object type, can contain an L{OsisClient} instance which will provide the necessa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RootObjectAccessor:
"""Descriptor returning a correct L{OsisClient} instance for every root object exposed on L{OsisConnection} Every L{OsisConnection} instance got an attribute, C{_accessors}, which, for every root object type, can contain an L{OsisClient} instance which will provide the necessary methods to... | the_stack_v2_python_sparse | code/osis/client/connection.py | racktivity/ext-OSIS | train | 0 |
bdc0258a196df6980c3249c064d9762e25509ee5 | [
"self.extent = width / 2.0\nself.sub = rospy.Subscriber('input_scan', LaserScan, self.filter_scan, queue_size=10)\nself.pub = rospy.Publisher('output_scan', LaserScan, queue_size=10)",
"angles = linspace(msg.angle_min, msg.angle_max, len(msg.ranges))\npoints = [r * sin(theta) for r, theta in zip(msg.ranges, angle... | <|body_start_0|>
self.extent = width / 2.0
self.sub = rospy.Subscriber('input_scan', LaserScan, self.filter_scan, queue_size=10)
self.pub = rospy.Publisher('output_scan', LaserScan, queue_size=10)
<|end_body_0|>
<|body_start_1|>
angles = linspace(msg.angle_min, msg.angle_max, len(msg.ra... | A class that implements a LaserScan filter that removes all of the points that are not in front of the robot. | FrontFilter | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FrontFilter:
"""A class that implements a LaserScan filter that removes all of the points that are not in front of the robot."""
def __init__(self, width):
""":param self: The self reference. :param width: The width of the robot."""
<|body_0|>
def filter_scan(self, msg):... | stack_v2_sparse_classes_36k_train_000370 | 2,270 | permissive | [
{
"docstring": ":param self: The self reference. :param width: The width of the robot.",
"name": "__init__",
"signature": "def __init__(self, width)"
},
{
"docstring": ":param self: Self reference. :param msg: LaserScan message.",
"name": "filter_scan",
"signature": "def filter_scan(self... | 2 | stack_v2_sparse_classes_30k_train_011354 | Implement the Python class `FrontFilter` described below.
Class description:
A class that implements a LaserScan filter that removes all of the points that are not in front of the robot.
Method signatures and docstrings:
- def __init__(self, width): :param self: The self reference. :param width: The width of the robo... | Implement the Python class `FrontFilter` described below.
Class description:
A class that implements a LaserScan filter that removes all of the points that are not in front of the robot.
Method signatures and docstrings:
- def __init__(self, width): :param self: The self reference. :param width: The width of the robo... | 0da63ef9a36e174f782c00f56099eb71bc15ca8b | <|skeleton|>
class FrontFilter:
"""A class that implements a LaserScan filter that removes all of the points that are not in front of the robot."""
def __init__(self, width):
""":param self: The self reference. :param width: The width of the robot."""
<|body_0|>
def filter_scan(self, msg):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FrontFilter:
"""A class that implements a LaserScan filter that removes all of the points that are not in front of the robot."""
def __init__(self, width):
""":param self: The self reference. :param width: The width of the robot."""
self.extent = width / 2.0
self.sub = rospy.Subsc... | the_stack_v2_python_sparse | rob599_hw1_ref/src/front_filter.py | patu0/rob599 | train | 0 |
321824f993a083a4178f9e94d875e541e0366627 | [
"Process.__init__(self)\nself.name = 'SystemMonitor'\nself.daemon = True\nself._msg_q = msg_q\nself._init_read_bytes = psutil.disk_io_counters().read_bytes\nself._init_write_bytes = psutil.disk_io_counters().write_bytes\nself._init_bytes_sent = int(psutil.net_io_counters().bytes_sent)\nself._init_bytes_recv = int(p... | <|body_start_0|>
Process.__init__(self)
self.name = 'SystemMonitor'
self.daemon = True
self._msg_q = msg_q
self._init_read_bytes = psutil.disk_io_counters().read_bytes
self._init_write_bytes = psutil.disk_io_counters().write_bytes
self._init_bytes_sent = int(psuti... | System resource usage monitor | SystemMonitor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SystemMonitor:
"""System resource usage monitor"""
def __init__(self, exp_id, hostname, msg_q):
""":param str exp_id: experiment ID :param str hostname: hostname :param subprocess.Queue msg_q: message queue for sending data to message sender"""
<|body_0|>
def run(self):
... | stack_v2_sparse_classes_36k_train_000371 | 19,650 | no_license | [
{
"docstring": ":param str exp_id: experiment ID :param str hostname: hostname :param subprocess.Queue msg_q: message queue for sending data to message sender",
"name": "__init__",
"signature": "def __init__(self, exp_id, hostname, msg_q)"
},
{
"docstring": "Override",
"name": "run",
"si... | 3 | stack_v2_sparse_classes_30k_train_014796 | Implement the Python class `SystemMonitor` described below.
Class description:
System resource usage monitor
Method signatures and docstrings:
- def __init__(self, exp_id, hostname, msg_q): :param str exp_id: experiment ID :param str hostname: hostname :param subprocess.Queue msg_q: message queue for sending data to ... | Implement the Python class `SystemMonitor` described below.
Class description:
System resource usage monitor
Method signatures and docstrings:
- def __init__(self, exp_id, hostname, msg_q): :param str exp_id: experiment ID :param str hostname: hostname :param subprocess.Queue msg_q: message queue for sending data to ... | 723d766ee5fa996a87026f8105f37ccbcc397641 | <|skeleton|>
class SystemMonitor:
"""System resource usage monitor"""
def __init__(self, exp_id, hostname, msg_q):
""":param str exp_id: experiment ID :param str hostname: hostname :param subprocess.Queue msg_q: message queue for sending data to message sender"""
<|body_0|>
def run(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SystemMonitor:
"""System resource usage monitor"""
def __init__(self, exp_id, hostname, msg_q):
""":param str exp_id: experiment ID :param str hostname: hostname :param subprocess.Queue msg_q: message queue for sending data to message sender"""
Process.__init__(self)
self.name = '... | the_stack_v2_python_sparse | performance-monitor/producer/check_pegasus.py | dcvan/cluster15_ensemble | train | 0 |
d7e2f92a4ce61035c4c6b4c7576f4da76552662a | [
"def help(left, right):\n if not left and (not right):\n return True\n if not (left and right):\n return False\n if left.val != right.val:\n return False\n return help(left.left, right.right) and help(left.right, right.left)\nreturn help(root.left, root.right) if root else True",
... | <|body_start_0|>
def help(left, right):
if not left and (not right):
return True
if not (left and right):
return False
if left.val != right.val:
return False
return help(left.left, right.right) and help(left.right, r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSymmetric(self, root):
"""递归 怎么判断一棵树是不是对称二叉树? 如果所给根节点为空,那么是对称 如果不为空,当左右子树对称的时候,它对称 如何知道左右子树对称呢? 从图中我们发现,如果左树的左孩子和右树的右孩子一样 并且左树的右孩子和右树的左孩子一样,则对称 :param root: : TreeNode :return: -> bool 复杂度分析: 时间复杂度为O(n) 因为要遍历n个结点 空间复杂度O(H) 空间复杂度是递归的深度,也就是跟树的高度有关,最坏情况下树 变为一个链表结构,高度为n"""
... | stack_v2_sparse_classes_36k_train_000372 | 4,285 | no_license | [
{
"docstring": "递归 怎么判断一棵树是不是对称二叉树? 如果所给根节点为空,那么是对称 如果不为空,当左右子树对称的时候,它对称 如何知道左右子树对称呢? 从图中我们发现,如果左树的左孩子和右树的右孩子一样 并且左树的右孩子和右树的左孩子一样,则对称 :param root: : TreeNode :return: -> bool 复杂度分析: 时间复杂度为O(n) 因为要遍历n个结点 空间复杂度O(H) 空间复杂度是递归的深度,也就是跟树的高度有关,最坏情况下树 变为一个链表结构,高度为n",
"name": "isSymmetric",
"signature": "def isSy... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSymmetric(self, root): 递归 怎么判断一棵树是不是对称二叉树? 如果所给根节点为空,那么是对称 如果不为空,当左右子树对称的时候,它对称 如何知道左右子树对称呢? 从图中我们发现,如果左树的左孩子和右树的右孩子一样 并且左树的右孩子和右树的左孩子一样,则对称 :param root: : TreeNode :return... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSymmetric(self, root): 递归 怎么判断一棵树是不是对称二叉树? 如果所给根节点为空,那么是对称 如果不为空,当左右子树对称的时候,它对称 如何知道左右子树对称呢? 从图中我们发现,如果左树的左孩子和右树的右孩子一样 并且左树的右孩子和右树的左孩子一样,则对称 :param root: : TreeNode :return... | 51943e2c2c4ec70c7c1d5b53c9fdf0a719428d7a | <|skeleton|>
class Solution:
def isSymmetric(self, root):
"""递归 怎么判断一棵树是不是对称二叉树? 如果所给根节点为空,那么是对称 如果不为空,当左右子树对称的时候,它对称 如何知道左右子树对称呢? 从图中我们发现,如果左树的左孩子和右树的右孩子一样 并且左树的右孩子和右树的左孩子一样,则对称 :param root: : TreeNode :return: -> bool 复杂度分析: 时间复杂度为O(n) 因为要遍历n个结点 空间复杂度O(H) 空间复杂度是递归的深度,也就是跟树的高度有关,最坏情况下树 变为一个链表结构,高度为n"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isSymmetric(self, root):
"""递归 怎么判断一棵树是不是对称二叉树? 如果所给根节点为空,那么是对称 如果不为空,当左右子树对称的时候,它对称 如何知道左右子树对称呢? 从图中我们发现,如果左树的左孩子和右树的右孩子一样 并且左树的右孩子和右树的左孩子一样,则对称 :param root: : TreeNode :return: -> bool 复杂度分析: 时间复杂度为O(n) 因为要遍历n个结点 空间复杂度O(H) 空间复杂度是递归的深度,也就是跟树的高度有关,最坏情况下树 变为一个链表结构,高度为n"""
def help... | the_stack_v2_python_sparse | LeetCode_practice/BinaryTree/0101_SymmetricTree.py | LeBron-Jian/BasicAlgorithmPractice | train | 13 | |
b833ed6644663968d0fc754d93c76f18fc42c957 | [
"self.hash_func = getattr(hashlib, hash_func_name)\nif len(salts) < 3:\n raise Exception('请至少输入 3 个 salts')\nself.salts = salts",
"if isinstance(data, str):\n return data.encode()\nelif isinstance(data, bytes):\n return data\nelse:\n raise Exception('被hash值必须是一个字符串')",
"hash_values = []\nfor i in se... | <|body_start_0|>
self.hash_func = getattr(hashlib, hash_func_name)
if len(salts) < 3:
raise Exception('请至少输入 3 个 salts')
self.salts = salts
<|end_body_0|>
<|body_start_1|>
if isinstance(data, str):
return data.encode()
elif isinstance(data, bytes):
... | MultipleHash | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultipleHash:
def __init__(self, salts, hash_func_name='md5'):
"""该类实现对某个数值进行加盐hash的过程 :param salts: 对原始的数据进行预定义加盐 :param hash_func_name: 可使用多个 hash 函数"""
<|body_0|>
def _safe_data(self, data):
"""对即将hash的数据进行预处理 这里我已经确认我运行在 py3 环境中 就不像之前一样对系统进行判断 :param data: :retur... | stack_v2_sparse_classes_36k_train_000373 | 5,342 | no_license | [
{
"docstring": "该类实现对某个数值进行加盐hash的过程 :param salts: 对原始的数据进行预定义加盐 :param hash_func_name: 可使用多个 hash 函数",
"name": "__init__",
"signature": "def __init__(self, salts, hash_func_name='md5')"
},
{
"docstring": "对即将hash的数据进行预处理 这里我已经确认我运行在 py3 环境中 就不像之前一样对系统进行判断 :param data: :return:",
"name": "_s... | 3 | null | Implement the Python class `MultipleHash` described below.
Class description:
Implement the MultipleHash class.
Method signatures and docstrings:
- def __init__(self, salts, hash_func_name='md5'): 该类实现对某个数值进行加盐hash的过程 :param salts: 对原始的数据进行预定义加盐 :param hash_func_name: 可使用多个 hash 函数
- def _safe_data(self, data): 对即将ha... | Implement the Python class `MultipleHash` described below.
Class description:
Implement the MultipleHash class.
Method signatures and docstrings:
- def __init__(self, salts, hash_func_name='md5'): 该类实现对某个数值进行加盐hash的过程 :param salts: 对原始的数据进行预定义加盐 :param hash_func_name: 可使用多个 hash 函数
- def _safe_data(self, data): 对即将ha... | c0d99403a90aaf0444def560edc0473efcf6d57f | <|skeleton|>
class MultipleHash:
def __init__(self, salts, hash_func_name='md5'):
"""该类实现对某个数值进行加盐hash的过程 :param salts: 对原始的数据进行预定义加盐 :param hash_func_name: 可使用多个 hash 函数"""
<|body_0|>
def _safe_data(self, data):
"""对即将hash的数据进行预处理 这里我已经确认我运行在 py3 环境中 就不像之前一样对系统进行判断 :param data: :retur... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultipleHash:
def __init__(self, salts, hash_func_name='md5'):
"""该类实现对某个数值进行加盐hash的过程 :param salts: 对原始的数据进行预定义加盐 :param hash_func_name: 可使用多个 hash 函数"""
self.hash_func = getattr(hashlib, hash_func_name)
if len(salts) < 3:
raise Exception('请至少输入 3 个 salts')
self.sa... | the_stack_v2_python_sparse | common/bloom_filter_service.py | ren168/JustSimpleSpider | train | 0 | |
f084c4d84c5c54fff59ad60b57501e8bc24119b5 | [
"super(JPEGCompression).__init__()\nassert 100 >= quality > 0\nself.quality = quality\nself.to_image = transform.ToPILImage()\nself.to_tensor = transform.ToTensor()",
"if image.ndim == 4:\n image = image.squeeze()\njpg = BytesIO()\npil = self.to_image(image)\npil.save(jpg, 'JPEG', quality=self.quality)\ntensor... | <|body_start_0|>
super(JPEGCompression).__init__()
assert 100 >= quality > 0
self.quality = quality
self.to_image = transform.ToPILImage()
self.to_tensor = transform.ToTensor()
<|end_body_0|>
<|body_start_1|>
if image.ndim == 4:
image = image.squeeze()
... | Implementation of JPEG Compression defence | JPEGCompression | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JPEGCompression:
"""Implementation of JPEG Compression defence"""
def __init__(self, quality=20):
""":param quality: Compression quality. Lower means more compression."""
<|body_0|>
def __call__(self, image):
""":param image: The image to apply the defence to. :r... | stack_v2_sparse_classes_36k_train_000374 | 1,026 | permissive | [
{
"docstring": ":param quality: Compression quality. Lower means more compression.",
"name": "__init__",
"signature": "def __init__(self, quality=20)"
},
{
"docstring": ":param image: The image to apply the defence to. :return: Image tensor compressed using JPEG compression.",
"name": "__cal... | 2 | stack_v2_sparse_classes_30k_train_004455 | Implement the Python class `JPEGCompression` described below.
Class description:
Implementation of JPEG Compression defence
Method signatures and docstrings:
- def __init__(self, quality=20): :param quality: Compression quality. Lower means more compression.
- def __call__(self, image): :param image: The image to app... | Implement the Python class `JPEGCompression` described below.
Class description:
Implementation of JPEG Compression defence
Method signatures and docstrings:
- def __init__(self, quality=20): :param quality: Compression quality. Lower means more compression.
- def __call__(self, image): :param image: The image to app... | f5a79e3aa5dc15d7f2fd677ea64f41dd3a1e9cd8 | <|skeleton|>
class JPEGCompression:
"""Implementation of JPEG Compression defence"""
def __init__(self, quality=20):
""":param quality: Compression quality. Lower means more compression."""
<|body_0|>
def __call__(self, image):
""":param image: The image to apply the defence to. :r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JPEGCompression:
"""Implementation of JPEG Compression defence"""
def __init__(self, quality=20):
""":param quality: Compression quality. Lower means more compression."""
super(JPEGCompression).__init__()
assert 100 >= quality > 0
self.quality = quality
self.to_ima... | the_stack_v2_python_sparse | sat/defence/JPEGCompression.py | larsksy/Semantic-Adversarial-Toolbox | train | 1 |
3fb62d5061ddee8cd773e3d70b35af53732b9114 | [
"self.input_size = input_size\nself.output_size = output_size\nself.mem_size = mem_size\nself.mem_width = mem_width\nself.layer_sizes = layer_sizes\nself.num_heads = num_heads\nself.W_read_list = [init_weights(shape=(self.mem_width, 4 * self.layer_sizes[0]), name='W_read_%d' % h) for h in range(self.num_heads)]\nse... | <|body_start_0|>
self.input_size = input_size
self.output_size = output_size
self.mem_size = mem_size
self.mem_width = mem_width
self.layer_sizes = layer_sizes
self.num_heads = num_heads
self.W_read_list = [init_weights(shape=(self.mem_width, 4 * self.layer_sizes[... | ControllerLSTM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ControllerLSTM:
def __init__(self, input_size=8, output_size=8, mem_size=128, mem_width=20, layer_sizes=[100], num_heads=3):
""":type input_size: int :param input_size: the input size of outside input :type output_size: int :param output_size: the output size of outside output :type mem_... | stack_v2_sparse_classes_36k_train_000375 | 6,110 | no_license | [
{
"docstring": ":type input_size: int :param input_size: the input size of outside input :type output_size: int :param output_size: the output size of outside output :type mem_size: int :param mem_size: rows of the memory matrix :type mem_width: int :param mem_width: length of each row in the memory matrix :typ... | 2 | stack_v2_sparse_classes_30k_train_001015 | Implement the Python class `ControllerLSTM` described below.
Class description:
Implement the ControllerLSTM class.
Method signatures and docstrings:
- def __init__(self, input_size=8, output_size=8, mem_size=128, mem_width=20, layer_sizes=[100], num_heads=3): :type input_size: int :param input_size: the input size o... | Implement the Python class `ControllerLSTM` described below.
Class description:
Implement the ControllerLSTM class.
Method signatures and docstrings:
- def __init__(self, input_size=8, output_size=8, mem_size=128, mem_width=20, layer_sizes=[100], num_heads=3): :type input_size: int :param input_size: the input size o... | f10abd01b5e1b855c169575353ce5a3027b413c6 | <|skeleton|>
class ControllerLSTM:
def __init__(self, input_size=8, output_size=8, mem_size=128, mem_width=20, layer_sizes=[100], num_heads=3):
""":type input_size: int :param input_size: the input size of outside input :type output_size: int :param output_size: the output size of outside output :type mem_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ControllerLSTM:
def __init__(self, input_size=8, output_size=8, mem_size=128, mem_width=20, layer_sizes=[100], num_heads=3):
""":type input_size: int :param input_size: the input size of outside input :type output_size: int :param output_size: the output size of outside output :type mem_size: int :par... | the_stack_v2_python_sparse | RL/turing-machine/layers/controller.py | BigeyeDestroyer/rnn-project | train | 7 | |
1e7e8816ec6e1760bde7146bfade6b18b9c66402 | [
"dp = [0] * (num + 1)\ndp[0] = 0\nfor i in range(1, num + 1):\n dp[i] = dp[i - 2 ** floor(log2(i))] + 1\nreturn dp",
"dp = [0] * (num + 1)\ndp[0] = 0\nfor i in range(1, num + 1):\n tmp = i\n j = 0\n while tmp >= 2:\n j += 1\n tmp = tmp >> 1\n dp[i] = dp[i - 2 ** j] + 1\nreturn dp"
] | <|body_start_0|>
dp = [0] * (num + 1)
dp[0] = 0
for i in range(1, num + 1):
dp[i] = dp[i - 2 ** floor(log2(i))] + 1
return dp
<|end_body_0|>
<|body_start_1|>
dp = [0] * (num + 1)
dp[0] = 0
for i in range(1, num + 1):
tmp = i
j ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countBits(self, num: int) -> List[int]:
"""DP, Time: O(n), Space: O(n)"""
<|body_0|>
def countBits(self, num: int) -> List[int]:
"""Without build in log2"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dp = [0] * (num + 1)
dp[0... | stack_v2_sparse_classes_36k_train_000376 | 1,033 | no_license | [
{
"docstring": "DP, Time: O(n), Space: O(n)",
"name": "countBits",
"signature": "def countBits(self, num: int) -> List[int]"
},
{
"docstring": "Without build in log2",
"name": "countBits",
"signature": "def countBits(self, num: int) -> List[int]"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countBits(self, num: int) -> List[int]: DP, Time: O(n), Space: O(n)
- def countBits(self, num: int) -> List[int]: Without build in log2 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countBits(self, num: int) -> List[int]: DP, Time: O(n), Space: O(n)
- def countBits(self, num: int) -> List[int]: Without build in log2
<|skeleton|>
class Solution:
def... | 72136e3487d239f5b37e2d6393e034262a6bf599 | <|skeleton|>
class Solution:
def countBits(self, num: int) -> List[int]:
"""DP, Time: O(n), Space: O(n)"""
<|body_0|>
def countBits(self, num: int) -> List[int]:
"""Without build in log2"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countBits(self, num: int) -> List[int]:
"""DP, Time: O(n), Space: O(n)"""
dp = [0] * (num + 1)
dp[0] = 0
for i in range(1, num + 1):
dp[i] = dp[i - 2 ** floor(log2(i))] + 1
return dp
def countBits(self, num: int) -> List[int]:
"""W... | the_stack_v2_python_sparse | python/338-Counting Bits.py | cwza/leetcode | train | 0 | |
5976a2dd80d24ba694dad84da69c4cae4b9f5dd8 | [
"super().__init__(n_feat, n_head, dropout)\nprecision = torch.float\nself.rotary_ndims = self.d_k\nif precision == 'fp16':\n precision = torch.half\nself.rotary_emb = RotaryPositionalEmbedding(self.rotary_ndims, base=rotary_emd_base, precision=precision)",
"T, B, C = value.size()\nquery = query.view(T, B, self... | <|body_start_0|>
super().__init__(n_feat, n_head, dropout)
precision = torch.float
self.rotary_ndims = self.d_k
if precision == 'fp16':
precision = torch.half
self.rotary_emb = RotaryPositionalEmbedding(self.rotary_ndims, base=rotary_emd_base, precision=precision)
<|e... | RotaryPositionMultiHeadedAttention | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"LGPL-2.1-or-later",
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RotaryPositionMultiHeadedAttention:
def __init__(self, n_feat, n_head, dropout, precision, rotary_emd_base=10000):
"""Construct an RotaryPositionMultiHeadedAttention object."""
<|body_0|>
def forward(self, query, key, value, key_padding_mask=None, **kwargs):
"""Compu... | stack_v2_sparse_classes_36k_train_000377 | 9,673 | permissive | [
{
"docstring": "Construct an RotaryPositionMultiHeadedAttention object.",
"name": "__init__",
"signature": "def __init__(self, n_feat, n_head, dropout, precision, rotary_emd_base=10000)"
},
{
"docstring": "Compute rotary position attention. Args: query: Query tensor T X B X C key: Key tensor T X... | 2 | stack_v2_sparse_classes_30k_train_000148 | Implement the Python class `RotaryPositionMultiHeadedAttention` described below.
Class description:
Implement the RotaryPositionMultiHeadedAttention class.
Method signatures and docstrings:
- def __init__(self, n_feat, n_head, dropout, precision, rotary_emd_base=10000): Construct an RotaryPositionMultiHeadedAttention... | Implement the Python class `RotaryPositionMultiHeadedAttention` described below.
Class description:
Implement the RotaryPositionMultiHeadedAttention class.
Method signatures and docstrings:
- def __init__(self, n_feat, n_head, dropout, precision, rotary_emd_base=10000): Construct an RotaryPositionMultiHeadedAttention... | b60c741f746877293bb85eed6806736fc8fa0ffd | <|skeleton|>
class RotaryPositionMultiHeadedAttention:
def __init__(self, n_feat, n_head, dropout, precision, rotary_emd_base=10000):
"""Construct an RotaryPositionMultiHeadedAttention object."""
<|body_0|>
def forward(self, query, key, value, key_padding_mask=None, **kwargs):
"""Compu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RotaryPositionMultiHeadedAttention:
def __init__(self, n_feat, n_head, dropout, precision, rotary_emd_base=10000):
"""Construct an RotaryPositionMultiHeadedAttention object."""
super().__init__(n_feat, n_head, dropout)
precision = torch.float
self.rotary_ndims = self.d_k
... | the_stack_v2_python_sparse | kosmos-2/fairseq/fairseq/modules/espnet_multihead_attention.py | microsoft/unilm | train | 15,313 | |
4e1e867ce5b564f944423487e76af73c8a4a6a73 | [
"self.q = collections.deque([])\nfor i in range(0, len(A), 2):\n if A[i] > 0:\n self.q.append((A[i], A[i + 1]))",
"while n > 0 and self.q:\n count, number = self.q.popleft()\n if count >= n:\n count -= n\n if count > 0:\n self.q.appendleft((count, number))\n return ... | <|body_start_0|>
self.q = collections.deque([])
for i in range(0, len(A), 2):
if A[i] > 0:
self.q.append((A[i], A[i + 1]))
<|end_body_0|>
<|body_start_1|>
while n > 0 and self.q:
count, number = self.q.popleft()
if count >= n:
... | RLEIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RLEIterator:
def __init__(self, A):
""":type A: List[int]"""
<|body_0|>
def next(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.q = collections.deque([])
for i in range(0, len(A), 2):
i... | stack_v2_sparse_classes_36k_train_000378 | 768 | no_license | [
{
"docstring": ":type A: List[int]",
"name": "__init__",
"signature": "def __init__(self, A)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "next",
"signature": "def next(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017823 | Implement the Python class `RLEIterator` described below.
Class description:
Implement the RLEIterator class.
Method signatures and docstrings:
- def __init__(self, A): :type A: List[int]
- def next(self, n): :type n: int :rtype: int | Implement the Python class `RLEIterator` described below.
Class description:
Implement the RLEIterator class.
Method signatures and docstrings:
- def __init__(self, A): :type A: List[int]
- def next(self, n): :type n: int :rtype: int
<|skeleton|>
class RLEIterator:
def __init__(self, A):
""":type A: Lis... | 20fe3c9adb0a6937ea6482b26f26fddfa04a64b8 | <|skeleton|>
class RLEIterator:
def __init__(self, A):
""":type A: List[int]"""
<|body_0|>
def next(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RLEIterator:
def __init__(self, A):
""":type A: List[int]"""
self.q = collections.deque([])
for i in range(0, len(A), 2):
if A[i] > 0:
self.q.append((A[i], A[i + 1]))
def next(self, n):
""":type n: int :rtype: int"""
while n > 0 and self... | the_stack_v2_python_sparse | 900. RLE Iterator.py | YuzhouPeng/LeetCode-Python | train | 0 | |
615f0344914a603fdfec80c7061858bd8985a71b | [
"super(_RunnerWrapper, self).__init__(config)\nself.dry_run = False\n'\\n Does not run tests (only fetches \"self.features\") if true. Runs tests otherwise.\\n '\nself.__hooks = hooks",
"super(_RunnerWrapper, self).load_hooks(filename)\nfor hook_name, hook in self.__hooks.items():\n hook_to_add =... | <|body_start_0|>
super(_RunnerWrapper, self).__init__(config)
self.dry_run = False
'\n Does not run tests (only fetches "self.features") if true. Runs tests otherwise.\n '
self.__hooks = hooks
<|end_body_0|>
<|body_start_1|>
super(_RunnerWrapper, self).load_hooks(f... | Wrapper around behave native wrapper. Has nothing todo with BddRunner! We need it to support dry runs (to fetch data from scenarios) and hooks api | _RunnerWrapper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _RunnerWrapper:
"""Wrapper around behave native wrapper. Has nothing todo with BddRunner! We need it to support dry runs (to fetch data from scenarios) and hooks api"""
def __init__(self, config, hooks):
""":type config configuration.Configuration :param config behave configuration :... | stack_v2_sparse_classes_36k_train_000379 | 13,356 | permissive | [
{
"docstring": ":type config configuration.Configuration :param config behave configuration :type hooks dict or empty if new runner mode :param hooks hooks in format \"before_scenario\" => f(context, scenario) to load after/before hooks, provided by user",
"name": "__init__",
"signature": "def __init__(... | 4 | null | Implement the Python class `_RunnerWrapper` described below.
Class description:
Wrapper around behave native wrapper. Has nothing todo with BddRunner! We need it to support dry runs (to fetch data from scenarios) and hooks api
Method signatures and docstrings:
- def __init__(self, config, hooks): :type config configu... | Implement the Python class `_RunnerWrapper` described below.
Class description:
Wrapper around behave native wrapper. Has nothing todo with BddRunner! We need it to support dry runs (to fetch data from scenarios) and hooks api
Method signatures and docstrings:
- def __init__(self, config, hooks): :type config configu... | 05dbd4575d01a213f3f4d69aa4968473f2536142 | <|skeleton|>
class _RunnerWrapper:
"""Wrapper around behave native wrapper. Has nothing todo with BddRunner! We need it to support dry runs (to fetch data from scenarios) and hooks api"""
def __init__(self, config, hooks):
""":type config configuration.Configuration :param config behave configuration :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _RunnerWrapper:
"""Wrapper around behave native wrapper. Has nothing todo with BddRunner! We need it to support dry runs (to fetch data from scenarios) and hooks api"""
def __init__(self, config, hooks):
""":type config configuration.Configuration :param config behave configuration :type hooks di... | the_stack_v2_python_sparse | python/helpers/pycharm/behave_runner.py | JetBrains/intellij-community | train | 16,288 |
0798982cc7b7658ac3fdfdbfc0335e1c775d65b4 | [
"threading.Thread.__init__(self)\nself.region_name = region_name\nself.profile_name = profile_name\nself.spot_master_table_name = spot_master_table_name\nself.spot_master_queue_name = spot_master_queue_name\nself.spot_request_table_name = spot_request_table_name\nself.spot_request_queue_name = spot_request_queue_na... | <|body_start_0|>
threading.Thread.__init__(self)
self.region_name = region_name
self.profile_name = profile_name
self.spot_master_table_name = spot_master_table_name
self.spot_master_queue_name = spot_master_queue_name
self.spot_request_table_name = spot_request_table_nam... | Dispatch Master messages - launch a microservice to execute based on the service_class_name attribute Note that the service class names are defined in :class:awsspotbatch.common.const and begin with MICROSVC_MASTER_CLASSNAME_ | SpotMasterDispatcher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpotMasterDispatcher:
"""Dispatch Master messages - launch a microservice to execute based on the service_class_name attribute Note that the service class names are defined in :class:awsspotbatch.common.const and begin with MICROSVC_MASTER_CLASSNAME_"""
def __init__(self, spot_master_table_n... | stack_v2_sparse_classes_36k_train_000380 | 7,141 | no_license | [
{
"docstring": ":param spot_master_table_name: (Default value = awsspotbatch.common.const.SPOT_MASTER_TABLE_NAME) :param spot_master_queue_name: (Default value = awsspotbatch.common.const.SPOT_MASTER_QUEUE_NAME) :param spot_request_table_name: (Default value = awsspotbatch.common.const.SPOT_REQUEST_TABLE_NAME) ... | 2 | stack_v2_sparse_classes_30k_val_000810 | Implement the Python class `SpotMasterDispatcher` described below.
Class description:
Dispatch Master messages - launch a microservice to execute based on the service_class_name attribute Note that the service class names are defined in :class:awsspotbatch.common.const and begin with MICROSVC_MASTER_CLASSNAME_
Method... | Implement the Python class `SpotMasterDispatcher` described below.
Class description:
Dispatch Master messages - launch a microservice to execute based on the service_class_name attribute Note that the service class names are defined in :class:awsspotbatch.common.const and begin with MICROSVC_MASTER_CLASSNAME_
Method... | f6db8f9f65bd231f3589865ac2eb1bcb45c9d837 | <|skeleton|>
class SpotMasterDispatcher:
"""Dispatch Master messages - launch a microservice to execute based on the service_class_name attribute Note that the service class names are defined in :class:awsspotbatch.common.const and begin with MICROSVC_MASTER_CLASSNAME_"""
def __init__(self, spot_master_table_n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpotMasterDispatcher:
"""Dispatch Master messages - launch a microservice to execute based on the service_class_name attribute Note that the service class names are defined in :class:awsspotbatch.common.const and begin with MICROSVC_MASTER_CLASSNAME_"""
def __init__(self, spot_master_table_name=awsspotba... | the_stack_v2_python_sparse | src/awsspotbatch/microsvc/master/spotmasterdispatcher.py | petezybrick/awsspotbatch | train | 1 |
c506c4115e9a29e10e005c12702987e735f96f3d | [
"if digits[-1] < 9:\n digits[-1] += 1\n return digits\nelse:\n str_s = str()\n result = []\n for i in range(len(digits)):\n str_s += str(digits[i])\n for i in str(int(str_s) + 1):\n result.append(int(i))\n return result",
"index = len(digits)\nif index == 0:\n return digits\n... | <|body_start_0|>
if digits[-1] < 9:
digits[-1] += 1
return digits
else:
str_s = str()
result = []
for i in range(len(digits)):
str_s += str(digits[i])
for i in str(int(str_s) + 1):
result.append(int(i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def plusOne1(self, digits: List[int]) -> List[int]:
"""执行用时: 40 ms , 在所有 Python3 提交中击败了 57.89% 的用户 内存消耗: 14.9 MB , 在所有 Python3 提交中击败了 21.62% 的用户 :param digits: :return:"""
<|body_0|>
def plusOne(self, digits: List[int]) -> List[int]:
"""执行用时: 24 ms , 在所有 Py... | stack_v2_sparse_classes_36k_train_000381 | 2,456 | no_license | [
{
"docstring": "执行用时: 40 ms , 在所有 Python3 提交中击败了 57.89% 的用户 内存消耗: 14.9 MB , 在所有 Python3 提交中击败了 21.62% 的用户 :param digits: :return:",
"name": "plusOne1",
"signature": "def plusOne1(self, digits: List[int]) -> List[int]"
},
{
"docstring": "执行用时: 24 ms , 在所有 Python3 提交中击败了 99.67% 的用户 内存消耗: 14.7 MB ,... | 3 | stack_v2_sparse_classes_30k_train_001403 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def plusOne1(self, digits: List[int]) -> List[int]: 执行用时: 40 ms , 在所有 Python3 提交中击败了 57.89% 的用户 内存消耗: 14.9 MB , 在所有 Python3 提交中击败了 21.62% 的用户 :param digits: :return:
- def plusOn... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def plusOne1(self, digits: List[int]) -> List[int]: 执行用时: 40 ms , 在所有 Python3 提交中击败了 57.89% 的用户 内存消耗: 14.9 MB , 在所有 Python3 提交中击败了 21.62% 的用户 :param digits: :return:
- def plusOn... | d613ed8a5a2c15ace7d513965b372d128845d66a | <|skeleton|>
class Solution:
def plusOne1(self, digits: List[int]) -> List[int]:
"""执行用时: 40 ms , 在所有 Python3 提交中击败了 57.89% 的用户 内存消耗: 14.9 MB , 在所有 Python3 提交中击败了 21.62% 的用户 :param digits: :return:"""
<|body_0|>
def plusOne(self, digits: List[int]) -> List[int]:
"""执行用时: 24 ms , 在所有 Py... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def plusOne1(self, digits: List[int]) -> List[int]:
"""执行用时: 40 ms , 在所有 Python3 提交中击败了 57.89% 的用户 内存消耗: 14.9 MB , 在所有 Python3 提交中击败了 21.62% 的用户 :param digits: :return:"""
if digits[-1] < 9:
digits[-1] += 1
return digits
else:
str_s = str()... | the_stack_v2_python_sparse | plus_one.py | nomboy/leetcode | train | 0 | |
26ff8b9b8b6f4d25cd599ad7f21179d81a8dc43e | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('raykatz_nedg_gaudiosi', 'raykatz_nedg_gaudiosi')\nwith open('auth.json') as data_file:\n data = json.load(data_file)\nurl = 'http://realtime.mbta.com/developer/api/v2/routes?api_key=' + data['mbta'] +... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('raykatz_nedg_gaudiosi', 'raykatz_nedg_gaudiosi')
with open('auth.json') as data_file:
data = json.load(data_file)
url = 'http://realti... | mbta_routes | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class mbta_routes:
def execute(trial=False):
"""Retrieve mbta_routes data from US Census"""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happening in this script. Each run of... | stack_v2_sparse_classes_36k_train_000382 | 4,206 | no_license | [
{
"docstring": "Retrieve mbta_routes data from US Census",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new document describing that invocation e... | 2 | null | Implement the Python class `mbta_routes` described below.
Class description:
Implement the mbta_routes class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve mbta_routes data from US Census
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Create the provenance docu... | Implement the Python class `mbta_routes` described below.
Class description:
Implement the mbta_routes class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve mbta_routes data from US Census
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Create the provenance docu... | 97e72731ffadbeae57d7a332decd58706e7c08de | <|skeleton|>
class mbta_routes:
def execute(trial=False):
"""Retrieve mbta_routes data from US Census"""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happening in this script. Each run of... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class mbta_routes:
def execute(trial=False):
"""Retrieve mbta_routes data from US Census"""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('raykatz_nedg_gaudiosi', 'raykatz_nedg_gaudiosi')
with open('auth.js... | the_stack_v2_python_sparse | raykatz_nedg_gaudiosi/mbta_routes.py | ROODAY/course-2017-fal-proj | train | 3 | |
6abe2f0b07755ec38c14e1be56bef53638193efa | [
"self.hardware_client.seti('dios/0/mode', 0)\ncurrent_output = self.hardware_client.geti('dios/0/output')\nif newval == 0:\n DIO_bit_bitshifted = ~(1 << self.DIO_bit)\n new_output = current_output & DIO_bit_bitshifted\nelif newval == 1:\n DIO_bit_bitshifted = 1 << self.DIO_bit\n new_output = current_out... | <|body_start_0|>
self.hardware_client.seti('dios/0/mode', 0)
current_output = self.hardware_client.geti('dios/0/output')
if newval == 0:
DIO_bit_bitshifted = ~(1 << self.DIO_bit)
new_output = current_output & DIO_bit_bitshifted
elif newval == 1:
DIO_bi... | HDAWG | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HDAWG:
def _HDAWG_toggle(self, newval):
"""Set DIO_bit to high or low :newval: Either 0 or 1 indicating the new output state."""
<|body_0|>
def setup(self):
"""Setup a ZI HDAWG driver module to be used as a staticline toggle. :DIO_bit: Which bit to toggle, in decimal... | stack_v2_sparse_classes_36k_train_000383 | 11,934 | permissive | [
{
"docstring": "Set DIO_bit to high or low :newval: Either 0 or 1 indicating the new output state.",
"name": "_HDAWG_toggle",
"signature": "def _HDAWG_toggle(self, newval)"
},
{
"docstring": "Setup a ZI HDAWG driver module to be used as a staticline toggle. :DIO_bit: Which bit to toggle, in deci... | 2 | null | Implement the Python class `HDAWG` described below.
Class description:
Implement the HDAWG class.
Method signatures and docstrings:
- def _HDAWG_toggle(self, newval): Set DIO_bit to high or low :newval: Either 0 or 1 indicating the new output state.
- def setup(self): Setup a ZI HDAWG driver module to be used as a st... | Implement the Python class `HDAWG` described below.
Class description:
Implement the HDAWG class.
Method signatures and docstrings:
- def _HDAWG_toggle(self, newval): Set DIO_bit to high or low :newval: Either 0 or 1 indicating the new output state.
- def setup(self): Setup a ZI HDAWG driver module to be used as a st... | c8794a342d30119a6be93b2dd30ea61b5c946d8a | <|skeleton|>
class HDAWG:
def _HDAWG_toggle(self, newval):
"""Set DIO_bit to high or low :newval: Either 0 or 1 indicating the new output state."""
<|body_0|>
def setup(self):
"""Setup a ZI HDAWG driver module to be used as a staticline toggle. :DIO_bit: Which bit to toggle, in decimal... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HDAWG:
def _HDAWG_toggle(self, newval):
"""Set DIO_bit to high or low :newval: Either 0 or 1 indicating the new output state."""
self.hardware_client.seti('dios/0/mode', 0)
current_output = self.hardware_client.geti('dios/0/output')
if newval == 0:
DIO_bit_bitshifte... | the_stack_v2_python_sparse | pylabnet/hardware/staticline/staticline_devices.py | lukingroup/pylabnet | train | 15 | |
9b90606d3456f8603f6db3ae0aea5585b0173077 | [
"picking_obj = self.pool.get('stock.picking')\nseq_obj_name = self._name\nvals['name'] = self.pool.get('ir.sequence').get(cr, user, seq_obj_name)\nnew_id = picking_obj.create(cr, user, vals, context)\nreturn new_id",
"picking_obj = self.pool.get('stock.picking')\nwrite_boolean = picking_obj.write(cr, uid, ids, va... | <|body_start_0|>
picking_obj = self.pool.get('stock.picking')
seq_obj_name = self._name
vals['name'] = self.pool.get('ir.sequence').get(cr, user, seq_obj_name)
new_id = picking_obj.create(cr, user, vals, context)
return new_id
<|end_body_0|>
<|body_start_1|>
picking_obj ... | stock_picking_in | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class stock_picking_in:
def create(self, cr, user, vals, context=None):
"""Override create to call create of stock.picking"""
<|body_0|>
def write(self, cr, uid, ids, vals, context=None):
"""Override write to call write of stock.picking"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k_train_000384 | 17,898 | no_license | [
{
"docstring": "Override create to call create of stock.picking",
"name": "create",
"signature": "def create(self, cr, user, vals, context=None)"
},
{
"docstring": "Override write to call write of stock.picking",
"name": "write",
"signature": "def write(self, cr, uid, ids, vals, context=... | 2 | stack_v2_sparse_classes_30k_test_000667 | Implement the Python class `stock_picking_in` described below.
Class description:
Implement the stock_picking_in class.
Method signatures and docstrings:
- def create(self, cr, user, vals, context=None): Override create to call create of stock.picking
- def write(self, cr, uid, ids, vals, context=None): Override writ... | Implement the Python class `stock_picking_in` described below.
Class description:
Implement the stock_picking_in class.
Method signatures and docstrings:
- def create(self, cr, user, vals, context=None): Override create to call create of stock.picking
- def write(self, cr, uid, ids, vals, context=None): Override writ... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class stock_picking_in:
def create(self, cr, user, vals, context=None):
"""Override create to call create of stock.picking"""
<|body_0|>
def write(self, cr, uid, ids, vals, context=None):
"""Override write to call write of stock.picking"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class stock_picking_in:
def create(self, cr, user, vals, context=None):
"""Override create to call create of stock.picking"""
picking_obj = self.pool.get('stock.picking')
seq_obj_name = self._name
vals['name'] = self.pool.get('ir.sequence').get(cr, user, seq_obj_name)
new_id ... | the_stack_v2_python_sparse | v_7/NISS/shamil_v3/stock_oc/model/stock.py | musabahmed/baba | train | 0 | |
1e35c22dcc71e1ce17c1f00a66bc4baaa14a75df | [
"self.input = input\nself.all_colors = [1, 2, 3, 4, 5, 6, 7]\nself.costscheme = costscheme",
"gc = self.input.check_graph()\nwhile not self.input.found():\n for counter, node in enumerate(self.input.wrong_nodes):\n neighbour_colors = []\n for neighbour in node.neighbours:\n neighbour_c... | <|body_start_0|>
self.input = input
self.all_colors = [1, 2, 3, 4, 5, 6, 7]
self.costscheme = costscheme
<|end_body_0|>
<|body_start_1|>
gc = self.input.check_graph()
while not self.input.found():
for counter, node in enumerate(self.input.wrong_nodes):
... | Greedy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Greedy:
def __init__(self, input, costscheme):
"""An initializer takes a randomly generated input graph and costscheme"""
<|body_0|>
def greedy_fill(self):
"""Uses an pre made graph, and optimises it by changing the color of the neighbours and checking the result"""
... | stack_v2_sparse_classes_36k_train_000385 | 1,546 | no_license | [
{
"docstring": "An initializer takes a randomly generated input graph and costscheme",
"name": "__init__",
"signature": "def __init__(self, input, costscheme)"
},
{
"docstring": "Uses an pre made graph, and optimises it by changing the color of the neighbours and checking the result",
"name"... | 2 | stack_v2_sparse_classes_30k_train_019995 | Implement the Python class `Greedy` described below.
Class description:
Implement the Greedy class.
Method signatures and docstrings:
- def __init__(self, input, costscheme): An initializer takes a randomly generated input graph and costscheme
- def greedy_fill(self): Uses an pre made graph, and optimises it by chang... | Implement the Python class `Greedy` described below.
Class description:
Implement the Greedy class.
Method signatures and docstrings:
- def __init__(self, input, costscheme): An initializer takes a randomly generated input graph and costscheme
- def greedy_fill(self): Uses an pre made graph, and optimises it by chang... | 50411bb6814a30008a83a3ecabab2ce49dae1fea | <|skeleton|>
class Greedy:
def __init__(self, input, costscheme):
"""An initializer takes a randomly generated input graph and costscheme"""
<|body_0|>
def greedy_fill(self):
"""Uses an pre made graph, and optimises it by changing the color of the neighbours and checking the result"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Greedy:
def __init__(self, input, costscheme):
"""An initializer takes a randomly generated input graph and costscheme"""
self.input = input
self.all_colors = [1, 2, 3, 4, 5, 6, 7]
self.costscheme = costscheme
def greedy_fill(self):
"""Uses an pre made graph, and o... | the_stack_v2_python_sparse | algorithms/greedy.py | matt-mrf/QuMaDel | train | 0 | |
2dc54fa465b4c299ac2d858e69f178c69b3aef25 | [
"self.heights = heights\nmin_ = 0\nmax_ = max((max(row) for row in heights)) - min((min(row) for row in heights))\nwhile min_ < max_:\n guess = (min_ + max_) // 2\n if self.verifyIsPossible(guess):\n max_ = guess\n else:\n min_ = guess + 1\nreturn max_",
"rec = [(0, 0)]\nattainable = set(re... | <|body_start_0|>
self.heights = heights
min_ = 0
max_ = max((max(row) for row in heights)) - min((min(row) for row in heights))
while min_ < max_:
guess = (min_ + max_) // 2
if self.verifyIsPossible(guess):
max_ = guess
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minimumEffortPath(self, heights: List[List[int]]) -> int:
"""Find the minimum effort required to get from top-left corner of heights to lower-right :param heights: rectangular-like map represented as list of lists :return: the minimum effort required Time complexity: O(mn *... | stack_v2_sparse_classes_36k_train_000386 | 4,330 | no_license | [
{
"docstring": "Find the minimum effort required to get from top-left corner of heights to lower-right :param heights: rectangular-like map represented as list of lists :return: the minimum effort required Time complexity: O(mn * log(var)), where the heights is m-by-n board and var is the spread of values in he... | 2 | stack_v2_sparse_classes_30k_train_021288 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumEffortPath(self, heights: List[List[int]]) -> int: Find the minimum effort required to get from top-left corner of heights to lower-right :param heights: rectangular-l... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumEffortPath(self, heights: List[List[int]]) -> int: Find the minimum effort required to get from top-left corner of heights to lower-right :param heights: rectangular-l... | ee8237b66975fb5584a3d68b311e762c0462c8aa | <|skeleton|>
class Solution:
def minimumEffortPath(self, heights: List[List[int]]) -> int:
"""Find the minimum effort required to get from top-left corner of heights to lower-right :param heights: rectangular-like map represented as list of lists :return: the minimum effort required Time complexity: O(mn *... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minimumEffortPath(self, heights: List[List[int]]) -> int:
"""Find the minimum effort required to get from top-left corner of heights to lower-right :param heights: rectangular-like map represented as list of lists :return: the minimum effort required Time complexity: O(mn * log(var)), wh... | the_stack_v2_python_sparse | LC1631-Path-With-Minimum-Effort.py | kate-melnykova/LeetCode-solutions | train | 2 | |
14f58c051bd45199cc2f55a79f4e9885f8a9c5e8 | [
"if not fe:\n logging.info(f'Stage {stage.key.integer_id()} has no feature entry')\n return []\nif fe.feature_type not in self.GATE_RULES:\n logging.info(f'Skipping stage of bad feature {fe.key.integer_id()}')\n return []\nif stage.stage_type not in self.GATE_RULES[fe.feature_type]:\n logging.info(f'... | <|body_start_0|>
if not fe:
logging.info(f'Stage {stage.key.integer_id()} has no feature entry')
return []
if fe.feature_type not in self.GATE_RULES:
logging.info(f'Skipping stage of bad feature {fe.key.integer_id()}')
return []
if stage.stage_type... | WriteMissingGates | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WriteMissingGates:
def make_needed_gates(self, fe, stage, existing_gates):
"""Instantiate and return any needed gates for the given stage."""
<|body_0|>
def get_template_data(self, **kwargs):
"""Create a chunk of needed gates for all features."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_000387 | 7,549 | permissive | [
{
"docstring": "Instantiate and return any needed gates for the given stage.",
"name": "make_needed_gates",
"signature": "def make_needed_gates(self, fe, stage, existing_gates)"
},
{
"docstring": "Create a chunk of needed gates for all features.",
"name": "get_template_data",
"signature"... | 2 | stack_v2_sparse_classes_30k_train_005571 | Implement the Python class `WriteMissingGates` described below.
Class description:
Implement the WriteMissingGates class.
Method signatures and docstrings:
- def make_needed_gates(self, fe, stage, existing_gates): Instantiate and return any needed gates for the given stage.
- def get_template_data(self, **kwargs): Cr... | Implement the Python class `WriteMissingGates` described below.
Class description:
Implement the WriteMissingGates class.
Method signatures and docstrings:
- def make_needed_gates(self, fe, stage, existing_gates): Instantiate and return any needed gates for the given stage.
- def get_template_data(self, **kwargs): Cr... | 17f9886d064da5bda84006d5866077727646fff2 | <|skeleton|>
class WriteMissingGates:
def make_needed_gates(self, fe, stage, existing_gates):
"""Instantiate and return any needed gates for the given stage."""
<|body_0|>
def get_template_data(self, **kwargs):
"""Create a chunk of needed gates for all features."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WriteMissingGates:
def make_needed_gates(self, fe, stage, existing_gates):
"""Instantiate and return any needed gates for the given stage."""
if not fe:
logging.info(f'Stage {stage.key.integer_id()} has no feature entry')
return []
if fe.feature_type not in self... | the_stack_v2_python_sparse | internals/maintenance_scripts.py | GoogleChrome/chromium-dashboard | train | 574 | |
eddc8eb62a93f89b2879a81c80c054cfb626ec9a | [
"t = TableFu(self.csv_file, sorted_by={'Author': {'reverse': True}})\nself.table.pop(0)\nself.table.sort(key=lambda row: row[0], reverse=True)\nself.assertEqual(t[0].cells, self.table[0])",
"t = TableFu(self.csv_file)\npages = t.values('Number of Pages')\npages = sorted(pages, reverse=True)\nt.sort('Number of Pag... | <|body_start_0|>
t = TableFu(self.csv_file, sorted_by={'Author': {'reverse': True}})
self.table.pop(0)
self.table.sort(key=lambda row: row[0], reverse=True)
self.assertEqual(t[0].cells, self.table[0])
<|end_body_0|>
<|body_start_1|>
t = TableFu(self.csv_file)
pages = t.v... | OptionsTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptionsTest:
def test_sort_option_str(self):
"""Sort the table by a string field, Author"""
<|body_0|>
def test_sort_option_int(self):
"""Sorting the table by an int field, Number of Pages"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
t = TableFu(... | stack_v2_sparse_classes_36k_train_000388 | 30,557 | no_license | [
{
"docstring": "Sort the table by a string field, Author",
"name": "test_sort_option_str",
"signature": "def test_sort_option_str(self)"
},
{
"docstring": "Sorting the table by an int field, Number of Pages",
"name": "test_sort_option_int",
"signature": "def test_sort_option_int(self)"
... | 2 | null | Implement the Python class `OptionsTest` described below.
Class description:
Implement the OptionsTest class.
Method signatures and docstrings:
- def test_sort_option_str(self): Sort the table by a string field, Author
- def test_sort_option_int(self): Sorting the table by an int field, Number of Pages | Implement the Python class `OptionsTest` described below.
Class description:
Implement the OptionsTest class.
Method signatures and docstrings:
- def test_sort_option_str(self): Sort the table by a string field, Author
- def test_sort_option_int(self): Sorting the table by an int field, Number of Pages
<|skeleton|>
... | 0ac6653219c2701c13c508c5c4fc9bc3437eea06 | <|skeleton|>
class OptionsTest:
def test_sort_option_str(self):
"""Sort the table by a string field, Author"""
<|body_0|>
def test_sort_option_int(self):
"""Sorting the table by an int field, Number of Pages"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OptionsTest:
def test_sort_option_str(self):
"""Sort the table by a string field, Author"""
t = TableFu(self.csv_file, sorted_by={'Author': {'reverse': True}})
self.table.pop(0)
self.table.sort(key=lambda row: row[0], reverse=True)
self.assertEqual(t[0].cells, self.tabl... | the_stack_v2_python_sparse | repoData/eyeseast-python-tablefu/allPythonContent.py | aCoffeeYin/pyreco | train | 0 | |
985c1981365a5c9e7c886a5077741b078bd2fca3 | [
"self.seed = seed\nself.vocab = vocab\nself.gramm = gramm\nself.axiom = axiom\nself.n = n\nself.word = self.iterate()\nself.gramm_str = utility.list_to_str([i[0] + ' -> ' + i[1] for i in self.gramm], '\\n')",
"r = 'Grammar:\\n{}\\n'.format(self.gramm_str)\nr += 'Axiom: {}\\n'.format(self.axiom)\nr ... | <|body_start_0|>
self.seed = seed
self.vocab = vocab
self.gramm = gramm
self.axiom = axiom
self.n = n
self.word = self.iterate()
self.gramm_str = utility.list_to_str([i[0] + ' -> ' + i[1] for i in self.gramm], '\n')
<|end_body_0|>
<|body_start_1|>
r = 'Gr... | Lindenmayer system class | lsystem | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class lsystem:
"""Lindenmayer system class"""
def __init__(self, vocab: vocabulary, gramm: list, axiom: str, n: int, seed: int=None) -> None:
"""Lindenmayer system parameters Parameters ---------- vocab : vocabulary The vocabulary of the L-system gramm : list The grammatical rules of the L... | stack_v2_sparse_classes_36k_train_000389 | 18,172 | permissive | [
{
"docstring": "Lindenmayer system parameters Parameters ---------- vocab : vocabulary The vocabulary of the L-system gramm : list The grammatical rules of the L-system axiom : str The initial axiom of the L-system n : int The number of iterations of the L-system seed : int, optional The seed for the random gen... | 5 | stack_v2_sparse_classes_30k_train_019137 | Implement the Python class `lsystem` described below.
Class description:
Lindenmayer system class
Method signatures and docstrings:
- def __init__(self, vocab: vocabulary, gramm: list, axiom: str, n: int, seed: int=None) -> None: Lindenmayer system parameters Parameters ---------- vocab : vocabulary The vocabulary of... | Implement the Python class `lsystem` described below.
Class description:
Lindenmayer system class
Method signatures and docstrings:
- def __init__(self, vocab: vocabulary, gramm: list, axiom: str, n: int, seed: int=None) -> None: Lindenmayer system parameters Parameters ---------- vocab : vocabulary The vocabulary of... | b47e951cc465f1d2d6ca4384b2bce05c6e96e2a0 | <|skeleton|>
class lsystem:
"""Lindenmayer system class"""
def __init__(self, vocab: vocabulary, gramm: list, axiom: str, n: int, seed: int=None) -> None:
"""Lindenmayer system parameters Parameters ---------- vocab : vocabulary The vocabulary of the L-system gramm : list The grammatical rules of the L... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class lsystem:
"""Lindenmayer system class"""
def __init__(self, vocab: vocabulary, gramm: list, axiom: str, n: int, seed: int=None) -> None:
"""Lindenmayer system parameters Parameters ---------- vocab : vocabulary The vocabulary of the L-system gramm : list The grammatical rules of the L-system axiom... | the_stack_v2_python_sparse | Models/MarcMentat/evolve_soft_2d/evolve/lsystems.py | martinventer/Naude_Masters-Project | train | 0 |
f3de7aa483b8b90e9d885d8ddf8731b41cfd2e2e | [
"self.input = input()\nif not check_input(self.input):\n raise Exception\nself.bus_times = {}\nwith open(file) as data:\n for lines in data:\n lines = lines.strip()\n list1 = lines.split('\\t')[0]\n self.bus_times[list1] = ' '.join(lines.split('\\t')[1:]).split(' ')",
"hour = int(self.i... | <|body_start_0|>
self.input = input()
if not check_input(self.input):
raise Exception
self.bus_times = {}
with open(file) as data:
for lines in data:
lines = lines.strip()
list1 = lines.split('\t')[0]
self.bus_times[... | Main class where magic happens. | Main | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Main:
"""Main class where magic happens."""
def __init__(self, file: str):
"""Class constructor. :param file: File with bus times."""
<|body_0|>
def get_departure_time(self):
"""Find next departure time and print it. :return:"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k_train_000390 | 3,214 | no_license | [
{
"docstring": "Class constructor. :param file: File with bus times.",
"name": "__init__",
"signature": "def __init__(self, file: str)"
},
{
"docstring": "Find next departure time and print it. :return:",
"name": "get_departure_time",
"signature": "def get_departure_time(self)"
}
] | 2 | null | Implement the Python class `Main` described below.
Class description:
Main class where magic happens.
Method signatures and docstrings:
- def __init__(self, file: str): Class constructor. :param file: File with bus times.
- def get_departure_time(self): Find next departure time and print it. :return: | Implement the Python class `Main` described below.
Class description:
Main class where magic happens.
Method signatures and docstrings:
- def __init__(self, file: str): Class constructor. :param file: File with bus times.
- def get_departure_time(self): Find next departure time and print it. :return:
<|skeleton|>
cl... | fc18a82f9911194a6f7e73bf081422adc06a1177 | <|skeleton|>
class Main:
"""Main class where magic happens."""
def __init__(self, file: str):
"""Class constructor. :param file: File with bus times."""
<|body_0|>
def get_departure_time(self):
"""Find next departure time and print it. :return:"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Main:
"""Main class where magic happens."""
def __init__(self, file: str):
"""Class constructor. :param file: File with bus times."""
self.input = input()
if not check_input(self.input):
raise Exception
self.bus_times = {}
with open(file) as data:
... | the_stack_v2_python_sparse | iti0102/EX15A/bus.py | NikitaKums/TalTech | train | 0 |
1bd24d00624f132ae27aaf4be75706fee7a4386a | [
"self.origine = origine\nself.x = axex\nself.y = axey\nself.z = axez",
"res = copy.copy(self.origine)\nres.x += v.x * self.x.x + v.y * self.y.x + v.z * self.z.x\nres.y += v.x * self.x.y + v.y * self.y.y + v.z * self.z.y\nres.z += v.x * self.x.z + v.y * self.y.z + v.z * self.z.z\nreturn res",
"s = 'origine : ' +... | <|body_start_0|>
self.origine = origine
self.x = axex
self.y = axey
self.z = axez
<|end_body_0|>
<|body_start_1|>
res = copy.copy(self.origine)
res.x += v.x * self.x.x + v.y * self.y.x + v.z * self.z.x
res.y += v.x * self.x.y + v.y * self.y.y + v.z * self.z.y
... | dfinition d'un repre orthonorm | repere | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class repere:
"""dfinition d'un repre orthonorm"""
def __init__(self, origine=vecteur(0, 0, 0), axex=vecteur(1, 0, 0), axey=vecteur(0, 1, 0), axez=vecteur(0, 0, 1)):
"""initialisation, origine et les trois axes"""
<|body_0|>
def coordonnees(self, v):
"""on suppose que ... | stack_v2_sparse_classes_36k_train_000391 | 9,439 | permissive | [
{
"docstring": "initialisation, origine et les trois axes",
"name": "__init__",
"signature": "def __init__(self, origine=vecteur(0, 0, 0), axex=vecteur(1, 0, 0), axey=vecteur(0, 1, 0), axez=vecteur(0, 0, 1))"
},
{
"docstring": "on suppose que les coordonnes de v sont exprimes dans ce repre, calc... | 3 | null | Implement the Python class `repere` described below.
Class description:
dfinition d'un repre orthonorm
Method signatures and docstrings:
- def __init__(self, origine=vecteur(0, 0, 0), axex=vecteur(1, 0, 0), axey=vecteur(0, 1, 0), axez=vecteur(0, 0, 1)): initialisation, origine et les trois axes
- def coordonnees(self... | Implement the Python class `repere` described below.
Class description:
dfinition d'un repre orthonorm
Method signatures and docstrings:
- def __init__(self, origine=vecteur(0, 0, 0), axex=vecteur(1, 0, 0), axey=vecteur(0, 1, 0), axez=vecteur(0, 0, 1)): initialisation, origine et les trois axes
- def coordonnees(self... | 2abbc7a20c7437f9ab91d1ec83a6aecdefceb028 | <|skeleton|>
class repere:
"""dfinition d'un repre orthonorm"""
def __init__(self, origine=vecteur(0, 0, 0), axex=vecteur(1, 0, 0), axey=vecteur(0, 1, 0), axez=vecteur(0, 0, 1)):
"""initialisation, origine et les trois axes"""
<|body_0|>
def coordonnees(self, v):
"""on suppose que ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class repere:
"""dfinition d'un repre orthonorm"""
def __init__(self, origine=vecteur(0, 0, 0), axex=vecteur(1, 0, 0), axey=vecteur(0, 1, 0), axez=vecteur(0, 0, 1)):
"""initialisation, origine et les trois axes"""
self.origine = origine
self.x = axex
self.y = axey
self.z... | the_stack_v2_python_sparse | _todo/programme/image_synthese_base.py | Pandinosaurus/ensae_teaching_cs | train | 1 |
52d01e865c8aad19bfa80344cb934be78737652d | [
"pc = self._entity_manager.pc\npc_fatigue = self._entity_manager.get_component(pc, FatigueComponent)\nif pc_fatigue.fatigue > 0:\n return\nevent.dispatch(PreInputEvent())\nkey = self.get_keypress()\nif key == libtcod.KEY_ESCAPE or libtcod.console_is_window_closed():\n event.dispatch(QuitEvent())\nif key in se... | <|body_start_0|>
pc = self._entity_manager.pc
pc_fatigue = self._entity_manager.get_component(pc, FatigueComponent)
if pc_fatigue.fatigue > 0:
return
event.dispatch(PreInputEvent())
key = self.get_keypress()
if key == libtcod.KEY_ESCAPE or libtcod.console_is_w... | InputSystem | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InputSystem:
def execute(self):
"""Wait for player input, dispatching appropriate events."""
<|body_0|>
def get_keypress(self):
"""Wrapper method for retrieving keypress events from the keyboard A bug(?) in libtcod means that the wait_for_keypress function actually r... | stack_v2_sparse_classes_36k_train_000392 | 3,339 | permissive | [
{
"docstring": "Wait for player input, dispatching appropriate events.",
"name": "execute",
"signature": "def execute(self)"
},
{
"docstring": "Wrapper method for retrieving keypress events from the keyboard A bug(?) in libtcod means that the wait_for_keypress function actually returns key press... | 2 | stack_v2_sparse_classes_30k_train_000559 | Implement the Python class `InputSystem` described below.
Class description:
Implement the InputSystem class.
Method signatures and docstrings:
- def execute(self): Wait for player input, dispatching appropriate events.
- def get_keypress(self): Wrapper method for retrieving keypress events from the keyboard A bug(?)... | Implement the Python class `InputSystem` described below.
Class description:
Implement the InputSystem class.
Method signatures and docstrings:
- def execute(self): Wait for player input, dispatching appropriate events.
- def get_keypress(self): Wrapper method for retrieving keypress events from the keyboard A bug(?)... | b76202af71df0c30be0bd5f06a3428c990476e0e | <|skeleton|>
class InputSystem:
def execute(self):
"""Wait for player input, dispatching appropriate events."""
<|body_0|>
def get_keypress(self):
"""Wrapper method for retrieving keypress events from the keyboard A bug(?) in libtcod means that the wait_for_keypress function actually r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InputSystem:
def execute(self):
"""Wait for player input, dispatching appropriate events."""
pc = self._entity_manager.pc
pc_fatigue = self._entity_manager.get_component(pc, FatigueComponent)
if pc_fatigue.fatigue > 0:
return
event.dispatch(PreInputEvent())
... | the_stack_v2_python_sparse | roglick/systems/input.py | Kromey/roglick | train | 6 | |
f33f27ef0913bd9cccf0bad5f0936e39d5243f70 | [
"input_text = '[[foo]\\n bar] [[baz]]'\noutput = singhtext.text_to_html(input_text)\nassert ('[[' in output) == False, 'Multi-line links fail.'",
"input_text = '\\n$foo\\n== bar ==\\nbaz\\n'\ncorrect_output = '<h2> bar </h2>\\n<p>baz</p>'\nactual_output = singhtext.text_to_html(input_text)\nassert 'bar' in actual... | <|body_start_0|>
input_text = '[[foo]\n bar] [[baz]]'
output = singhtext.text_to_html(input_text)
assert ('[[' in output) == False, 'Multi-line links fail.'
<|end_body_0|>
<|body_start_1|>
input_text = '\n$foo\n== bar ==\nbaz\n'
correct_output = '<h2> bar </h2>\n<p>baz</p>'
... | Test SinghText HTML generation. testMultilineLinks - links that span multiple lines testSpecialLineInterference - $special intefere with headers? | StringMatchingTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StringMatchingTests:
"""Test SinghText HTML generation. testMultilineLinks - links that span multiple lines testSpecialLineInterference - $special intefere with headers?"""
def testMultilineLinks(self):
"""Test links that span multiple lines, another way."""
<|body_0|>
d... | stack_v2_sparse_classes_36k_train_000393 | 3,509 | no_license | [
{
"docstring": "Test links that span multiple lines, another way.",
"name": "testMultilineLinks",
"signature": "def testMultilineLinks(self)"
},
{
"docstring": "Make sure special lines don't interfere with headers.",
"name": "testSpecialLineInterference",
"signature": "def testSpecialLin... | 4 | stack_v2_sparse_classes_30k_train_003449 | Implement the Python class `StringMatchingTests` described below.
Class description:
Test SinghText HTML generation. testMultilineLinks - links that span multiple lines testSpecialLineInterference - $special intefere with headers?
Method signatures and docstrings:
- def testMultilineLinks(self): Test links that span ... | Implement the Python class `StringMatchingTests` described below.
Class description:
Test SinghText HTML generation. testMultilineLinks - links that span multiple lines testSpecialLineInterference - $special intefere with headers?
Method signatures and docstrings:
- def testMultilineLinks(self): Test links that span ... | da65d948b346d3f455e79168a8753b2b16d8fc5f | <|skeleton|>
class StringMatchingTests:
"""Test SinghText HTML generation. testMultilineLinks - links that span multiple lines testSpecialLineInterference - $special intefere with headers?"""
def testMultilineLinks(self):
"""Test links that span multiple lines, another way."""
<|body_0|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StringMatchingTests:
"""Test SinghText HTML generation. testMultilineLinks - links that span multiple lines testSpecialLineInterference - $special intefere with headers?"""
def testMultilineLinks(self):
"""Test links that span multiple lines, another way."""
input_text = '[[foo]\n bar] [[... | the_stack_v2_python_sparse | other/singhtext/test.py | BackupTheBerlios/onebigsoup-svn | train | 0 |
4531302889252776345ebf63ca0c94bf352152a7 | [
"super(rdma_core, self).__init__(**kwargs)\nself.__baseurl = kwargs.pop('baseurl', 'https://github.com/linux-rdma/rdma-core/archive')\nself.__default_repository = 'https://github.com/linux-rdma/rdma-core.git'\nself.__ospackages = kwargs.pop('ospackages', [])\nself.__prefix = kwargs.pop('prefix', '/usr/local/rdma-co... | <|body_start_0|>
super(rdma_core, self).__init__(**kwargs)
self.__baseurl = kwargs.pop('baseurl', 'https://github.com/linux-rdma/rdma-core/archive')
self.__default_repository = 'https://github.com/linux-rdma/rdma-core.git'
self.__ospackages = kwargs.pop('ospackages', [])
self.__p... | The `rdma_core` building block configures, builds, and installs the [RDMA Core](https://github.com/linux-rdma/rdma-core) component. The [CMake](#cmake) building block should be installed prior to this building block. # Parameters annotate: Boolean flag to specify whether to include annotations (labels). The default is ... | rdma_core | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class rdma_core:
"""The `rdma_core` building block configures, builds, and installs the [RDMA Core](https://github.com/linux-rdma/rdma-core) component. The [CMake](#cmake) building block should be installed prior to this building block. # Parameters annotate: Boolean flag to specify whether to include ... | stack_v2_sparse_classes_36k_train_000394 | 9,309 | permissive | [
{
"docstring": "Initialize building block",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Based on the Linux distribution, set values accordingly. A user specified value overrides any defaults.",
"name": "__distro",
"signature": "def __distro(self)"
... | 4 | stack_v2_sparse_classes_30k_val_000459 | Implement the Python class `rdma_core` described below.
Class description:
The `rdma_core` building block configures, builds, and installs the [RDMA Core](https://github.com/linux-rdma/rdma-core) component. The [CMake](#cmake) building block should be installed prior to this building block. # Parameters annotate: Bool... | Implement the Python class `rdma_core` described below.
Class description:
The `rdma_core` building block configures, builds, and installs the [RDMA Core](https://github.com/linux-rdma/rdma-core) component. The [CMake](#cmake) building block should be installed prior to this building block. # Parameters annotate: Bool... | 60fd2a51c171258a6b3f93c2523101cb7018ba1b | <|skeleton|>
class rdma_core:
"""The `rdma_core` building block configures, builds, and installs the [RDMA Core](https://github.com/linux-rdma/rdma-core) component. The [CMake](#cmake) building block should be installed prior to this building block. # Parameters annotate: Boolean flag to specify whether to include ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class rdma_core:
"""The `rdma_core` building block configures, builds, and installs the [RDMA Core](https://github.com/linux-rdma/rdma-core) component. The [CMake](#cmake) building block should be installed prior to this building block. # Parameters annotate: Boolean flag to specify whether to include annotations (... | the_stack_v2_python_sparse | hpccm/building_blocks/rdma_core.py | NVIDIA/hpc-container-maker | train | 419 |
f12f8afcf191d78c912a5d274a50189ab3ade460 | [
"crypto_power = CryptoPower(power_ups=Ursula._default_crypto_powerups)\nif claim_signing_key:\n crypto_power.consume_power_up(SigningPower(pubkey=target_ursula.stamp.as_umbral_pubkey()))\nvladimir = cls(crypto_power=crypto_power, rest_host=target_ursula.rest_information()[0].host, rest_port=target_ursula.rest_in... | <|body_start_0|>
crypto_power = CryptoPower(power_ups=Ursula._default_crypto_powerups)
if claim_signing_key:
crypto_power.consume_power_up(SigningPower(pubkey=target_ursula.stamp.as_umbral_pubkey()))
vladimir = cls(crypto_power=crypto_power, rest_host=target_ursula.rest_information()... | The power of Ursula, but with a heart forged deep in the mountains of Microsoft or a State Actor or whatever. | Vladimir | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vladimir:
"""The power of Ursula, but with a heart forged deep in the mountains of Microsoft or a State Actor or whatever."""
def from_target_ursula(cls, target_ursula, claim_signing_key=False):
"""Sometimes Vladimir seeks to attack or imitate a *specific* target Ursula. TODO: This i... | stack_v2_sparse_classes_36k_train_000395 | 2,381 | no_license | [
{
"docstring": "Sometimes Vladimir seeks to attack or imitate a *specific* target Ursula. TODO: This is probably a more instructive method if it takes a bytes representation instead of the entire Ursula.",
"name": "from_target_ursula",
"signature": "def from_target_ursula(cls, target_ursula, claim_signi... | 2 | stack_v2_sparse_classes_30k_train_009384 | Implement the Python class `Vladimir` described below.
Class description:
The power of Ursula, but with a heart forged deep in the mountains of Microsoft or a State Actor or whatever.
Method signatures and docstrings:
- def from_target_ursula(cls, target_ursula, claim_signing_key=False): Sometimes Vladimir seeks to a... | Implement the Python class `Vladimir` described below.
Class description:
The power of Ursula, but with a heart forged deep in the mountains of Microsoft or a State Actor or whatever.
Method signatures and docstrings:
- def from_target_ursula(cls, target_ursula, claim_signing_key=False): Sometimes Vladimir seeks to a... | 9a8a5ba75c04e14d5f393ebd0a626c046948c003 | <|skeleton|>
class Vladimir:
"""The power of Ursula, but with a heart forged deep in the mountains of Microsoft or a State Actor or whatever."""
def from_target_ursula(cls, target_ursula, claim_signing_key=False):
"""Sometimes Vladimir seeks to attack or imitate a *specific* target Ursula. TODO: This i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Vladimir:
"""The power of Ursula, but with a heart forged deep in the mountains of Microsoft or a State Actor or whatever."""
def from_target_ursula(cls, target_ursula, claim_signing_key=False):
"""Sometimes Vladimir seeks to attack or imitate a *specific* target Ursula. TODO: This is probably a ... | the_stack_v2_python_sparse | nucypher/characters/unlawful.py | OnGridSystems/nucypher | train | 0 |
aa7029f71aa4f657ea5e28c5908cc715e9b77802 | [
"res = 0\nfor i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 1:\n self.step = 0\n self.dfs(grid, i, j)\n res = max(res, self.step)\nreturn res",
"if x < 0 or y < 0 or x > len(grid) - 1 or (y > len(grid[0]) - 1) or (grid[x][y] != 1):\n return... | <|body_start_0|>
res = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
self.step = 0
self.dfs(grid, i, j)
res = max(res, self.step)
return res
<|end_body_0|>
<|body_start_1|>
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxAreaOfIsland(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_0|>
def dfs(self, grid, x, y):
""":type grid: List[list[int]] :type x: int :type y: int :rtype : None"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res... | stack_v2_sparse_classes_36k_train_000396 | 1,685 | permissive | [
{
"docstring": ":type grid: List[List[int]] :rtype: int",
"name": "maxAreaOfIsland",
"signature": "def maxAreaOfIsland(self, grid)"
},
{
"docstring": ":type grid: List[list[int]] :type x: int :type y: int :rtype : None",
"name": "dfs",
"signature": "def dfs(self, grid, x, y)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019028 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxAreaOfIsland(self, grid): :type grid: List[List[int]] :rtype: int
- def dfs(self, grid, x, y): :type grid: List[list[int]] :type x: int :type y: int :rtype : None | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxAreaOfIsland(self, grid): :type grid: List[List[int]] :rtype: int
- def dfs(self, grid, x, y): :type grid: List[list[int]] :type x: int :type y: int :rtype : None
<|skele... | 55c6c3e7890b596b709b50cafa415b9594c03edd | <|skeleton|>
class Solution:
def maxAreaOfIsland(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_0|>
def dfs(self, grid, x, y):
""":type grid: List[list[int]] :type x: int :type y: int :rtype : None"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxAreaOfIsland(self, grid):
""":type grid: List[List[int]] :rtype: int"""
res = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
self.step = 0
self.dfs(grid, i, j)
... | the_stack_v2_python_sparse | max-area-of-island.py | summer-vacation/AlgoExec | train | 1 | |
4dc8a0b9660f502ad1930bac172cb28aa2676cf7 | [
"if not self.qf.is_recurrent:\n return super().get_critic_output_dict(subtraj_batch)\nrewards = subtraj_batch['rewards']\nterminals = subtraj_batch['terminals']\nobs = subtraj_batch['env_obs']\nactions = subtraj_batch['env_actions']\nnext_obs = subtraj_batch['next_env_obs']\nmemories = subtraj_batch['memories']\... | <|body_start_0|>
if not self.qf.is_recurrent:
return super().get_critic_output_dict(subtraj_batch)
rewards = subtraj_batch['rewards']
terminals = subtraj_batch['terminals']
obs = subtraj_batch['env_obs']
actions = subtraj_batch['env_actions']
next_obs = subtra... | Same as BpttDdpg, but with a recurrent Q function | BpttDdpgRecurrentQ | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BpttDdpgRecurrentQ:
"""Same as BpttDdpg, but with a recurrent Q function"""
def get_critic_output_dict(self, subtraj_batch):
""":param subtraj_batch: A tensor subtrajectory dict. Basically, it should be the output of `create_torch_subtraj_batch` :return: Dictionary containing Variabl... | stack_v2_sparse_classes_36k_train_000397 | 4,610 | permissive | [
{
"docstring": ":param subtraj_batch: A tensor subtrajectory dict. Basically, it should be the output of `create_torch_subtraj_batch` :return: Dictionary containing Variables/Tensors for training the critic, including intermediate values that might be useful to log.",
"name": "get_critic_output_dict",
"... | 2 | null | Implement the Python class `BpttDdpgRecurrentQ` described below.
Class description:
Same as BpttDdpg, but with a recurrent Q function
Method signatures and docstrings:
- def get_critic_output_dict(self, subtraj_batch): :param subtraj_batch: A tensor subtrajectory dict. Basically, it should be the output of `create_to... | Implement the Python class `BpttDdpgRecurrentQ` described below.
Class description:
Same as BpttDdpg, but with a recurrent Q function
Method signatures and docstrings:
- def get_critic_output_dict(self, subtraj_batch): :param subtraj_batch: A tensor subtrajectory dict. Basically, it should be the output of `create_to... | baba8ce634d32a48c7dfe4dc03b123e18e96e0a3 | <|skeleton|>
class BpttDdpgRecurrentQ:
"""Same as BpttDdpg, but with a recurrent Q function"""
def get_critic_output_dict(self, subtraj_batch):
""":param subtraj_batch: A tensor subtrajectory dict. Basically, it should be the output of `create_torch_subtraj_batch` :return: Dictionary containing Variabl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BpttDdpgRecurrentQ:
"""Same as BpttDdpg, but with a recurrent Q function"""
def get_critic_output_dict(self, subtraj_batch):
""":param subtraj_batch: A tensor subtrajectory dict. Basically, it should be the output of `create_torch_subtraj_batch` :return: Dictionary containing Variables/Tensors fo... | the_stack_v2_python_sparse | rlkit/memory_states/bptt_ddpg_rq.py | Asap7772/railrl_evalsawyer | train | 1 |
d9104b6c4e964e4ff11a1a6cd20bb28e199ade52 | [
"self.name = name\nself.cmd = name.split()\nself.shfile = shfile\nself.optional = optional or []\nself.environment = self._environment()\nif cpus is not None:\n self.environment['FSLPARALLEL'] = cpus\n self.environment['USER'] = os.getlogin()\n process = subprocess.Popen(['which', 'condor_qsub'], env=self.... | <|body_start_0|>
self.name = name
self.cmd = name.split()
self.shfile = shfile
self.optional = optional or []
self.environment = self._environment()
if cpus is not None:
self.environment['FSLPARALLEL'] = cpus
self.environment['USER'] = os.getlogin(... | Parent class for the wrapping of FSL functions. | FSLWrapper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FSLWrapper:
"""Parent class for the wrapping of FSL functions."""
def __init__(self, name, shfile='/etc/fsl/5.0/fsl.sh', optional=None, cpus=None):
"""Initialize the FSLWrapper class by setting properly the environment. Parameters ---------- name: str (mandatory) the name of the FSL ... | stack_v2_sparse_classes_36k_train_000398 | 5,850 | no_license | [
{
"docstring": "Initialize the FSLWrapper class by setting properly the environment. Parameters ---------- name: str (mandatory) the name of the FSL binary to be called. shfile: str (optional, default NeuroSpin path) the path to the FSL 'fsl.sh' configuration file. optional: list (optional, default None) the na... | 4 | stack_v2_sparse_classes_30k_train_000871 | Implement the Python class `FSLWrapper` described below.
Class description:
Parent class for the wrapping of FSL functions.
Method signatures and docstrings:
- def __init__(self, name, shfile='/etc/fsl/5.0/fsl.sh', optional=None, cpus=None): Initialize the FSLWrapper class by setting properly the environment. Paramet... | Implement the Python class `FSLWrapper` described below.
Class description:
Parent class for the wrapping of FSL functions.
Method signatures and docstrings:
- def __init__(self, name, shfile='/etc/fsl/5.0/fsl.sh', optional=None, cpus=None): Initialize the FSLWrapper class by setting properly the environment. Paramet... | 02d5e94dce362b2f99dedf486e5342f98af17af4 | <|skeleton|>
class FSLWrapper:
"""Parent class for the wrapping of FSL functions."""
def __init__(self, name, shfile='/etc/fsl/5.0/fsl.sh', optional=None, cpus=None):
"""Initialize the FSLWrapper class by setting properly the environment. Parameters ---------- name: str (mandatory) the name of the FSL ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FSLWrapper:
"""Parent class for the wrapping of FSL functions."""
def __init__(self, name, shfile='/etc/fsl/5.0/fsl.sh', optional=None, cpus=None):
"""Initialize the FSLWrapper class by setting properly the environment. Parameters ---------- name: str (mandatory) the name of the FSL binary to be ... | the_stack_v2_python_sparse | clindmri/extensions/fsl/wrappers.py | dgoyard/caps-clindmri | train | 0 |
8828e66fe2db9dc500c592a04008f0b9a3720fe6 | [
"env = ZerosEnvironment(batch_size=batch_size, observation_shape=observation_shape)\n\n@common.function\ndef observation_and_reward():\n observation = env.reset().observation\n reward = env.step(tf.zeros(batch_size)).reward\n return (observation, reward)\nobservation, reward = observation_and_reward()\nexp... | <|body_start_0|>
env = ZerosEnvironment(batch_size=batch_size, observation_shape=observation_shape)
@common.function
def observation_and_reward():
observation = env.reset().observation
reward = env.step(tf.zeros(batch_size)).reward
return (observation, reward... | BanditTFEnvironmentTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BanditTFEnvironmentTest:
def testObservationAndRewardShapes(self, batch_size, observation_shape):
"""Exercise `reset` and `step`. Ensure correct shapes are returned."""
<|body_0|>
def testTwoConsecutiveSteps(self, batch_size, observation_shape):
"""Test two consecuti... | stack_v2_sparse_classes_36k_train_000399 | 5,763 | permissive | [
{
"docstring": "Exercise `reset` and `step`. Ensure correct shapes are returned.",
"name": "testObservationAndRewardShapes",
"signature": "def testObservationAndRewardShapes(self, batch_size, observation_shape)"
},
{
"docstring": "Test two consecutive calls to `step`.",
"name": "testTwoConse... | 3 | stack_v2_sparse_classes_30k_train_004785 | Implement the Python class `BanditTFEnvironmentTest` described below.
Class description:
Implement the BanditTFEnvironmentTest class.
Method signatures and docstrings:
- def testObservationAndRewardShapes(self, batch_size, observation_shape): Exercise `reset` and `step`. Ensure correct shapes are returned.
- def test... | Implement the Python class `BanditTFEnvironmentTest` described below.
Class description:
Implement the BanditTFEnvironmentTest class.
Method signatures and docstrings:
- def testObservationAndRewardShapes(self, batch_size, observation_shape): Exercise `reset` and `step`. Ensure correct shapes are returned.
- def test... | eca1093d3a047e538f17f6ab92ab4d8144284f23 | <|skeleton|>
class BanditTFEnvironmentTest:
def testObservationAndRewardShapes(self, batch_size, observation_shape):
"""Exercise `reset` and `step`. Ensure correct shapes are returned."""
<|body_0|>
def testTwoConsecutiveSteps(self, batch_size, observation_shape):
"""Test two consecuti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BanditTFEnvironmentTest:
def testObservationAndRewardShapes(self, batch_size, observation_shape):
"""Exercise `reset` and `step`. Ensure correct shapes are returned."""
env = ZerosEnvironment(batch_size=batch_size, observation_shape=observation_shape)
@common.function
def obse... | the_stack_v2_python_sparse | tf_agents/bandits/environments/bandit_tf_environment_test.py | tensorflow/agents | train | 2,755 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.