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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ce93973ab1a7250ee1f45e7d76731bae1d1fdd83 | [
"type_str = self.cleaned_data['type']\ntry:\n Cvterm.objects.get(name=self.cleaned_data['type'].split(',')[0])\nexcept Cvterm.DoesNotExist:\n raise ValidationError('This type does not exist in the database')\nreturn type_str",
"vector = self.cleaned_data['vector']\nerror_in_type = self.errors.get('type', Fa... | <|body_start_0|>
type_str = self.cleaned_data['type']
try:
Cvterm.objects.get(name=self.cleaned_data['type'].split(',')[0])
except Cvterm.DoesNotExist:
raise ValidationError('This type does not exist in the database')
return type_str
<|end_body_0|>
<|body_start_1... | Form to add features to db | FeatureForm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureForm:
"""Form to add features to db"""
def clean_type(self):
"""It validates the type field"""
<|body_0|>
def clean_vector(self):
"""It validates the vector. If the feature is a vector it does not validate anything if feature is not a vector if validates t... | stack_v2_sparse_classes_36k_train_023200 | 7,506 | permissive | [
{
"docstring": "It validates the type field",
"name": "clean_type",
"signature": "def clean_type(self)"
},
{
"docstring": "It validates the vector. If the feature is a vector it does not validate anything if feature is not a vector if validates that the vector is in the database",
"name": "c... | 2 | stack_v2_sparse_classes_30k_train_014381 | Implement the Python class `FeatureForm` described below.
Class description:
Form to add features to db
Method signatures and docstrings:
- def clean_type(self): It validates the type field
- def clean_vector(self): It validates the vector. If the feature is a vector it does not validate anything if feature is not a ... | Implement the Python class `FeatureForm` described below.
Class description:
Form to add features to db
Method signatures and docstrings:
- def clean_type(self): It validates the type field
- def clean_vector(self): It validates the vector. If the feature is a vector it does not validate anything if feature is not a ... | 7a50c9c4e65308fb51abf4f236457d12e9d028d6 | <|skeleton|>
class FeatureForm:
"""Form to add features to db"""
def clean_type(self):
"""It validates the type field"""
<|body_0|>
def clean_vector(self):
"""It validates the vector. If the feature is a vector it does not validate anything if feature is not a vector if validates t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeatureForm:
"""Form to add features to db"""
def clean_type(self):
"""It validates the type field"""
type_str = self.cleaned_data['type']
try:
Cvterm.objects.get(name=self.cleaned_data['type'].split(',')[0])
except Cvterm.DoesNotExist:
raise Valida... | the_stack_v2_python_sparse | goldenbraid/forms/feature.py | bioinfcomav/goldebraid | train | 0 |
fa55ad8b8c0619a04460e3d5cecf31e3dd06b6f7 | [
"res = super(sms_send_by_saleorder, self).default_get(cr, uid, fields, context=context)\nserver_ids = self.pool.get('ineco.sms.server').search(cr, uid, [('is_default', '=', True)])\nif server_ids:\n res.update({'server_id': server_ids[0]})\nsale_id = context and context.get('active_id', False) or False\nif conte... | <|body_start_0|>
res = super(sms_send_by_saleorder, self).default_get(cr, uid, fields, context=context)
server_ids = self.pool.get('ineco.sms.server').search(cr, uid, [('is_default', '=', True)])
if server_ids:
res.update({'server_id': server_ids[0]})
sale_id = context and co... | sms_send_by_saleorder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class sms_send_by_saleorder:
def default_get(self, cr, uid, fields, context):
"""To get default values for the object. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param fields: List of fields for which we want default values @pa... | stack_v2_sparse_classes_36k_train_023201 | 4,081 | no_license | [
{
"docstring": "To get default values for the object. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param fields: List of fields for which we want default values @param context: A standard dictionary @return: A dictionary which of fields with value... | 2 | stack_v2_sparse_classes_30k_test_000522 | Implement the Python class `sms_send_by_saleorder` described below.
Class description:
Implement the sms_send_by_saleorder class.
Method signatures and docstrings:
- def default_get(self, cr, uid, fields, context): To get default values for the object. @param self: The object pointer. @param cr: A database cursor @pa... | Implement the Python class `sms_send_by_saleorder` described below.
Class description:
Implement the sms_send_by_saleorder class.
Method signatures and docstrings:
- def default_get(self, cr, uid, fields, context): To get default values for the object. @param self: The object pointer. @param cr: A database cursor @pa... | 1b4b04388e723dc7137dd8d2a29fdef3f59f4861 | <|skeleton|>
class sms_send_by_saleorder:
def default_get(self, cr, uid, fields, context):
"""To get default values for the object. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param fields: List of fields for which we want default values @pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class sms_send_by_saleorder:
def default_get(self, cr, uid, fields, context):
"""To get default values for the object. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param fields: List of fields for which we want default values @param context: A... | the_stack_v2_python_sparse | ineco_sms/wizard/send_sms_by_saleorder.py | anndream/new_mixprint_addons | train | 0 | |
ee1a9063c6a67fc8835d4af345cca399daaa6ae1 | [
"self.mode = mode\nself.code = None\nself.name = None\nself.open = None\nself.high = None\nself.low = None\nself.close = None\nself.curOpen = None\nself.curLow = None\nself.curHigh = None\nself.preClose = None\nself.date = None\nself.time = None\nself.datetime = None\nself.volume = None\nself.bidPrices = None\nself... | <|body_start_0|>
self.mode = mode
self.code = None
self.name = None
self.open = None
self.high = None
self.low = None
self.close = None
self.curOpen = None
self.curLow = None
self.curHigh = None
self.preClose = None
self.dat... | K线数据 | DyStockCtaBarData | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DyStockCtaBarData:
"""K线数据"""
def __init__(self, mode):
"""@mode: Bar的格式,like '1d', '1m', '5m', '30m' and etc. 回测时需要基于此值撮合成交"""
<|body_0|>
def __getattr__(self, name):
"""获取股票价格 涨停时,没有卖盘(ask) 跌停时,没有买盘(bid)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_023202 | 5,965 | permissive | [
{
"docstring": "@mode: Bar的格式,like '1d', '1m', '5m', '30m' and etc. 回测时需要基于此值撮合成交",
"name": "__init__",
"signature": "def __init__(self, mode)"
},
{
"docstring": "获取股票价格 涨停时,没有卖盘(ask) 跌停时,没有买盘(bid)",
"name": "__getattr__",
"signature": "def __getattr__(self, name)"
}
] | 2 | null | Implement the Python class `DyStockCtaBarData` described below.
Class description:
K线数据
Method signatures and docstrings:
- def __init__(self, mode): @mode: Bar的格式,like '1d', '1m', '5m', '30m' and etc. 回测时需要基于此值撮合成交
- def __getattr__(self, name): 获取股票价格 涨停时,没有卖盘(ask) 跌停时,没有买盘(bid) | Implement the Python class `DyStockCtaBarData` described below.
Class description:
K线数据
Method signatures and docstrings:
- def __init__(self, mode): @mode: Bar的格式,like '1d', '1m', '5m', '30m' and etc. 回测时需要基于此值撮合成交
- def __getattr__(self, name): 获取股票价格 涨停时,没有卖盘(ask) 跌停时,没有买盘(bid)
<|skeleton|>
class DyStockCtaBarDat... | 163d06cb7fd30a8f24b3f2e06206c1fd024353c3 | <|skeleton|>
class DyStockCtaBarData:
"""K线数据"""
def __init__(self, mode):
"""@mode: Bar的格式,like '1d', '1m', '5m', '30m' and etc. 回测时需要基于此值撮合成交"""
<|body_0|>
def __getattr__(self, name):
"""获取股票价格 涨停时,没有卖盘(ask) 跌停时,没有买盘(bid)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DyStockCtaBarData:
"""K线数据"""
def __init__(self, mode):
"""@mode: Bar的格式,like '1d', '1m', '5m', '30m' and etc. 回测时需要基于此值撮合成交"""
self.mode = mode
self.code = None
self.name = None
self.open = None
self.high = None
self.low = None
self.close =... | the_stack_v2_python_sparse | Stock/Trade/Strategy/DyStockCtaBase.py | stockcode/DevilYuan | train | 2 |
de722b02ff25e868292b41a6612bee790b4a5636 | [
"self.parent = parent\nself.name = name\nself._unix_name = UnixName(self.name)\nself._unix_name_used = False\nself.origin = origin\nself.simple_name = _StripNamespace(self.name, namespace)\nself.description = json.get('description', None)\nself.optional = json.get('optional', None)\nself.instance_of = json.get('isI... | <|body_start_0|>
self.parent = parent
self.name = name
self._unix_name = UnixName(self.name)
self._unix_name_used = False
self.origin = origin
self.simple_name = _StripNamespace(self.name, namespace)
self.description = json.get('description', None)
self.op... | A property of a type OR a parameter to a function. Properties: - |name| name of the property as in the json. This shouldn't change since it is the key used to access Value::Dict - |unix_name| the unix_style_name of the property. Used as variable name - |optional| a boolean representing whether the property is optional ... | Property | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Property:
"""A property of a type OR a parameter to a function. Properties: - |name| name of the property as in the json. This shouldn't change since it is the key used to access Value::Dict - |unix_name| the unix_style_name of the property. Used as variable name - |optional| a boolean representi... | stack_v2_sparse_classes_36k_train_023203 | 31,957 | permissive | [
{
"docstring": "Creates a Property from JSON.",
"name": "__init__",
"signature": "def __init__(self, parent, name, json, namespace, origin)"
},
{
"docstring": "Gets the property's unix_name. Raises AttributeError if not set.",
"name": "GetUnixName",
"signature": "def GetUnixName(self)"
... | 3 | stack_v2_sparse_classes_30k_train_018307 | Implement the Python class `Property` described below.
Class description:
A property of a type OR a parameter to a function. Properties: - |name| name of the property as in the json. This shouldn't change since it is the key used to access Value::Dict - |unix_name| the unix_style_name of the property. Used as variable... | Implement the Python class `Property` described below.
Class description:
A property of a type OR a parameter to a function. Properties: - |name| name of the property as in the json. This shouldn't change since it is the key used to access Value::Dict - |unix_name| the unix_style_name of the property. Used as variable... | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | <|skeleton|>
class Property:
"""A property of a type OR a parameter to a function. Properties: - |name| name of the property as in the json. This shouldn't change since it is the key used to access Value::Dict - |unix_name| the unix_style_name of the property. Used as variable name - |optional| a boolean representi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Property:
"""A property of a type OR a parameter to a function. Properties: - |name| name of the property as in the json. This shouldn't change since it is the key used to access Value::Dict - |unix_name| the unix_style_name of the property. Used as variable name - |optional| a boolean representing whether th... | the_stack_v2_python_sparse | tools/json_schema_compiler/model.py | chromium/chromium | train | 17,408 |
968f401b9e058fbabb7d91444f44bbf6db05adaf | [
"super(NativeInterface, self).__init__(**kwargs)\nself._time_per_cycle = kwargs.pop('time_per_cycle', 15)\nself._jobs_per_cycle = kwargs.pop('jobs_per_cycle', 20)",
"full_sub_dict = job_config.copy()\nfull_command = '%s >& %s' % (link.command_template().format(**full_sub_dict), logfile)\nlogdir = os.path.dirname(... | <|body_start_0|>
super(NativeInterface, self).__init__(**kwargs)
self._time_per_cycle = kwargs.pop('time_per_cycle', 15)
self._jobs_per_cycle = kwargs.pop('jobs_per_cycle', 20)
<|end_body_0|>
<|body_start_1|>
full_sub_dict = job_config.copy()
full_command = '%s >& %s' % (link.co... | Implmentation of ScatterGather that uses the native system | NativeInterface | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NativeInterface:
"""Implmentation of ScatterGather that uses the native system"""
def __init__(self, **kwargs):
"""C'tor Keyword arguements ------------------ jobs_per_cycle : int [20] Maximum number of jobs to submit in each cycle time_per_cycle : int [15] Time per submission cycle ... | stack_v2_sparse_classes_36k_train_023204 | 4,417 | permissive | [
{
"docstring": "C'tor Keyword arguements ------------------ jobs_per_cycle : int [20] Maximum number of jobs to submit in each cycle time_per_cycle : int [15] Time per submission cycle in seconds max_job_age : int [90] Max job age in minutes",
"name": "__init__",
"signature": "def __init__(self, **kwarg... | 3 | null | Implement the Python class `NativeInterface` described below.
Class description:
Implmentation of ScatterGather that uses the native system
Method signatures and docstrings:
- def __init__(self, **kwargs): C'tor Keyword arguements ------------------ jobs_per_cycle : int [20] Maximum number of jobs to submit in each c... | Implement the Python class `NativeInterface` described below.
Class description:
Implmentation of ScatterGather that uses the native system
Method signatures and docstrings:
- def __init__(self, **kwargs): C'tor Keyword arguements ------------------ jobs_per_cycle : int [20] Maximum number of jobs to submit in each c... | fbd4c95ffadbff31cbb9cc862ff84a78dc734ef5 | <|skeleton|>
class NativeInterface:
"""Implmentation of ScatterGather that uses the native system"""
def __init__(self, **kwargs):
"""C'tor Keyword arguements ------------------ jobs_per_cycle : int [20] Maximum number of jobs to submit in each cycle time_per_cycle : int [15] Time per submission cycle ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NativeInterface:
"""Implmentation of ScatterGather that uses the native system"""
def __init__(self, **kwargs):
"""C'tor Keyword arguements ------------------ jobs_per_cycle : int [20] Maximum number of jobs to submit in each cycle time_per_cycle : int [15] Time per submission cycle in seconds ma... | the_stack_v2_python_sparse | fermipy/jobs/native_impl.py | fermiPy/fermipy | train | 51 |
648ac173e5956499617ea380b2bca3aca584662a | [
"for i, val in enumerate(nums):\n other = target - val\n if other in nums[i + 1:]:\n return [i, nums.index(other, i + 1)]",
"dic = dict()\nfor i, val in enumerate(nums):\n other = target - val\n if other in dic:\n return [dic.get(other), i]\n dic[val] = i"
] | <|body_start_0|>
for i, val in enumerate(nums):
other = target - val
if other in nums[i + 1:]:
return [i, nums.index(other, i + 1)]
<|end_body_0|>
<|body_start_1|>
dic = dict()
for i, val in enumerate(nums):
other = target - val
if... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, nums: list, target: int) -> list:
"""在原列表中查找,如果找到补码,返回从i+1开始查找的索引。"""
<|body_0|>
def twoSum1(self, nums: list, target: int) -> list:
"""空间换时间:新建dict,存于dict中方便查找(Hash查找速度快)。"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
f... | stack_v2_sparse_classes_36k_train_023205 | 1,336 | no_license | [
{
"docstring": "在原列表中查找,如果找到补码,返回从i+1开始查找的索引。",
"name": "twoSum",
"signature": "def twoSum(self, nums: list, target: int) -> list"
},
{
"docstring": "空间换时间:新建dict,存于dict中方便查找(Hash查找速度快)。",
"name": "twoSum1",
"signature": "def twoSum1(self, nums: list, target: int) -> list"
}
] | 2 | stack_v2_sparse_classes_30k_train_011681 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums: list, target: int) -> list: 在原列表中查找,如果找到补码,返回从i+1开始查找的索引。
- def twoSum1(self, nums: list, target: int) -> list: 空间换时间:新建dict,存于dict中方便查找(Hash查找速度快)。 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums: list, target: int) -> list: 在原列表中查找,如果找到补码,返回从i+1开始查找的索引。
- def twoSum1(self, nums: list, target: int) -> list: 空间换时间:新建dict,存于dict中方便查找(Hash查找速度快)。
<|ske... | 2bbb1640589aab34f2bc42489283033cc11fb885 | <|skeleton|>
class Solution:
def twoSum(self, nums: list, target: int) -> list:
"""在原列表中查找,如果找到补码,返回从i+1开始查找的索引。"""
<|body_0|>
def twoSum1(self, nums: list, target: int) -> list:
"""空间换时间:新建dict,存于dict中方便查找(Hash查找速度快)。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum(self, nums: list, target: int) -> list:
"""在原列表中查找,如果找到补码,返回从i+1开始查找的索引。"""
for i, val in enumerate(nums):
other = target - val
if other in nums[i + 1:]:
return [i, nums.index(other, i + 1)]
def twoSum1(self, nums: list, target:... | the_stack_v2_python_sparse | 001_two-sum.py | helloocc/algorithm | train | 1 | |
e7ae9b564fa3d46691c6ca7e722d41e511f4cbd0 | [
"tmp_date = pendulum.parse(self.date.name)\nplan_date = tmp_date.format('YYYY-MM-DD')\nrecord = self.env['metro_park_maintenance.day_plan'].create([{'plan_name': self.name, 'plan_date': plan_date, 'state': 'draft', 'week_plan_id': self.week_plan_id.id, 'pms_work_class_info': self.pms_work_class_info.id, 'run_trains... | <|body_start_0|>
tmp_date = pendulum.parse(self.date.name)
plan_date = tmp_date.format('YYYY-MM-DD')
record = self.env['metro_park_maintenance.day_plan'].create([{'plan_name': self.name, 'plan_date': plan_date, 'state': 'draft', 'week_plan_id': self.week_plan_id.id, 'pms_work_class_info': self.p... | 重写onok函数,每条线路各自实现各自的 | DayPlanWizard | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DayPlanWizard:
"""重写onok函数,每条线路各自实现各自的"""
def on_ok(self):
"""点击确定按扭, 创建的时候就把当日的运行图数据放进去,这样便于修改 :return:"""
<|body_0|>
def get_day_plan_action(self):
"""取得日计划动作 :return:"""
<|body_1|>
def get_parent_plan_data(self):
"""获取上一级计划的检修计划数据 :return:... | stack_v2_sparse_classes_36k_train_023206 | 3,982 | no_license | [
{
"docstring": "点击确定按扭, 创建的时候就把当日的运行图数据放进去,这样便于修改 :return:",
"name": "on_ok",
"signature": "def on_ok(self)"
},
{
"docstring": "取得日计划动作 :return:",
"name": "get_day_plan_action",
"signature": "def get_day_plan_action(self)"
},
{
"docstring": "获取上一级计划的检修计划数据 :return:",
"name": ... | 3 | stack_v2_sparse_classes_30k_train_011537 | Implement the Python class `DayPlanWizard` described below.
Class description:
重写onok函数,每条线路各自实现各自的
Method signatures and docstrings:
- def on_ok(self): 点击确定按扭, 创建的时候就把当日的运行图数据放进去,这样便于修改 :return:
- def get_day_plan_action(self): 取得日计划动作 :return:
- def get_parent_plan_data(self): 获取上一级计划的检修计划数据 :return: | Implement the Python class `DayPlanWizard` described below.
Class description:
重写onok函数,每条线路各自实现各自的
Method signatures and docstrings:
- def on_ok(self): 点击确定按扭, 创建的时候就把当日的运行图数据放进去,这样便于修改 :return:
- def get_day_plan_action(self): 取得日计划动作 :return:
- def get_parent_plan_data(self): 获取上一级计划的检修计划数据 :return:
<|skeleton|>
... | 13b428a5c4ade6278e3e5e996ef10d9fb0fea4b9 | <|skeleton|>
class DayPlanWizard:
"""重写onok函数,每条线路各自实现各自的"""
def on_ok(self):
"""点击确定按扭, 创建的时候就把当日的运行图数据放进去,这样便于修改 :return:"""
<|body_0|>
def get_day_plan_action(self):
"""取得日计划动作 :return:"""
<|body_1|>
def get_parent_plan_data(self):
"""获取上一级计划的检修计划数据 :return:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DayPlanWizard:
"""重写onok函数,每条线路各自实现各自的"""
def on_ok(self):
"""点击确定按扭, 创建的时候就把当日的运行图数据放进去,这样便于修改 :return:"""
tmp_date = pendulum.parse(self.date.name)
plan_date = tmp_date.format('YYYY-MM-DD')
record = self.env['metro_park_maintenance.day_plan'].create([{'plan_name': self.n... | the_stack_v2_python_sparse | mdias_addons/metro_park_base_data_6/models/day_plan_wizard.py | rezaghanimi/main_mdias | train | 0 |
c36710aa670ef1aad0851c4a9e4d5254a3646b32 | [
"pg_list = []\nnetwork_sys = client_object.get_network_system()\nfor pg in network_sys.networkInfo.portgroup:\n pg_list.append(pg.spec.name)\nreturn pg_list",
"host_mor = client_object.get_host_mor()\nnetwork_folder = host_mor.parent.parent.parent.networkFolder\nfor component in network_folder.childEntity:\n ... | <|body_start_0|>
pg_list = []
network_sys = client_object.get_network_system()
for pg in network_sys.networkInfo.portgroup:
pg_list.append(pg.spec.name)
return pg_list
<|end_body_0|>
<|body_start_1|>
host_mor = client_object.get_host_mor()
network_folder = ho... | Network related operations. | ESX55NetworkImpl | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ESX55NetworkImpl:
"""Network related operations."""
def list_networks(cls, client_object):
"""Returns the list of port groups. @type client_object: client instance @param client_object: Hypervisor client instance @rtype: list @return: List of port groups."""
<|body_0|>
d... | stack_v2_sparse_classes_36k_train_023207 | 1,942 | no_license | [
{
"docstring": "Returns the list of port groups. @type client_object: client instance @param client_object: Hypervisor client instance @rtype: list @return: List of port groups.",
"name": "list_networks",
"signature": "def list_networks(cls, client_object)"
},
{
"docstring": "Returns the ID(key)... | 2 | stack_v2_sparse_classes_30k_train_016411 | Implement the Python class `ESX55NetworkImpl` described below.
Class description:
Network related operations.
Method signatures and docstrings:
- def list_networks(cls, client_object): Returns the list of port groups. @type client_object: client instance @param client_object: Hypervisor client instance @rtype: list @... | Implement the Python class `ESX55NetworkImpl` described below.
Class description:
Network related operations.
Method signatures and docstrings:
- def list_networks(cls, client_object): Returns the list of port groups. @type client_object: client instance @param client_object: Hypervisor client instance @rtype: list @... | 5b55817c050b637e2747084290f6206d2e622938 | <|skeleton|>
class ESX55NetworkImpl:
"""Network related operations."""
def list_networks(cls, client_object):
"""Returns the list of port groups. @type client_object: client instance @param client_object: Hypervisor client instance @rtype: list @return: List of port groups."""
<|body_0|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ESX55NetworkImpl:
"""Network related operations."""
def list_networks(cls, client_object):
"""Returns the list of port groups. @type client_object: client instance @param client_object: Hypervisor client instance @rtype: list @return: List of port groups."""
pg_list = []
network_s... | the_stack_v2_python_sparse | SystemTesting/pylib/vmware/vsphere/esx/api/esx55_network_impl.py | Cloudxtreme/MyProject | train | 0 |
7717e37b527afefae41fd199791d191b5b0e276b | [
"self = object.__new__(cls)\nself.name = cls.DEFAULT_NAME\nself.value = value\nself.extension = cls.DEFAULT_EXTENSION\nself.INSTANCES[value] = self\nreturn self",
"self.name = name\nself.value = value\nself.extension = extension\nself.INSTANCES[value] = self"
] | <|body_start_0|>
self = object.__new__(cls)
self.name = cls.DEFAULT_NAME
self.value = value
self.extension = cls.DEFAULT_EXTENSION
self.INSTANCES[value] = self
return self
<|end_body_0|>
<|body_start_1|>
self.name = name
self.value = value
self.ex... | Represents a message sticker's format's type. Attributes ---------- name : `str` The name of the message sticker format type. value : `int` The Discord side identifier value of the message sticker format type. extension : `str` The extension of the sticker format type. Class Attributes ---------------- INSTANCES : `dic... | StickerFormat | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StickerFormat:
"""Represents a message sticker's format's type. Attributes ---------- name : `str` The name of the message sticker format type. value : `int` The Discord side identifier value of the message sticker format type. extension : `str` The extension of the sticker format type. Class Att... | stack_v2_sparse_classes_36k_train_023208 | 4,961 | permissive | [
{
"docstring": "Creates a sticker format type from the given id and stores it at class's `.INSTANCES`. Called by `.get` when no sticker format type was found with the given id. Parameters ---------- id_ : `int` The identifier of the sticker format type. Returns ------- sticker_format : ``StickerFormat``",
"... | 2 | null | Implement the Python class `StickerFormat` described below.
Class description:
Represents a message sticker's format's type. Attributes ---------- name : `str` The name of the message sticker format type. value : `int` The Discord side identifier value of the message sticker format type. extension : `str` The extensio... | Implement the Python class `StickerFormat` described below.
Class description:
Represents a message sticker's format's type. Attributes ---------- name : `str` The name of the message sticker format type. value : `int` The Discord side identifier value of the message sticker format type. extension : `str` The extensio... | 53f24fdb38459dc5a4fd04f11bdbfee8295b76a4 | <|skeleton|>
class StickerFormat:
"""Represents a message sticker's format's type. Attributes ---------- name : `str` The name of the message sticker format type. value : `int` The Discord side identifier value of the message sticker format type. extension : `str` The extension of the sticker format type. Class Att... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StickerFormat:
"""Represents a message sticker's format's type. Attributes ---------- name : `str` The name of the message sticker format type. value : `int` The Discord side identifier value of the message sticker format type. extension : `str` The extension of the sticker format type. Class Attributes -----... | the_stack_v2_python_sparse | hata/discord/sticker/sticker/preinstanced.py | HuyaneMatsu/hata | train | 3 |
de78dbab235e698e0ec04bf7eaf548f7f67602f7 | [
"super().__init__(runner, shutdown_timeout=shutdown_timeout, ssl_context=ssl_context, backlog=backlog)\nself._host = host\nself._port = port\nself._reuse_address = reuse_address\nself._reuse_port = reuse_port",
"scheme = 'https' if self._ssl_context else 'http'\nhost = self._host[0] if isinstance(self._host, list... | <|body_start_0|>
super().__init__(runner, shutdown_timeout=shutdown_timeout, ssl_context=ssl_context, backlog=backlog)
self._host = host
self._port = port
self._reuse_address = reuse_address
self._reuse_port = reuse_port
<|end_body_0|>
<|body_start_1|>
scheme = 'https' i... | HomeAssistant specific aiohttp Site. Vanilla TCPSite accepts only str as host. However, the underlying asyncio's create_server() implementation does take a list of strings to bind to multiple host IP's. To support multiple server_host entries (e.g. to enable dual-stack explicitly), we would like to pass an array of str... | HomeAssistantTCPSite | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HomeAssistantTCPSite:
"""HomeAssistant specific aiohttp Site. Vanilla TCPSite accepts only str as host. However, the underlying asyncio's create_server() implementation does take a list of strings to bind to multiple host IP's. To support multiple server_host entries (e.g. to enable dual-stack ex... | stack_v2_sparse_classes_36k_train_023209 | 2,275 | permissive | [
{
"docstring": "Initialize HomeAssistantTCPSite.",
"name": "__init__",
"signature": "def __init__(self, runner: web.BaseRunner, host: None | str | list[str], port: int, *, shutdown_timeout: float=10.0, ssl_context: SSLContext | None=None, backlog: int=128, reuse_address: bool | None=None, reuse_port: bo... | 3 | null | Implement the Python class `HomeAssistantTCPSite` described below.
Class description:
HomeAssistant specific aiohttp Site. Vanilla TCPSite accepts only str as host. However, the underlying asyncio's create_server() implementation does take a list of strings to bind to multiple host IP's. To support multiple server_hos... | Implement the Python class `HomeAssistantTCPSite` described below.
Class description:
HomeAssistant specific aiohttp Site. Vanilla TCPSite accepts only str as host. However, the underlying asyncio's create_server() implementation does take a list of strings to bind to multiple host IP's. To support multiple server_hos... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class HomeAssistantTCPSite:
"""HomeAssistant specific aiohttp Site. Vanilla TCPSite accepts only str as host. However, the underlying asyncio's create_server() implementation does take a list of strings to bind to multiple host IP's. To support multiple server_host entries (e.g. to enable dual-stack ex... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HomeAssistantTCPSite:
"""HomeAssistant specific aiohttp Site. Vanilla TCPSite accepts only str as host. However, the underlying asyncio's create_server() implementation does take a list of strings to bind to multiple host IP's. To support multiple server_host entries (e.g. to enable dual-stack explicitly), we... | the_stack_v2_python_sparse | homeassistant/components/http/web_runner.py | home-assistant/core | train | 35,501 |
c7e6c761ac230f98461bbd04cc6c951461f6297f | [
"self.ser = serial.Serial()\nself.ser.baudrate = baurate\nself.ser.port = port\nself.ser.timeout = timeout\nself.lines = []",
"self.lines = []\nwhile True:\n line = self.ser.readline()\n if line:\n self.lines.append(line)\n if not line or line[-1:] != '\\n':\n break\nreturn self.lines",
"... | <|body_start_0|>
self.ser = serial.Serial()
self.ser.baudrate = baurate
self.ser.port = port
self.ser.timeout = timeout
self.lines = []
<|end_body_0|>
<|body_start_1|>
self.lines = []
while True:
line = self.ser.readline()
if line:
... | Base Serial Blass | SerialConnectorBase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SerialConnectorBase:
"""Base Serial Blass"""
def __init__(self, port='COM5', baurate=115200, timeout=1):
"""Constructor"""
<|body_0|>
def readlines(self):
"""read all lines that are available. abort after timout when no more data arrives."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_023210 | 2,151 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, port='COM5', baurate=115200, timeout=1)"
},
{
"docstring": "read all lines that are available. abort after timout when no more data arrives.",
"name": "readlines",
"signature": "def readlines(self)"
},
... | 5 | null | Implement the Python class `SerialConnectorBase` described below.
Class description:
Base Serial Blass
Method signatures and docstrings:
- def __init__(self, port='COM5', baurate=115200, timeout=1): Constructor
- def readlines(self): read all lines that are available. abort after timout when no more data arrives.
- d... | Implement the Python class `SerialConnectorBase` described below.
Class description:
Base Serial Blass
Method signatures and docstrings:
- def __init__(self, port='COM5', baurate=115200, timeout=1): Constructor
- def readlines(self): read all lines that are available. abort after timout when no more data arrives.
- d... | 24a74926170cbdfafa47e972644e2fe5b627d8ff | <|skeleton|>
class SerialConnectorBase:
"""Base Serial Blass"""
def __init__(self, port='COM5', baurate=115200, timeout=1):
"""Constructor"""
<|body_0|>
def readlines(self):
"""read all lines that are available. abort after timout when no more data arrives."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SerialConnectorBase:
"""Base Serial Blass"""
def __init__(self, port='COM5', baurate=115200, timeout=1):
"""Constructor"""
self.ser = serial.Serial()
self.ser.baudrate = baurate
self.ser.port = port
self.ser.timeout = timeout
self.lines = []
def readli... | the_stack_v2_python_sparse | robo4.2/4.2/lib/python2.7/site-packages/RoboGalaxyLibrary/cli/serial/SerialBase.py | richa92/Jenkin_Regression_Testing | train | 0 |
070e883a20d5fcc9923dbf373cc8387f736e1f75 | [
"def parse_mtl_lines(line_list, tree_dict, level=0):\n \"\"\"Recursive helper function to parse MTL lines\n \"\"\"\n while line_list:\n line = line_list.pop(0)\n try:\n key, value = [s.strip(' \"') for s in line.split('=')]\n key = key.replace(' ', '_')\n ... | <|body_start_0|>
def parse_mtl_lines(line_list, tree_dict, level=0):
"""Recursive helper function to parse MTL lines
"""
while line_list:
line = line_list.pop(0)
try:
key, value = [s.strip(' "') for s in line.split('... | Subclass of Metadata to manage MTL data | MTLMetadata | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MTLMetadata:
"""Subclass of Metadata to manage MTL data"""
def _parse_mtl_string(self, mtl_string, tree_dict=None):
"""Private function to parse a block of MTL text into a nested dict Exposed to allow unit testing using a string Arguments: mtl_string: MTL text block (string) Returns:... | stack_v2_sparse_classes_36k_train_023211 | 10,018 | permissive | [
{
"docstring": "Private function to parse a block of MTL text into a nested dict Exposed to allow unit testing using a string Arguments: mtl_string: MTL text block (string) Returns: MTL parameter nested dictionary.",
"name": "_parse_mtl_string",
"signature": "def _parse_mtl_string(self, mtl_string, tree... | 3 | stack_v2_sparse_classes_30k_train_006230 | Implement the Python class `MTLMetadata` described below.
Class description:
Subclass of Metadata to manage MTL data
Method signatures and docstrings:
- def _parse_mtl_string(self, mtl_string, tree_dict=None): Private function to parse a block of MTL text into a nested dict Exposed to allow unit testing using a strin... | Implement the Python class `MTLMetadata` described below.
Class description:
Subclass of Metadata to manage MTL data
Method signatures and docstrings:
- def _parse_mtl_string(self, mtl_string, tree_dict=None): Private function to parse a block of MTL text into a nested dict Exposed to allow unit testing using a strin... | a6b9de7e1fe1d3bae8669ec41cd09407e3e0afbc | <|skeleton|>
class MTLMetadata:
"""Subclass of Metadata to manage MTL data"""
def _parse_mtl_string(self, mtl_string, tree_dict=None):
"""Private function to parse a block of MTL text into a nested dict Exposed to allow unit testing using a string Arguments: mtl_string: MTL text block (string) Returns:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MTLMetadata:
"""Subclass of Metadata to manage MTL data"""
def _parse_mtl_string(self, mtl_string, tree_dict=None):
"""Private function to parse a block of MTL text into a nested dict Exposed to allow unit testing using a string Arguments: mtl_string: MTL text block (string) Returns: MTL paramete... | the_stack_v2_python_sparse | metadata_sync/metadata/_mtl_metadata.py | alex-ip/metadata_sync | train | 0 |
136bb6ec6b39a9e87aeef3f23b434c05fb9e2ef1 | [
"PostProcessorInterfaceBase.initialize(self)\nself.inputFormat = None\nself.outputFormat = None\nself.label = None\nself.clusterIDs = []",
"for child in xmlNode:\n if child.tag == 'dataType':\n dataType = child.text\n if dataType in set(['HistorySet', 'PointSet']):\n self.inputFormat =... | <|body_start_0|>
PostProcessorInterfaceBase.initialize(self)
self.inputFormat = None
self.outputFormat = None
self.label = None
self.clusterIDs = []
<|end_body_0|>
<|body_start_1|>
for child in xmlNode:
if child.tag == 'dataType':
dataType = c... | This Post-Processor filters out the points or histories accordingly to a chosen clustering label | dataObjectLabelFilter | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class dataObjectLabelFilter:
"""This Post-Processor filters out the points or histories accordingly to a chosen clustering label"""
def initialize(self):
"""Method to initialize the Interfaced Post-processor @ In, None, @ Out, None,"""
<|body_0|>
def readMoreXML(self, xmlNode)... | stack_v2_sparse_classes_36k_train_023212 | 4,275 | permissive | [
{
"docstring": "Method to initialize the Interfaced Post-processor @ In, None, @ Out, None,",
"name": "initialize",
"signature": "def initialize(self)"
},
{
"docstring": "Function that reads elements this post-processor will use @ In, xmlNode, ElementTree, Xml element node @ Out, None",
"nam... | 3 | stack_v2_sparse_classes_30k_train_016258 | Implement the Python class `dataObjectLabelFilter` described below.
Class description:
This Post-Processor filters out the points or histories accordingly to a chosen clustering label
Method signatures and docstrings:
- def initialize(self): Method to initialize the Interfaced Post-processor @ In, None, @ Out, None,
... | Implement the Python class `dataObjectLabelFilter` described below.
Class description:
This Post-Processor filters out the points or histories accordingly to a chosen clustering label
Method signatures and docstrings:
- def initialize(self): Method to initialize the Interfaced Post-processor @ In, None, @ Out, None,
... | fbee9e3def3c1ee576d1af85f3258cc816ceaaaf | <|skeleton|>
class dataObjectLabelFilter:
"""This Post-Processor filters out the points or histories accordingly to a chosen clustering label"""
def initialize(self):
"""Method to initialize the Interfaced Post-processor @ In, None, @ Out, None,"""
<|body_0|>
def readMoreXML(self, xmlNode)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class dataObjectLabelFilter:
"""This Post-Processor filters out the points or histories accordingly to a chosen clustering label"""
def initialize(self):
"""Method to initialize the Interfaced Post-processor @ In, None, @ Out, None,"""
PostProcessorInterfaceBase.initialize(self)
self.in... | the_stack_v2_python_sparse | framework/PostProcessorFunctions/dataObjectLabelFilter.py | jbae11/raven | train | 0 |
cc15e2111cd96a422debe0d6bf491ae7cdd6723a | [
"self.bot_id = kwargs.get('bot_id')\nself.position = kwargs.get('position')\nself.rotation = kwargs.get('rotation')\nself.waypoint_position = kwargs.get('waypoint_position')",
"self.bot_id = kwargs['bot_id']\nself.position = kwargs['position']\nself.rotation = kwargs['rotation']\nself.waypoint_position = kwargs['... | <|body_start_0|>
self.bot_id = kwargs.get('bot_id')
self.position = kwargs.get('position')
self.rotation = kwargs.get('rotation')
self.waypoint_position = kwargs.get('waypoint_position')
<|end_body_0|>
<|body_start_1|>
self.bot_id = kwargs['bot_id']
self.position = kwarg... | BotTransformSyncRequest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BotTransformSyncRequest:
def __init__(self, **kwargs):
"""Params: bot_id: int position: Vector3 rotation: float waypoint_position: Vector3"""
<|body_0|>
def load(self, **kwargs):
"""load from dict Exception: KeyError"""
<|body_1|>
def dump(self):
... | stack_v2_sparse_classes_36k_train_023213 | 26,590 | no_license | [
{
"docstring": "Params: bot_id: int position: Vector3 rotation: float waypoint_position: Vector3",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "load from dict Exception: KeyError",
"name": "load",
"signature": "def load(self, **kwargs)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_017306 | Implement the Python class `BotTransformSyncRequest` described below.
Class description:
Implement the BotTransformSyncRequest class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Params: bot_id: int position: Vector3 rotation: float waypoint_position: Vector3
- def load(self, **kwargs): load from... | Implement the Python class `BotTransformSyncRequest` described below.
Class description:
Implement the BotTransformSyncRequest class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Params: bot_id: int position: Vector3 rotation: float waypoint_position: Vector3
- def load(self, **kwargs): load from... | aa0b2697e295889e8c23a7104889ea95f2a4b6b1 | <|skeleton|>
class BotTransformSyncRequest:
def __init__(self, **kwargs):
"""Params: bot_id: int position: Vector3 rotation: float waypoint_position: Vector3"""
<|body_0|>
def load(self, **kwargs):
"""load from dict Exception: KeyError"""
<|body_1|>
def dump(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BotTransformSyncRequest:
def __init__(self, **kwargs):
"""Params: bot_id: int position: Vector3 rotation: float waypoint_position: Vector3"""
self.bot_id = kwargs.get('bot_id')
self.position = kwargs.get('position')
self.rotation = kwargs.get('rotation')
self.waypoint_p... | the_stack_v2_python_sparse | message.py | songhui17/Server | train | 0 | |
8fb919f2a151a8a579f812aecd079f6dab826d28 | [
"super(InversePunisher, self).__init__()\nself.history = []\nself.mem_length = 1\nself.grudged = False\nself.grudge_memory = 1",
"if self.grudge_memory >= self.mem_length:\n self.grudge_memory = 0\n self.grudged = False\nif self.grudged:\n self.grudge_memory += 1\n return 'D'\nelif 'D' in opponent.his... | <|body_start_0|>
super(InversePunisher, self).__init__()
self.history = []
self.mem_length = 1
self.grudged = False
self.grudge_memory = 1
<|end_body_0|>
<|body_start_1|>
if self.grudge_memory >= self.mem_length:
self.grudge_memory = 0
self.grudge... | A player starts by cooperating however will defect if at any point the opponent has defected, but forgets after meme_length matches, with 1<=mem_length<=20 proportional to the amount of time the opponent has played 'C'. The inverse of Punisher | InversePunisher | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InversePunisher:
"""A player starts by cooperating however will defect if at any point the opponent has defected, but forgets after meme_length matches, with 1<=mem_length<=20 proportional to the amount of time the opponent has played 'C'. The inverse of Punisher"""
def __init__(self):
... | stack_v2_sparse_classes_36k_train_023214 | 3,311 | permissive | [
{
"docstring": "Initialised the player",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Begins by playing C, then plays D for an amount of rounds proportional to the opponents historical '%' of playing 'C' if the opponent ever plays D",
"name": "strategy",
"sign... | 3 | stack_v2_sparse_classes_30k_train_021044 | Implement the Python class `InversePunisher` described below.
Class description:
A player starts by cooperating however will defect if at any point the opponent has defected, but forgets after meme_length matches, with 1<=mem_length<=20 proportional to the amount of time the opponent has played 'C'. The inverse of Pun... | Implement the Python class `InversePunisher` described below.
Class description:
A player starts by cooperating however will defect if at any point the opponent has defected, but forgets after meme_length matches, with 1<=mem_length<=20 proportional to the amount of time the opponent has played 'C'. The inverse of Pun... | 0ce3aa29eb239b9a9055cd7bebb627602851b65a | <|skeleton|>
class InversePunisher:
"""A player starts by cooperating however will defect if at any point the opponent has defected, but forgets after meme_length matches, with 1<=mem_length<=20 proportional to the amount of time the opponent has played 'C'. The inverse of Punisher"""
def __init__(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InversePunisher:
"""A player starts by cooperating however will defect if at any point the opponent has defected, but forgets after meme_length matches, with 1<=mem_length<=20 proportional to the amount of time the opponent has played 'C'. The inverse of Punisher"""
def __init__(self):
"""Initial... | the_stack_v2_python_sparse | axelrod/strategies/punisher.py | jamesbroadhead/Axelrod | train | 1 |
18f9804985f0694eb89489807b9a58078230f602 | [
"sequence = ['1']\nfor i in range(2, n + 1):\n prev = sequence[-1]\n curr_number = prev[0]\n curr_count = 1\n result = []\n for j in range(1, len(prev)):\n if prev[j] == curr_number:\n curr_count += 1\n else:\n result.append(str(curr_count))\n result.app... | <|body_start_0|>
sequence = ['1']
for i in range(2, n + 1):
prev = sequence[-1]
curr_number = prev[0]
curr_count = 1
result = []
for j in range(1, len(prev)):
if prev[j] == curr_number:
curr_count += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def count_and_say_1(self, n):
"""Returns count-and-say sequence up to the nth term included. Algorithm description to find the next term: 1) Count repeated numbers of current term till 1st non-repeated number. 2) Add str(count as a number) + str(number) to the resulting string.... | stack_v2_sparse_classes_36k_train_023215 | 3,147 | no_license | [
{
"docstring": "Returns count-and-say sequence up to the nth term included. Algorithm description to find the next term: 1) Count repeated numbers of current term till 1st non-repeated number. 2) Add str(count as a number) + str(number) to the resulting string. 3) Repeat till the end of current term. Time compl... | 2 | stack_v2_sparse_classes_30k_val_000670 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def count_and_say_1(self, n): Returns count-and-say sequence up to the nth term included. Algorithm description to find the next term: 1) Count repeated numbers of current term t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def count_and_say_1(self, n): Returns count-and-say sequence up to the nth term included. Algorithm description to find the next term: 1) Count repeated numbers of current term t... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class Solution:
def count_and_say_1(self, n):
"""Returns count-and-say sequence up to the nth term included. Algorithm description to find the next term: 1) Count repeated numbers of current term till 1st non-repeated number. 2) Add str(count as a number) + str(number) to the resulting string.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def count_and_say_1(self, n):
"""Returns count-and-say sequence up to the nth term included. Algorithm description to find the next term: 1) Count repeated numbers of current term till 1st non-repeated number. 2) Add str(count as a number) + str(number) to the resulting string. 3) Repeat til... | the_stack_v2_python_sparse | Strings/count_and_say.py | vladn90/Algorithms | train | 0 | |
9810f110f3647afc115629e29615433696d05d52 | [
"code = '{country_alpha2}-{subdivision_code}'.format(country_alpha2=country_alpha2, subdivision_code=subdivision_code)\ntry:\n if subdivisions.get(code=code) is None:\n abort(400, 'Bad request: country_alpha2 and subdivision_code are invalid')\nexcept KeyError:\n abort(400, 'Bad request: country_alpha2... | <|body_start_0|>
code = '{country_alpha2}-{subdivision_code}'.format(country_alpha2=country_alpha2, subdivision_code=subdivision_code)
try:
if subdivisions.get(code=code) is None:
abort(400, 'Bad request: country_alpha2 and subdivision_code are invalid')
except KeyErr... | CityItem | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CityItem:
def get(self, country_alpha2: str, subdivision_code: str, city_id: int):
"""Returns a city record. :param country_alpha2: The unique two character identifier of the country record. :type country_alpha2: str :param subdivision_code: The unique two character identifier of the sub... | stack_v2_sparse_classes_36k_train_023216 | 9,552 | permissive | [
{
"docstring": "Returns a city record. :param country_alpha2: The unique two character identifier of the country record. :type country_alpha2: str :param subdivision_code: The unique two character identifier of the subdivision record. :type subdivision_code: str :param city_id: The unique identifier of the city... | 3 | stack_v2_sparse_classes_30k_train_006072 | Implement the Python class `CityItem` described below.
Class description:
Implement the CityItem class.
Method signatures and docstrings:
- def get(self, country_alpha2: str, subdivision_code: str, city_id: int): Returns a city record. :param country_alpha2: The unique two character identifier of the country record. ... | Implement the Python class `CityItem` described below.
Class description:
Implement the CityItem class.
Method signatures and docstrings:
- def get(self, country_alpha2: str, subdivision_code: str, city_id: int): Returns a city record. :param country_alpha2: The unique two character identifier of the country record. ... | a38097d0f4a2f59c7c4892df6a72c19236df48e9 | <|skeleton|>
class CityItem:
def get(self, country_alpha2: str, subdivision_code: str, city_id: int):
"""Returns a city record. :param country_alpha2: The unique two character identifier of the country record. :type country_alpha2: str :param subdivision_code: The unique two character identifier of the sub... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CityItem:
def get(self, country_alpha2: str, subdivision_code: str, city_id: int):
"""Returns a city record. :param country_alpha2: The unique two character identifier of the country record. :type country_alpha2: str :param subdivision_code: The unique two character identifier of the subdivision recor... | the_stack_v2_python_sparse | api/geolocation_data_flaskapi/endpoints/location_endpoint.py | Fyzel/geolocation-data-flaskapi | train | 3 | |
c7eb70bd4ff66b3e27bd94493e598fbd1e4d138b | [
"self.name = name\nself.age = age\nself.score = score",
"print('这个人的name是:', self.name)\nprint('这个人的age是:', self.age)\nprint('这个人的score是:', self.score)"
] | <|body_start_0|>
self.name = name
self.age = age
self.score = score
<|end_body_0|>
<|body_start_1|>
print('这个人的name是:', self.name)
print('这个人的age是:', self.age)
print('这个人的score是:', self.score)
<|end_body_1|>
| Human | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Human:
def set_info(self, name, age, score=0):
"""此方法用来给人对象添加'姓名', '年龄', '家庭住址'三个属性"""
<|body_0|>
def show_info(self):
"""显示此人的全部信息"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.name = name
self.age = age
self.score = score
<|... | stack_v2_sparse_classes_36k_train_023217 | 597 | no_license | [
{
"docstring": "此方法用来给人对象添加'姓名', '年龄', '家庭住址'三个属性",
"name": "set_info",
"signature": "def set_info(self, name, age, score=0)"
},
{
"docstring": "显示此人的全部信息",
"name": "show_info",
"signature": "def show_info(self)"
}
] | 2 | null | Implement the Python class `Human` described below.
Class description:
Implement the Human class.
Method signatures and docstrings:
- def set_info(self, name, age, score=0): 此方法用来给人对象添加'姓名', '年龄', '家庭住址'三个属性
- def show_info(self): 显示此人的全部信息 | Implement the Python class `Human` described below.
Class description:
Implement the Human class.
Method signatures and docstrings:
- def set_info(self, name, age, score=0): 此方法用来给人对象添加'姓名', '年龄', '家庭住址'三个属性
- def show_info(self): 显示此人的全部信息
<|skeleton|>
class Human:
def set_info(self, name, age, score=0):
... | 9b921c90b3003226d919017d521a32da47e546ad | <|skeleton|>
class Human:
def set_info(self, name, age, score=0):
"""此方法用来给人对象添加'姓名', '年龄', '家庭住址'三个属性"""
<|body_0|>
def show_info(self):
"""显示此人的全部信息"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Human:
def set_info(self, name, age, score=0):
"""此方法用来给人对象添加'姓名', '年龄', '家庭住址'三个属性"""
self.name = name
self.age = age
self.score = score
def show_info(self):
"""显示此人的全部信息"""
print('这个人的name是:', self.name)
print('这个人的age是:', self.age)
print(... | the_stack_v2_python_sparse | python/python017/excesice/Human.py | demo112/1807 | train | 0 | |
e9f85e9444611e7bbef2d8078118f116066da014 | [
"powerset = []\nself.generate_powerset(0, [], inputSet, powerset)\nreturn powerset",
"if current_index == len(input_set):\n powerset.append(deepcopy(selected_so_far))\n return\n\"\\n Recurse WITH the item at 'currentIndex' in the powerset we\\n are working on.\\n \"\nselected_so_far.app... | <|body_start_0|>
powerset = []
self.generate_powerset(0, [], inputSet, powerset)
return powerset
<|end_body_0|>
<|body_start_1|>
if current_index == len(input_set):
powerset.append(deepcopy(selected_so_far))
return
"\n Recurse WITH the item at 'cur... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def powerset(self, inputSet):
"""Interface ---- :type inputSet: list of int :rtype: list of list of int Approach ---- 1. Draw the recursion tree 2. Establish a policy and the associated logic to enforce at each stack frame 3. Establish constraints and backtracking conditions Co... | stack_v2_sparse_classes_36k_train_023218 | 2,563 | no_license | [
{
"docstring": "Interface ---- :type inputSet: list of int :rtype: list of list of int Approach ---- 1. Draw the recursion tree 2. Establish a policy and the associated logic to enforce at each stack frame 3. Establish constraints and backtracking conditions Complexity ---- Recurrence relation T(N) = 2T(N-1) + ... | 2 | stack_v2_sparse_classes_30k_train_002358 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def powerset(self, inputSet): Interface ---- :type inputSet: list of int :rtype: list of list of int Approach ---- 1. Draw the recursion tree 2. Establish a policy and the associ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def powerset(self, inputSet): Interface ---- :type inputSet: list of int :rtype: list of list of int Approach ---- 1. Draw the recursion tree 2. Establish a policy and the associ... | c0d49423885832b616ae3c7cd58e8f24c17cfd4d | <|skeleton|>
class Solution:
def powerset(self, inputSet):
"""Interface ---- :type inputSet: list of int :rtype: list of list of int Approach ---- 1. Draw the recursion tree 2. Establish a policy and the associated logic to enforce at each stack frame 3. Establish constraints and backtracking conditions Co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def powerset(self, inputSet):
"""Interface ---- :type inputSet: list of int :rtype: list of list of int Approach ---- 1. Draw the recursion tree 2. Establish a policy and the associated logic to enforce at each stack frame 3. Establish constraints and backtracking conditions Complexity ---- ... | the_stack_v2_python_sparse | backtracking_algorithms/powerSet.py | miaviles/Data-Structures-Algorithms-Python | train | 0 | |
800804dbcac42424c531c7ecd0932eed06f658ef | [
"q = [root]\nresult = []\nnode = root\nwhile q:\n node = q.pop(0)\n if not node:\n result.append('#')\n else:\n result.append(str(node.val))\n q.append(node.left)\n q.append(node.right)\nreturn ','.join(result)",
"der = data.split(',')\nif der[0] == '#':\n return None\nroot... | <|body_start_0|>
q = [root]
result = []
node = root
while q:
node = q.pop(0)
if not node:
result.append('#')
else:
result.append(str(node.val))
q.append(node.left)
q.append(node.right)
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_023219 | 2,737 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 085d868ba0458fc8e6b5549aa00fa151c335fa7f | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
q = [root]
result = []
node = root
while q:
node = q.pop(0)
if not node:
result.append('#')
else:
... | the_stack_v2_python_sparse | 297-Serialize_And_Deserialize_Binary_Tree.py | chanyoonzhu/leetcode-python | train | 0 | |
0b628c77d286dda1abc44743e47c5e54e5f716e5 | [
"self.node_dict: Dict[str, Node] = dict()\nself.root_nodes: Set[Node] = set()\nif isinstance(graph_description, ProcessGraph):\n self.title: str = graph_description.title\n self.description: str = graph_description.description\n self.build_process_graph_from_description(process_graph=graph_description.proc... | <|body_start_0|>
self.node_dict: Dict[str, Node] = dict()
self.root_nodes: Set[Node] = set()
if isinstance(graph_description, ProcessGraph):
self.title: str = graph_description.title
self.description: str = graph_description.description
self.build_process_grap... | This class represents a process graph | Graph | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Graph:
"""This class represents a process graph"""
def __init__(self, graph_description: Union[Dict, ProcessGraph]):
"""The constructor checks the validity of the provided dictionary and build the node interconnections :param graph_description:"""
<|body_0|>
def build_pr... | stack_v2_sparse_classes_36k_train_023220 | 19,905 | permissive | [
{
"docstring": "The constructor checks the validity of the provided dictionary and build the node interconnections :param graph_description:",
"name": "__init__",
"signature": "def __init__(self, graph_description: Union[Dict, ProcessGraph])"
},
{
"docstring": "Build the directed process graph f... | 3 | null | Implement the Python class `Graph` described below.
Class description:
This class represents a process graph
Method signatures and docstrings:
- def __init__(self, graph_description: Union[Dict, ProcessGraph]): The constructor checks the validity of the provided dictionary and build the node interconnections :param g... | Implement the Python class `Graph` described below.
Class description:
This class represents a process graph
Method signatures and docstrings:
- def __init__(self, graph_description: Union[Dict, ProcessGraph]): The constructor checks the validity of the provided dictionary and build the node interconnections :param g... | 3617a1d5e377ddae65cb24304cbc16edba98b8fb | <|skeleton|>
class Graph:
"""This class represents a process graph"""
def __init__(self, graph_description: Union[Dict, ProcessGraph]):
"""The constructor checks the validity of the provided dictionary and build the node interconnections :param graph_description:"""
<|body_0|>
def build_pr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Graph:
"""This class represents a process graph"""
def __init__(self, graph_description: Union[Dict, ProcessGraph]):
"""The constructor checks the validity of the provided dictionary and build the node interconnections :param graph_description:"""
self.node_dict: Dict[str, Node] = dict()
... | the_stack_v2_python_sparse | src/openeo_grass_gis_driver/actinia_processing/base.py | neteler/openeo-grassgis-driver | train | 0 |
cba579f9543b4d57b85f44d5047bb90a6325c79d | [
"if not prices:\n return 0\nmin_v = 10000000000.0\nres = 0\nfor i in prices:\n if min_v > i:\n min_v = i\n res = max(res, i - min_v)\nreturn res",
"iCurrentMax = 0\niFinalMax = 0\nfor i in range(len(prices) - 1):\n iCurrentMax += prices[i + 1] - prices[i]\n if iCurrentMax < 0:\n iCurr... | <|body_start_0|>
if not prices:
return 0
min_v = 10000000000.0
res = 0
for i in prices:
if min_v > i:
min_v = i
res = max(res, i - min_v)
return res
<|end_body_0|>
<|body_start_1|>
iCurrentMax = 0
iFinalMax = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit2(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not prices:
return 0
... | stack_v2_sparse_classes_36k_train_023221 | 1,353 | no_license | [
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
},
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit2",
"signature": "def maxProfit2(self, prices)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit2(self, prices): :type prices: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit2(self, prices): :type prices: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxPro... | db2d0b05020a1fcb9f0cfaf9386f79daeaad759e | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit2(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
if not prices:
return 0
min_v = 10000000000.0
res = 0
for i in prices:
if min_v > i:
min_v = i
res = max(res, i - min_v)
return r... | the_stack_v2_python_sparse | leetcode/dynamic_programming/121_max_profit.py | longgb246/MLlearn | train | 0 | |
7b2939b8f9f110f8b0456d73c8a6a377f9900c90 | [
"self._GC_TAG = 'GC'\nself._WORKFLOW_TAG = 'WORKFLOW'\nif not ctx or not hasattr(ctx, self._GC_TAG):\n self.ctx = DataContext(None, self._GC_TAG)\n self.ctx.update_context(None, self._WORKFLOW_TAG)\nself.wf_context = getattr(self.ctx, self._WORKFLOW_TAG)\nself.gc_context = getattr(self.ctx, self._GC_TAG)\nsel... | <|body_start_0|>
self._GC_TAG = 'GC'
self._WORKFLOW_TAG = 'WORKFLOW'
if not ctx or not hasattr(ctx, self._GC_TAG):
self.ctx = DataContext(None, self._GC_TAG)
self.ctx.update_context(None, self._WORKFLOW_TAG)
self.wf_context = getattr(self.ctx, self._WORKFLOW_TAG)
... | In this class we need to define all procedures which will be used in robot file security_automation.robot | BaseWorkflowDecommissionSecurityService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseWorkflowDecommissionSecurityService:
"""In this class we need to define all procedures which will be used in robot file security_automation.robot"""
def __init__(self, ctx=None):
"""Step 1: Create variables for both global and local yaml files to store data Step 2: Passes the var... | stack_v2_sparse_classes_36k_train_023222 | 5,362 | no_license | [
{
"docstring": "Step 1: Create variables for both global and local yaml files to store data Step 2: Passes the variables names to DataContext proc to assign values Args: :param ctx:",
"name": "__init__",
"signature": "def __init__(self, ctx=None)"
},
{
"docstring": "Description: At the end of th... | 4 | null | Implement the Python class `BaseWorkflowDecommissionSecurityService` described below.
Class description:
In this class we need to define all procedures which will be used in robot file security_automation.robot
Method signatures and docstrings:
- def __init__(self, ctx=None): Step 1: Create variables for both global ... | Implement the Python class `BaseWorkflowDecommissionSecurityService` described below.
Class description:
In this class we need to define all procedures which will be used in robot file security_automation.robot
Method signatures and docstrings:
- def __init__(self, ctx=None): Step 1: Create variables for both global ... | 93dd6d14ae4b0856aa7c6f059904cc1f13800e5f | <|skeleton|>
class BaseWorkflowDecommissionSecurityService:
"""In this class we need to define all procedures which will be used in robot file security_automation.robot"""
def __init__(self, ctx=None):
"""Step 1: Create variables for both global and local yaml files to store data Step 2: Passes the var... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseWorkflowDecommissionSecurityService:
"""In this class we need to define all procedures which will be used in robot file security_automation.robot"""
def __init__(self, ctx=None):
"""Step 1: Create variables for both global and local yaml files to store data Step 2: Passes the variables names ... | the_stack_v2_python_sparse | automation_framework/workflow/baseworkflow_decommission_security_service.py | vijaymaddukuri/python_repo | train | 0 |
f60ffd73766652aa362fc12229e2e3393a4a99a3 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn UserExperienceAnalyticsAppHealthDevicePerformanceDetails()",
"from .entity import Entity\nfrom .entity import Entity\nfields: Dict[str, Callable[[Any], None]] = {'appDisplayName': lambda n: setattr(self, 'app_display_name', n.get_str_v... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return UserExperienceAnalyticsAppHealthDevicePerformanceDetails()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .entity import Entity
fields: Dict[str, Callable[[Any],... | The user experience analytics device performance entity contains device performance details. | UserExperienceAnalyticsAppHealthDevicePerformanceDetails | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserExperienceAnalyticsAppHealthDevicePerformanceDetails:
"""The user experience analytics device performance entity contains device performance details."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsAppHealthDevicePerformanceDetails:
... | stack_v2_sparse_classes_36k_train_023223 | 4,377 | 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: UserExperienceAnalyticsAppHealthDevicePerformanceDetails",
"name": "create_from_discriminator_value",
"signa... | 3 | stack_v2_sparse_classes_30k_train_000171 | Implement the Python class `UserExperienceAnalyticsAppHealthDevicePerformanceDetails` described below.
Class description:
The user experience analytics device performance entity contains device performance details.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]... | Implement the Python class `UserExperienceAnalyticsAppHealthDevicePerformanceDetails` described below.
Class description:
The user experience analytics device performance entity contains device performance details.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class UserExperienceAnalyticsAppHealthDevicePerformanceDetails:
"""The user experience analytics device performance entity contains device performance details."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsAppHealthDevicePerformanceDetails:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserExperienceAnalyticsAppHealthDevicePerformanceDetails:
"""The user experience analytics device performance entity contains device performance details."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsAppHealthDevicePerformanceDetails:
"""Cr... | the_stack_v2_python_sparse | msgraph/generated/models/user_experience_analytics_app_health_device_performance_details.py | microsoftgraph/msgraph-sdk-python | train | 135 |
9fb988b6703110718bf886b478a08db6a2636d45 | [
"if K == 0:\n return 1\ndp = [1.0] + [0.0] * N\nW_sum = 1.0\nfor i in range(1, N + 1):\n dp[i] = W_sum / W\n if i < K:\n W_sum += dp[i]\n if 0 <= i - W < K:\n W_sum -= dp[i - W]\nreturn sum(dp[K:])",
"def calculate(n, k, w):\n if (n, k) in records:\n return records[n, k]\n e... | <|body_start_0|>
if K == 0:
return 1
dp = [1.0] + [0.0] * N
W_sum = 1.0
for i in range(1, N + 1):
dp[i] = W_sum / W
if i < K:
W_sum += dp[i]
if 0 <= i - W < K:
W_sum -= dp[i - W]
return sum(dp[K:])
<|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def new21Game(self, N, K, W):
""":type N: int :type K: int :type W: int :rtype: float"""
<|body_0|>
def new21Game_failed(self, N, K, W):
""":type N: int :type K: int :type W: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_023224 | 2,405 | no_license | [
{
"docstring": ":type N: int :type K: int :type W: int :rtype: float",
"name": "new21Game",
"signature": "def new21Game(self, N, K, W)"
},
{
"docstring": ":type N: int :type K: int :type W: int :rtype: float",
"name": "new21Game_failed",
"signature": "def new21Game_failed(self, N, K, W)"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def new21Game(self, N, K, W): :type N: int :type K: int :type W: int :rtype: float
- def new21Game_failed(self, N, K, W): :type N: int :type K: int :type W: int :rtype: float | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def new21Game(self, N, K, W): :type N: int :type K: int :type W: int :rtype: float
- def new21Game_failed(self, N, K, W): :type N: int :type K: int :type W: int :rtype: float
<|... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def new21Game(self, N, K, W):
""":type N: int :type K: int :type W: int :rtype: float"""
<|body_0|>
def new21Game_failed(self, N, K, W):
""":type N: int :type K: int :type W: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def new21Game(self, N, K, W):
""":type N: int :type K: int :type W: int :rtype: float"""
if K == 0:
return 1
dp = [1.0] + [0.0] * N
W_sum = 1.0
for i in range(1, N + 1):
dp[i] = W_sum / W
if i < K:
W_sum += d... | the_stack_v2_python_sparse | src/lt_837.py | oxhead/CodingYourWay | train | 0 | |
e311bd10e2c0c89fdde8f8a392a818c288b97475 | [
"ans = []\nfactor = [1]\nfor i in range(2, n):\n factor.append(factor[-1] * i)\ncandi = [i for i in range(1, n + 1)]\ni = n - 2\nwhile candi:\n index, k = divmod(k, factor[i])\n if factor[i] == 1 or k == 0:\n index -= 1\n ans.append(str(candi[index]))\n candi.remove(candi[index])\n i -= 1\n... | <|body_start_0|>
ans = []
factor = [1]
for i in range(2, n):
factor.append(factor[-1] * i)
candi = [i for i in range(1, n + 1)]
i = n - 2
while candi:
index, k = divmod(k, factor[i])
if factor[i] == 1 or k == 0:
index -=... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getPermutation_1(self, n, k):
""":type n: int :type k: int :rtype: str"""
<|body_0|>
def getPermutation_k_subtract_one_first(self, n, k):
""":type n: int :type k: int :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ans = []... | stack_v2_sparse_classes_36k_train_023225 | 1,478 | no_license | [
{
"docstring": ":type n: int :type k: int :rtype: str",
"name": "getPermutation_1",
"signature": "def getPermutation_1(self, n, k)"
},
{
"docstring": ":type n: int :type k: int :rtype: str",
"name": "getPermutation_k_subtract_one_first",
"signature": "def getPermutation_k_subtract_one_fi... | 2 | stack_v2_sparse_classes_30k_train_001089 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getPermutation_1(self, n, k): :type n: int :type k: int :rtype: str
- def getPermutation_k_subtract_one_first(self, n, k): :type n: int :type k: int :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getPermutation_1(self, n, k): :type n: int :type k: int :rtype: str
- def getPermutation_k_subtract_one_first(self, n, k): :type n: int :type k: int :rtype: str
<|skeleton|>... | 0e99f9a5226507706b3ee66fd04bae813755ef40 | <|skeleton|>
class Solution:
def getPermutation_1(self, n, k):
""":type n: int :type k: int :rtype: str"""
<|body_0|>
def getPermutation_k_subtract_one_first(self, n, k):
""":type n: int :type k: int :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def getPermutation_1(self, n, k):
""":type n: int :type k: int :rtype: str"""
ans = []
factor = [1]
for i in range(2, n):
factor.append(factor[-1] * i)
candi = [i for i in range(1, n + 1)]
i = n - 2
while candi:
index, k... | the_stack_v2_python_sparse | medium/math/test_60_Permutation_Sequence.py | wuxu1019/leetcode_sophia | train | 1 | |
e9ae4336674e6b012f9f2f3d5ccfed0d10133d3f | [
"self.connectivityBoundaries = None\nself.connectivityConnections = None\nself.hierarchyBoundaries = None\nself.dualHierarchyBoundaries = None\nself.hierarchyConnections = None\nself.dualHierarchyConnections = None\nself.contacts = None",
"self.connectivityBoundaries = Cluster.clusterBoundaries(contacts=contacts)... | <|body_start_0|>
self.connectivityBoundaries = None
self.connectivityConnections = None
self.hierarchyBoundaries = None
self.dualHierarchyBoundaries = None
self.hierarchyConnections = None
self.dualHierarchyConnections = None
self.contacts = None
<|end_body_0|>
<... | An instance of this class can contain up to six different clusterings of the same data (see below) Clusters can be formed in the following ways: 1) Clustering based on connectivity All boundaries that are linked to each other via connections (connectors) form a boundary cluster. In the same way, all connections that ar... | MultiCluster | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiCluster:
"""An instance of this class can contain up to six different clusterings of the same data (see below) Clusters can be formed in the following ways: 1) Clustering based on connectivity All boundaries that are linked to each other via connections (connectors) form a boundary cluster. ... | stack_v2_sparse_classes_36k_train_023226 | 15,116 | permissive | [
{
"docstring": "Initializes attributes",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Clusters boundaries and connections based on connectivity. Arguments: - contacts: (Contacts) specifies contacts between connections and boundaries - topology: if True calculates topo... | 4 | stack_v2_sparse_classes_30k_train_006669 | Implement the Python class `MultiCluster` described below.
Class description:
An instance of this class can contain up to six different clusterings of the same data (see below) Clusters can be formed in the following ways: 1) Clustering based on connectivity All boundaries that are linked to each other via connections... | Implement the Python class `MultiCluster` described below.
Class description:
An instance of this class can contain up to six different clusterings of the same data (see below) Clusters can be formed in the following ways: 1) Clustering based on connectivity All boundaries that are linked to each other via connections... | 1370bfedae2ad5e6cdd1dc08395eb9e95b4a8596 | <|skeleton|>
class MultiCluster:
"""An instance of this class can contain up to six different clusterings of the same data (see below) Clusters can be formed in the following ways: 1) Clustering based on connectivity All boundaries that are linked to each other via connections (connectors) form a boundary cluster. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiCluster:
"""An instance of this class can contain up to six different clusterings of the same data (see below) Clusters can be formed in the following ways: 1) Clustering based on connectivity All boundaries that are linked to each other via connections (connectors) form a boundary cluster. In the same w... | the_stack_v2_python_sparse | code/pyto/scene/multi_cluster.py | anmartinezs/pyseg_system | train | 15 |
8cc2cc6a2ff2ca5c7df26651b2f9d49741f71e3a | [
"env = DummyEnvironment()\nenv['BUILDERS'] = {}\nenv['ENV'] = {}\nenv['PLATFORM'] = 'test'\nt = SCons.Tool.Tool('g++')\nt(env)\nassert env['CXX'] == 'c++' or env['CXX'] == 'g++', env['CXX']\nassert env['INCPREFIX'] == '-I', env['INCPREFIX']\nassert env['TOOLS'] == ['g++'], env['TOOLS']\nexc_caught = None\ntry:\n ... | <|body_start_0|>
env = DummyEnvironment()
env['BUILDERS'] = {}
env['ENV'] = {}
env['PLATFORM'] = 'test'
t = SCons.Tool.Tool('g++')
t(env)
assert env['CXX'] == 'c++' or env['CXX'] == 'g++', env['CXX']
assert env['INCPREFIX'] == '-I', env['INCPREFIX']
... | ToolTestCase | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ToolTestCase:
def test_Tool(self) -> None:
"""Test the Tool() function"""
<|body_0|>
def test_pathfind(self) -> None:
"""Test that find_program_path() alters PATH only if add_path is true"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
env = DummyEn... | stack_v2_sparse_classes_36k_train_023227 | 4,598 | permissive | [
{
"docstring": "Test the Tool() function",
"name": "test_Tool",
"signature": "def test_Tool(self) -> None"
},
{
"docstring": "Test that find_program_path() alters PATH only if add_path is true",
"name": "test_pathfind",
"signature": "def test_pathfind(self) -> None"
}
] | 2 | stack_v2_sparse_classes_30k_train_003152 | Implement the Python class `ToolTestCase` described below.
Class description:
Implement the ToolTestCase class.
Method signatures and docstrings:
- def test_Tool(self) -> None: Test the Tool() function
- def test_pathfind(self) -> None: Test that find_program_path() alters PATH only if add_path is true | Implement the Python class `ToolTestCase` described below.
Class description:
Implement the ToolTestCase class.
Method signatures and docstrings:
- def test_Tool(self) -> None: Test the Tool() function
- def test_pathfind(self) -> None: Test that find_program_path() alters PATH only if add_path is true
<|skeleton|>
... | b2a7d7066a2b854460a334a5fe737ea389655e6e | <|skeleton|>
class ToolTestCase:
def test_Tool(self) -> None:
"""Test the Tool() function"""
<|body_0|>
def test_pathfind(self) -> None:
"""Test that find_program_path() alters PATH only if add_path is true"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ToolTestCase:
def test_Tool(self) -> None:
"""Test the Tool() function"""
env = DummyEnvironment()
env['BUILDERS'] = {}
env['ENV'] = {}
env['PLATFORM'] = 'test'
t = SCons.Tool.Tool('g++')
t(env)
assert env['CXX'] == 'c++' or env['CXX'] == 'g++', ... | the_stack_v2_python_sparse | SCons/Tool/ToolTests.py | SCons/scons | train | 1,827 | |
607c23fcead3d3f2d4a4b0e88524a3708a921c0d | [
"self.index_map = defaultdict(list)\nfor i, word in enumerate(words):\n self.index_map[word].append(i)",
"list1 = self.index_map[word1]\nlist2 = self.index_map[word2]\ni, j = (0, 0)\nret = sys.maxsize\nwhile i < len(list1) and j < len(list2):\n idx1, idx2 = (list1[i], list2[j])\n if idx1 < idx2:\n ... | <|body_start_0|>
self.index_map = defaultdict(list)
for i, word in enumerate(words):
self.index_map[word].append(i)
<|end_body_0|>
<|body_start_1|>
list1 = self.index_map[word1]
list2 = self.index_map[word2]
i, j = (0, 0)
ret = sys.maxsize
while i < l... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.index_map = defaultdict(list)
... | stack_v2_sparse_classes_36k_train_023228 | 1,574 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortest(self, word1, word2)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000221 | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
<|skeleton|>
class WordDistance:
... | 7de5f69e6e44ca4e74d75fed2af390b3d2cbd2b9 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
self.index_map = defaultdict(list)
for i, word in enumerate(words):
self.index_map[word].append(i)
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
... | the_stack_v2_python_sparse | interview/linkedin/mid/LC244. Shortest Word Distance II.py | zhangshv123/superjump | train | 1 | |
a5a58165b6103e641547229a1f480598e0ecb48e | [
"self.myDict = {}\nself.minmaxHeap = []\nself.removed = set()",
"if key in self.myDict:\n self.myDict[key] += 1\n self.removed.add((self.myDict[key] - 1, key))\nelse:\n self.myDict[key] = 1\nhq.heappush(self.minmaxHeap, (self.myDict[key], key))",
"if key in self.myDict and self.myDict[key] > 1:\n se... | <|body_start_0|>
self.myDict = {}
self.minmaxHeap = []
self.removed = set()
<|end_body_0|>
<|body_start_1|>
if key in self.myDict:
self.myDict[key] += 1
self.removed.add((self.myDict[key] - 1, key))
else:
self.myDict[key] = 1
hq.heappu... | AllOne | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AllOne:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def inc(self, key: str) -> None:
"""Inserts a new key <Key> with value 1. Or increments an existing key by 1."""
<|body_1|>
def dec(self, key: str) -> None:
"""Decr... | stack_v2_sparse_classes_36k_train_023229 | 6,063 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a new key <Key> with value 1. Or increments an existing key by 1.",
"name": "inc",
"signature": "def inc(self, key: str) -> None"
},
{
"docstrin... | 5 | stack_v2_sparse_classes_30k_train_020614 | Implement the Python class `AllOne` described below.
Class description:
Implement the AllOne class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def inc(self, key: str) -> None: Inserts a new key <Key> with value 1. Or increments an existing key by 1.
- def dec(self, ... | Implement the Python class `AllOne` described below.
Class description:
Implement the AllOne class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def inc(self, key: str) -> None: Inserts a new key <Key> with value 1. Or increments an existing key by 1.
- def dec(self, ... | 1a961afb22f482e6b920256fa5d14154e5e1a940 | <|skeleton|>
class AllOne:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def inc(self, key: str) -> None:
"""Inserts a new key <Key> with value 1. Or increments an existing key by 1."""
<|body_1|>
def dec(self, key: str) -> None:
"""Decr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AllOne:
def __init__(self):
"""Initialize your data structure here."""
self.myDict = {}
self.minmaxHeap = []
self.removed = set()
def inc(self, key: str) -> None:
"""Inserts a new key <Key> with value 1. Or increments an existing key by 1."""
if key in self... | the_stack_v2_python_sparse | Difficult/432. All O`one Data Structure.py | rghv404/leet_code | train | 0 | |
406a695068149c4bc87f611bf748e9c2fcabd7cc | [
"tmp = self.head.next\nself.head.next = node\nnode.prev = self.head\nnode.next = tmp\ntmp.prev = node",
"node.prev.next = node.next\nnode.next.prev = node.prev\nnode.prev = node.next = None",
"self.cap = capacity\nself.cnt = 0\nself.key_to_node = {}\nself.head = Node(None, None)\nself.tail = Node(None, None)\ns... | <|body_start_0|>
tmp = self.head.next
self.head.next = node
node.prev = self.head
node.next = tmp
tmp.prev = node
<|end_body_0|>
<|body_start_1|>
node.prev.next = node.next
node.next.prev = node.prev
node.prev = node.next = None
<|end_body_1|>
<|body_sta... | Use a dictionary and a double linked list to keep record of LRU; Add two functions addNode and removeNode and all the operations with the double linked list can be done using these two functions. The dictionary stores key to node instead of key to value to save the effort of locating a value in the double linked list. ... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
"""Use a dictionary and a double linked list to keep record of LRU; Add two functions addNode and removeNode and all the operations with the double linked list can be done using these two functions. The dictionary stores key to node instead of key to value to save the effort of locating... | stack_v2_sparse_classes_36k_train_023230 | 9,208 | no_license | [
{
"docstring": "Add a node after head of the list",
"name": "addNode",
"signature": "def addNode(self, node)"
},
{
"docstring": "Remove a node from the list",
"name": "removeNode",
"signature": "def removeNode(self, node)"
},
{
"docstring": ":type capacity: int",
"name": "__i... | 5 | stack_v2_sparse_classes_30k_train_000794 | Implement the Python class `LRUCache` described below.
Class description:
Use a dictionary and a double linked list to keep record of LRU; Add two functions addNode and removeNode and all the operations with the double linked list can be done using these two functions. The dictionary stores key to node instead of key ... | Implement the Python class `LRUCache` described below.
Class description:
Use a dictionary and a double linked list to keep record of LRU; Add two functions addNode and removeNode and all the operations with the double linked list can be done using these two functions. The dictionary stores key to node instead of key ... | d634941087bc51869f43c0d8044db09b7bdbaf58 | <|skeleton|>
class LRUCache:
"""Use a dictionary and a double linked list to keep record of LRU; Add two functions addNode and removeNode and all the operations with the double linked list can be done using these two functions. The dictionary stores key to node instead of key to value to save the effort of locating... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
"""Use a dictionary and a double linked list to keep record of LRU; Add two functions addNode and removeNode and all the operations with the double linked list can be done using these two functions. The dictionary stores key to node instead of key to value to save the effort of locating a value in t... | the_stack_v2_python_sparse | 146_LRU_Cache.py | susunini/leetcode | train | 1 |
590de1da847d4ec936f214f16baddd17fcbc6d7d | [
"exito = False\nbd = MySQLConnector.MySQLConnector()\nconsulta1 = ('SELECT IdGrupo FROM Alumno_Grupo WHERE Dni=%s;', (p_dni,))\nrespuesta_bd = bd.execute(consulta1)\nif len(respuesta_bd) == 0:\n consulta2 = ('DELETE FROM Alumno WHERE Dni=%s;', (p_dni,))\n respuesta_bd2 = bd.execute(consulta2)\n if respuest... | <|body_start_0|>
exito = False
bd = MySQLConnector.MySQLConnector()
consulta1 = ('SELECT IdGrupo FROM Alumno_Grupo WHERE Dni=%s;', (p_dni,))
respuesta_bd = bd.execute(consulta1)
if len(respuesta_bd) == 0:
consulta2 = ('DELETE FROM Alumno WHERE Dni=%s;', (p_dni,))
... | GestorAlumno | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GestorAlumno:
def borrar_alumno(self, p_dni):
"""La función verifica si el alumno pertenece a algún grupo. De no pertenecer lo borra del sistema. :param p_dni: El Dni del alumno :return: True o False indicando el exito de la operación"""
<|body_0|>
def obtener_alumno(self, p... | stack_v2_sparse_classes_36k_train_023231 | 2,270 | no_license | [
{
"docstring": "La función verifica si el alumno pertenece a algún grupo. De no pertenecer lo borra del sistema. :param p_dni: El Dni del alumno :return: True o False indicando el exito de la operación",
"name": "borrar_alumno",
"signature": "def borrar_alumno(self, p_dni)"
},
{
"docstring": "Da... | 3 | stack_v2_sparse_classes_30k_train_019074 | Implement the Python class `GestorAlumno` described below.
Class description:
Implement the GestorAlumno class.
Method signatures and docstrings:
- def borrar_alumno(self, p_dni): La función verifica si el alumno pertenece a algún grupo. De no pertenecer lo borra del sistema. :param p_dni: El Dni del alumno :return: ... | Implement the Python class `GestorAlumno` described below.
Class description:
Implement the GestorAlumno class.
Method signatures and docstrings:
- def borrar_alumno(self, p_dni): La función verifica si el alumno pertenece a algún grupo. De no pertenecer lo borra del sistema. :param p_dni: El Dni del alumno :return: ... | 7fa252a193b934fd192763b6168bb48eb4542aed | <|skeleton|>
class GestorAlumno:
def borrar_alumno(self, p_dni):
"""La función verifica si el alumno pertenece a algún grupo. De no pertenecer lo borra del sistema. :param p_dni: El Dni del alumno :return: True o False indicando el exito de la operación"""
<|body_0|>
def obtener_alumno(self, p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GestorAlumno:
def borrar_alumno(self, p_dni):
"""La función verifica si el alumno pertenece a algún grupo. De no pertenecer lo borra del sistema. :param p_dni: El Dni del alumno :return: True o False indicando el exito de la operación"""
exito = False
bd = MySQLConnector.MySQLConnector... | the_stack_v2_python_sparse | src/packControladoras/GestorAlumno.py | rubenmulero/Akeko_Admin | train | 0 | |
57febc7b7d328744369c68beae40c2f58295da73 | [
"if cosmo is not None:\n self.cosmo = cosmo\nelse:\n self.cosmo = conversions.Cosmo_Conversions()",
"pspec_freqs = np.linspace(lower_freq, upper_freq, num_freqs, endpoint=False)\nomega_ratio = self.power_beam_sq_int(pol) / self.power_beam_int(pol) ** 2\nscalar = _compute_pspec_scalar(self.cosmo, self.beam_f... | <|body_start_0|>
if cosmo is not None:
self.cosmo = cosmo
else:
self.cosmo = conversions.Cosmo_Conversions()
<|end_body_0|>
<|body_start_1|>
pspec_freqs = np.linspace(lower_freq, upper_freq, num_freqs, endpoint=False)
omega_ratio = self.power_beam_sq_int(pol) / s... | PSpecBeamBase | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PSpecBeamBase:
def __init__(self, cosmo=None):
"""Base class for PSpecBeam objects. Provides compute_pspec_scalar() method to integrate over and interpolate beam solid angles, and Jy_to_mK() method to convert units. Parameters ---------- cosmo : conversions.Cosmo_Conversions object, opti... | stack_v2_sparse_classes_36k_train_023232 | 29,545 | permissive | [
{
"docstring": "Base class for PSpecBeam objects. Provides compute_pspec_scalar() method to integrate over and interpolate beam solid angles, and Jy_to_mK() method to convert units. Parameters ---------- cosmo : conversions.Cosmo_Conversions object, optional Cosmology object. Uses the default cosmology object i... | 4 | stack_v2_sparse_classes_30k_test_000654 | Implement the Python class `PSpecBeamBase` described below.
Class description:
Implement the PSpecBeamBase class.
Method signatures and docstrings:
- def __init__(self, cosmo=None): Base class for PSpecBeam objects. Provides compute_pspec_scalar() method to integrate over and interpolate beam solid angles, and Jy_to_... | Implement the Python class `PSpecBeamBase` described below.
Class description:
Implement the PSpecBeamBase class.
Method signatures and docstrings:
- def __init__(self, cosmo=None): Base class for PSpecBeam objects. Provides compute_pspec_scalar() method to integrate over and interpolate beam solid angles, and Jy_to_... | 482c31c5b1ead911d521f514b6e6a700b9fab17e | <|skeleton|>
class PSpecBeamBase:
def __init__(self, cosmo=None):
"""Base class for PSpecBeam objects. Provides compute_pspec_scalar() method to integrate over and interpolate beam solid angles, and Jy_to_mK() method to convert units. Parameters ---------- cosmo : conversions.Cosmo_Conversions object, opti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PSpecBeamBase:
def __init__(self, cosmo=None):
"""Base class for PSpecBeam objects. Provides compute_pspec_scalar() method to integrate over and interpolate beam solid angles, and Jy_to_mK() method to convert units. Parameters ---------- cosmo : conversions.Cosmo_Conversions object, optional Cosmology... | the_stack_v2_python_sparse | hera_pspec/pspecbeam.py | HERA-Team/hera_pspec | train | 11 | |
25e542625302c0114caa5a8dba96a7d89f6b14d8 | [
"self.max_matching = max_matching\nself.words = None\nself.word_dictionary = WordDictionary()\nself.disambiguate = Disambiguate()\nself.matching = None",
"self.word_dictionary.fit(dataset)\nself.words = self.word_dictionary.get_dictionary()\nself.matching = Matching(self.words, self.max_matching)\nself.word_dicti... | <|body_start_0|>
self.max_matching = max_matching
self.words = None
self.word_dictionary = WordDictionary()
self.disambiguate = Disambiguate()
self.matching = None
<|end_body_0|>
<|body_start_1|>
self.word_dictionary.fit(dataset)
self.words = self.word_dictionary... | DictSegmentation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DictSegmentation:
def __init__(self, max_matching=MAX_MATCHING):
"""初始化对象 :param max_matching: (int, optional, default=10) 词的最大匹配长度。用于在正向匹配和逆向匹配中对词进行划分"""
<|body_0|>
def fit(self, dataset, save_model='DictSegmentation.pickle'):
"""拟合词典 :param dataset: (list of list, ... | stack_v2_sparse_classes_36k_train_023233 | 7,309 | no_license | [
{
"docstring": "初始化对象 :param max_matching: (int, optional, default=10) 词的最大匹配长度。用于在正向匹配和逆向匹配中对词进行划分",
"name": "__init__",
"signature": "def __init__(self, max_matching=MAX_MATCHING)"
},
{
"docstring": "拟合词典 :param dataset: (list of list, mandatory) 训练数据集 :param save_model: (str, optional, defaul... | 6 | stack_v2_sparse_classes_30k_train_006301 | Implement the Python class `DictSegmentation` described below.
Class description:
Implement the DictSegmentation class.
Method signatures and docstrings:
- def __init__(self, max_matching=MAX_MATCHING): 初始化对象 :param max_matching: (int, optional, default=10) 词的最大匹配长度。用于在正向匹配和逆向匹配中对词进行划分
- def fit(self, dataset, save_m... | Implement the Python class `DictSegmentation` described below.
Class description:
Implement the DictSegmentation class.
Method signatures and docstrings:
- def __init__(self, max_matching=MAX_MATCHING): 初始化对象 :param max_matching: (int, optional, default=10) 词的最大匹配长度。用于在正向匹配和逆向匹配中对词进行划分
- def fit(self, dataset, save_m... | 8a4f4ac6ae32caa4098da067b7c4a7bd86f01973 | <|skeleton|>
class DictSegmentation:
def __init__(self, max_matching=MAX_MATCHING):
"""初始化对象 :param max_matching: (int, optional, default=10) 词的最大匹配长度。用于在正向匹配和逆向匹配中对词进行划分"""
<|body_0|>
def fit(self, dataset, save_model='DictSegmentation.pickle'):
"""拟合词典 :param dataset: (list of list, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DictSegmentation:
def __init__(self, max_matching=MAX_MATCHING):
"""初始化对象 :param max_matching: (int, optional, default=10) 词的最大匹配长度。用于在正向匹配和逆向匹配中对词进行划分"""
self.max_matching = max_matching
self.words = None
self.word_dictionary = WordDictionary()
self.disambiguate = Disa... | the_stack_v2_python_sparse | module/segmentation/dict/dict_segmentation.py | boyshen/BLTP | train | 2 | |
1b6ba4a0e8c4993d17518255b568cd541ba12ddc | [
"super(_EventCallbackManager, self).validate_callback(callback)\nif isinstance(callback, (type, types.ClassType)):\n if not issubclass(callback, EventCallback):\n raise ValueError('Type mismatch on callback argument')\nelif not issubclass(callback.__class__, EventCallback):\n raise ValueError('Type mis... | <|body_start_0|>
super(_EventCallbackManager, self).validate_callback(callback)
if isinstance(callback, (type, types.ClassType)):
if not issubclass(callback, EventCallback):
raise ValueError('Type mismatch on callback argument')
elif not issubclass(callback.__class__,... | Manager for {@link EventCallback} message callbacks. | _EventCallbackManager | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _EventCallbackManager:
"""Manager for {@link EventCallback} message callbacks."""
def validate_callback(self, callback):
"""Validates if `callback` is a valid EventCallback. :param callback: Callback to validate."""
<|body_0|>
def handle_fire(self, event_callback, event)... | stack_v2_sparse_classes_36k_train_023234 | 12,867 | permissive | [
{
"docstring": "Validates if `callback` is a valid EventCallback. :param callback: Callback to validate.",
"name": "validate_callback",
"signature": "def validate_callback(self, callback)"
},
{
"docstring": "Runs `event_callback` for `event`. :param event_callback: {@link dxlclient.callbacks.Eve... | 2 | stack_v2_sparse_classes_30k_train_017318 | Implement the Python class `_EventCallbackManager` described below.
Class description:
Manager for {@link EventCallback} message callbacks.
Method signatures and docstrings:
- def validate_callback(self, callback): Validates if `callback` is a valid EventCallback. :param callback: Callback to validate.
- def handle_f... | Implement the Python class `_EventCallbackManager` described below.
Class description:
Manager for {@link EventCallback} message callbacks.
Method signatures and docstrings:
- def validate_callback(self, callback): Validates if `callback` is a valid EventCallback. :param callback: Callback to validate.
- def handle_f... | 7bbc003592022f5776006d467f591a214a119013 | <|skeleton|>
class _EventCallbackManager:
"""Manager for {@link EventCallback} message callbacks."""
def validate_callback(self, callback):
"""Validates if `callback` is a valid EventCallback. :param callback: Callback to validate."""
<|body_0|>
def handle_fire(self, event_callback, event)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _EventCallbackManager:
"""Manager for {@link EventCallback} message callbacks."""
def validate_callback(self, callback):
"""Validates if `callback` is a valid EventCallback. :param callback: Callback to validate."""
super(_EventCallbackManager, self).validate_callback(callback)
if... | the_stack_v2_python_sparse | src/main/resources/dxlclient/_callback_manager.py | att/OpenDXLJythonClient | train | 4 |
095b1995c6c41bed7167d23e4e3be5ed80b2bfc9 | [
"value_list = []\ncurrent = head\nwhile current:\n value_list.append(current.val)\n current = current.next\nreturn self.isPalindromeList(value_list)",
"length = len(value_list) // 2\nif length <= 0:\n return True\nreturn value_list[:length] == value_list[-length:][::-1]"
] | <|body_start_0|>
value_list = []
current = head
while current:
value_list.append(current.val)
current = current.next
return self.isPalindromeList(value_list)
<|end_body_0|>
<|body_start_1|>
length = len(value_list) // 2
if length <= 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome(self, head):
""":type head: ListNode :rtype: bool"""
<|body_0|>
def isPalindromeList(self, value_list):
""":type head: ListNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
value_list = []
current =... | stack_v2_sparse_classes_36k_train_023235 | 766 | no_license | [
{
"docstring": ":type head: ListNode :rtype: bool",
"name": "isPalindrome",
"signature": "def isPalindrome(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: bool",
"name": "isPalindromeList",
"signature": "def isPalindromeList(self, value_list)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, head): :type head: ListNode :rtype: bool
- def isPalindromeList(self, value_list): :type head: ListNode :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, head): :type head: ListNode :rtype: bool
- def isPalindromeList(self, value_list): :type head: ListNode :rtype: bool
<|skeleton|>
class Solution:
def... | 9f53994d8a123003d5f12a76cf375982cee52806 | <|skeleton|>
class Solution:
def isPalindrome(self, head):
""":type head: ListNode :rtype: bool"""
<|body_0|>
def isPalindromeList(self, value_list):
""":type head: ListNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isPalindrome(self, head):
""":type head: ListNode :rtype: bool"""
value_list = []
current = head
while current:
value_list.append(current.val)
current = current.next
return self.isPalindromeList(value_list)
def isPalindromeList... | the_stack_v2_python_sparse | Algorithms/Q234_Palindrome_Linked_List.py | filosfino/leetcode | train | 1 | |
426b6b5fd6f52cf31624f1d61dd9662b0a8a2499 | [
"values = super(MultipleChoiceQuestionSerializer, self).to_representation(obj)\nanswers = obj.answer_set()\nvalues['answers'] = MultipleChoiceAnswerSerializer(answers, many=True).data\nreturn values",
"answers = validated_data.pop('answers')\nquestion = MultipleChoiceQuestion(**validated_data)\nquestion.module = ... | <|body_start_0|>
values = super(MultipleChoiceQuestionSerializer, self).to_representation(obj)
answers = obj.answer_set()
values['answers'] = MultipleChoiceAnswerSerializer(answers, many=True).data
return values
<|end_body_0|>
<|body_start_1|>
answers = validated_data.pop('answe... | Serializer for MultipleChoice questions editing :author: Leon Wiedmann | MultipleChoiceQuestionSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultipleChoiceQuestionSerializer:
"""Serializer for MultipleChoice questions editing :author: Leon Wiedmann"""
def to_representation(self, obj):
"""responsible for json serialization of objects :author: Leonhard Wiedmann :param obj: the object that should be serialized :return: a jso... | stack_v2_sparse_classes_36k_train_023236 | 3,942 | no_license | [
{
"docstring": "responsible for json serialization of objects :author: Leonhard Wiedmann :param obj: the object that should be serialized :return: a json representation of the object",
"name": "to_representation",
"signature": "def to_representation(self, obj)"
},
{
"docstring": "creating new da... | 2 | stack_v2_sparse_classes_30k_train_005311 | Implement the Python class `MultipleChoiceQuestionSerializer` described below.
Class description:
Serializer for MultipleChoice questions editing :author: Leon Wiedmann
Method signatures and docstrings:
- def to_representation(self, obj): responsible for json serialization of objects :author: Leonhard Wiedmann :param... | Implement the Python class `MultipleChoiceQuestionSerializer` described below.
Class description:
Serializer for MultipleChoice questions editing :author: Leon Wiedmann
Method signatures and docstrings:
- def to_representation(self, obj): responsible for json serialization of objects :author: Leonhard Wiedmann :param... | 6fc102c6841449dd9782183b22340d1f1cb7c5c4 | <|skeleton|>
class MultipleChoiceQuestionSerializer:
"""Serializer for MultipleChoice questions editing :author: Leon Wiedmann"""
def to_representation(self, obj):
"""responsible for json serialization of objects :author: Leonhard Wiedmann :param obj: the object that should be serialized :return: a jso... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultipleChoiceQuestionSerializer:
"""Serializer for MultipleChoice questions editing :author: Leon Wiedmann"""
def to_representation(self, obj):
"""responsible for json serialization of objects :author: Leonhard Wiedmann :param obj: the object that should be serialized :return: a json representat... | the_stack_v2_python_sparse | django/learning_base/multiple_choice/serializer.py | cvoelcker/clonecademy | train | 2 |
2b94d517c540d730685d3e8babb9792825371c80 | [
"N = len(board)\nqueue = collections.deque([(1, 0)])\nvisited = {1}\nwhile queue:\n cur_num, dist = queue.popleft()\n if cur_num == N * N:\n return dist\n for next_num in range(cur_num + 1, min(cur_num + 6, N * N) + 1):\n r, c = self.get_coordinates(next_num, N)\n if board[r][c] != -1:... | <|body_start_0|>
N = len(board)
queue = collections.deque([(1, 0)])
visited = {1}
while queue:
cur_num, dist = queue.popleft()
if cur_num == N * N:
return dist
for next_num in range(cur_num + 1, min(cur_num + 6, N * N) + 1):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def snakesAndLadders(self, board):
""":type board: List[List[int]] :rtype: int"""
<|body_0|>
def get_coordinates(self, num, N):
"""Given a number, return the board coordinates (r, c) the row changes every N squares, and so is only based on quot = (s2-1) / N... | stack_v2_sparse_classes_36k_train_023237 | 1,365 | no_license | [
{
"docstring": ":type board: List[List[int]] :rtype: int",
"name": "snakesAndLadders",
"signature": "def snakesAndLadders(self, board)"
},
{
"docstring": "Given a number, return the board coordinates (r, c) the row changes every N squares, and so is only based on quot = (s2-1) / N the column is ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def snakesAndLadders(self, board): :type board: List[List[int]] :rtype: int
- def get_coordinates(self, num, N): Given a number, return the board coordinates (r, c) the row chang... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def snakesAndLadders(self, board): :type board: List[List[int]] :rtype: int
- def get_coordinates(self, num, N): Given a number, return the board coordinates (r, c) the row chang... | 90c000c3be70727cde4f7494fbbb1c425bfd3da4 | <|skeleton|>
class Solution:
def snakesAndLadders(self, board):
""":type board: List[List[int]] :rtype: int"""
<|body_0|>
def get_coordinates(self, num, N):
"""Given a number, return the board coordinates (r, c) the row changes every N squares, and so is only based on quot = (s2-1) / N... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def snakesAndLadders(self, board):
""":type board: List[List[int]] :rtype: int"""
N = len(board)
queue = collections.deque([(1, 0)])
visited = {1}
while queue:
cur_num, dist = queue.popleft()
if cur_num == N * N:
return ... | the_stack_v2_python_sparse | 909.snakes-and-ladders.py | chenjienan/python-leetcode | train | 16 | |
1c4e2fd34033973c51d13e82d5ea3f5609ce3716 | [
"try:\n return EnvironmentProductsList.objects.get(pk=pk)\nexcept EnvironmentProductsList.DoesNotExist:\n raise Http404",
"env_product_list = self.get_object(pk)\nserializer = EnvironmentProductsListSerializer(env_product_list)\nreturn Response(serializer.data)",
"env_product_list = self.get_object(pk)\ns... | <|body_start_0|>
try:
return EnvironmentProductsList.objects.get(pk=pk)
except EnvironmentProductsList.DoesNotExist:
raise Http404
<|end_body_0|>
<|body_start_1|>
env_product_list = self.get_object(pk)
serializer = EnvironmentProductsListSerializer(env_product_li... | Retrieve, update or delete a EnvironmentProductsList instance. | EnvironmentProductsListDetails | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnvironmentProductsListDetails:
"""Retrieve, update or delete a EnvironmentProductsList instance."""
def get_object(self, pk):
"""Get the particular row from the table."""
<|body_0|>
def get(self, request, pk, format=None):
"""We are going to add the contact info... | stack_v2_sparse_classes_36k_train_023238 | 15,222 | permissive | [
{
"docstring": "Get the particular row from the table.",
"name": "get_object",
"signature": "def get_object(self, pk)"
},
{
"docstring": "We are going to add the contact info content along with this pull request",
"name": "get",
"signature": "def get(self, request, pk, format=None)"
},... | 4 | stack_v2_sparse_classes_30k_train_007389 | Implement the Python class `EnvironmentProductsListDetails` described below.
Class description:
Retrieve, update or delete a EnvironmentProductsList instance.
Method signatures and docstrings:
- def get_object(self, pk): Get the particular row from the table.
- def get(self, request, pk, format=None): We are going to... | Implement the Python class `EnvironmentProductsListDetails` described below.
Class description:
Retrieve, update or delete a EnvironmentProductsList instance.
Method signatures and docstrings:
- def get_object(self, pk): Get the particular row from the table.
- def get(self, request, pk, format=None): We are going to... | b0635e72338e14dad24f1ee0329212cd60a3e83a | <|skeleton|>
class EnvironmentProductsListDetails:
"""Retrieve, update or delete a EnvironmentProductsList instance."""
def get_object(self, pk):
"""Get the particular row from the table."""
<|body_0|>
def get(self, request, pk, format=None):
"""We are going to add the contact info... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EnvironmentProductsListDetails:
"""Retrieve, update or delete a EnvironmentProductsList instance."""
def get_object(self, pk):
"""Get the particular row from the table."""
try:
return EnvironmentProductsList.objects.get(pk=pk)
except EnvironmentProductsList.DoesNotExis... | the_stack_v2_python_sparse | environment/views.py | faisaltheparttimecoder/carelogBackend | train | 1 |
5d0bbc4cfa1588273c832d2ecd83a09a22d122c4 | [
"Parametre.__init__(self, 'carte', 'map')\nself.schema = '<cle>'\nself.aide_courte = \"affiche la carte de l'étendue\"\nself.aide_longue = \"Cette commande permet d'afficher un contexte représentant la carte (tronquée) de l'étendue. Les obstacles et les liens peuvent être édités simplement ici. Le contexte en lui-m... | <|body_start_0|>
Parametre.__init__(self, 'carte', 'map')
self.schema = '<cle>'
self.aide_courte = "affiche la carte de l'étendue"
self.aide_longue = "Cette commande permet d'afficher un contexte représentant la carte (tronquée) de l'étendue. Les obstacles et les liens peuvent être édité... | Commande 'etendue carte'. | PrmCarte | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmCarte:
"""Commande 'etendue carte'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Parametre.__i... | stack_v2_sparse_classes_36k_train_023239 | 3,590 | permissive | [
{
"docstring": "Constructeur du paramètre",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Interprétation du paramètre",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009374 | Implement the Python class `PrmCarte` described below.
Class description:
Commande 'etendue carte'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre | Implement the Python class `PrmCarte` described below.
Class description:
Commande 'etendue carte'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre
<|skeleton|>
class PrmCarte:
"""Commande 'etendue car... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmCarte:
"""Commande 'etendue carte'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrmCarte:
"""Commande 'etendue carte'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'carte', 'map')
self.schema = '<cle>'
self.aide_courte = "affiche la carte de l'étendue"
self.aide_longue = "Cette commande permet d'afficher un c... | the_stack_v2_python_sparse | src/primaires/salle/commandes/etendue/carte.py | vincent-lg/tsunami | train | 5 |
08a4279aaea8068b463e67f3da309885a1c2ceb3 | [
"if self.fakeRun:\n self.fakeRunWait()\nelse:\n instr = self.instructions['backward']\n self.arduino.write(instr)\n print('[@] Sent to Serial: {}'.format(instr))\n while True:\n msg = self.arduino.read()\n if msg == None:\n print('[#] nothing to read [read_from_serial]')\n ... | <|body_start_0|>
if self.fakeRun:
self.fakeRunWait()
else:
instr = self.instructions['backward']
self.arduino.write(instr)
print('[@] Sent to Serial: {}'.format(instr))
while True:
msg = self.arduino.read()
if ms... | Coordinator class. Controls the movement of the robot. Attributes: fakeRun: Defaults to False. Set to True if running in simulation stepsPerSec: Number of steps to take per second, if running in simulation | Coordinator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Coordinator:
"""Coordinator class. Controls the movement of the robot. Attributes: fakeRun: Defaults to False. Set to True if running in simulation stepsPerSec: Number of steps to take per second, if running in simulation"""
def backward(self):
"""Moves the robot backward"""
... | stack_v2_sparse_classes_36k_train_023240 | 3,768 | no_license | [
{
"docstring": "Moves the robot backward",
"name": "backward",
"signature": "def backward(self)"
},
{
"docstring": "Moves the robot forward Args: steps: Integer. Number of steps to take.",
"name": "forward",
"signature": "def forward(self, steps)"
},
{
"docstring": "Turns the rob... | 5 | stack_v2_sparse_classes_30k_val_000555 | Implement the Python class `Coordinator` described below.
Class description:
Coordinator class. Controls the movement of the robot. Attributes: fakeRun: Defaults to False. Set to True if running in simulation stepsPerSec: Number of steps to take per second, if running in simulation
Method signatures and docstrings:
-... | Implement the Python class `Coordinator` described below.
Class description:
Coordinator class. Controls the movement of the robot. Attributes: fakeRun: Defaults to False. Set to True if running in simulation stepsPerSec: Number of steps to take per second, if running in simulation
Method signatures and docstrings:
-... | 7c374547df9070bda0d8682cc10d5ed045737b36 | <|skeleton|>
class Coordinator:
"""Coordinator class. Controls the movement of the robot. Attributes: fakeRun: Defaults to False. Set to True if running in simulation stepsPerSec: Number of steps to take per second, if running in simulation"""
def backward(self):
"""Moves the robot backward"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Coordinator:
"""Coordinator class. Controls the movement of the robot. Attributes: fakeRun: Defaults to False. Set to True if running in simulation stepsPerSec: Number of steps to take per second, if running in simulation"""
def backward(self):
"""Moves the robot backward"""
if self.fakeR... | the_stack_v2_python_sparse | coordinator.py | jiachin1995/CZ3004 | train | 0 |
ce3336645447f413b04f9a3e2d69e32ff7558291 | [
"bit_count = [0] * 32\nfor i in range(32):\n for num in nums:\n bit_count[i] += num >> i & 1\n bit_count[i] = bit_count[i] % 3\nres = 0\nfor i in range(32):\n res += bit_count[i] << i\nreturn res - 2 ** 32 if res >= 2 ** 31 else res",
"ones = twos = threes = 0\nfor i in range(len(nums)):\n thre... | <|body_start_0|>
bit_count = [0] * 32
for i in range(32):
for num in nums:
bit_count[i] += num >> i & 1
bit_count[i] = bit_count[i] % 3
res = 0
for i in range(32):
res += bit_count[i] << i
return res - 2 ** 32 if res >= 2 ** 31 ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def singleNumber(self, nums):
"""Count for each bit through nums. :type nums: List[int] :rtype: int"""
<|body_0|>
def singleNumber(self, nums):
"""More consice implement. :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_36k_train_023241 | 1,191 | no_license | [
{
"docstring": "Count for each bit through nums. :type nums: List[int] :rtype: int",
"name": "singleNumber",
"signature": "def singleNumber(self, nums)"
},
{
"docstring": "More consice implement. :type nums: List[int] :rtype: int",
"name": "singleNumber",
"signature": "def singleNumber(s... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums): Count for each bit through nums. :type nums: List[int] :rtype: int
- def singleNumber(self, nums): More consice implement. :type nums: List[int] :rt... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums): Count for each bit through nums. :type nums: List[int] :rtype: int
- def singleNumber(self, nums): More consice implement. :type nums: List[int] :rt... | 052bd7915257679877dbe55b60ed1abb7528eaa2 | <|skeleton|>
class Solution:
def singleNumber(self, nums):
"""Count for each bit through nums. :type nums: List[int] :rtype: int"""
<|body_0|>
def singleNumber(self, nums):
"""More consice implement. :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def singleNumber(self, nums):
"""Count for each bit through nums. :type nums: List[int] :rtype: int"""
bit_count = [0] * 32
for i in range(32):
for num in nums:
bit_count[i] += num >> i & 1
bit_count[i] = bit_count[i] % 3
res = ... | the_stack_v2_python_sparse | python_solution/BitManipulation/137_SingleNumberII.py | Dimen61/leetcode | train | 4 | |
93d76a916b7824060a84f863b33a73ac503767fe | [
"if not prices:\n return 0\npre = 0\nopt_profit = 0\nfor i in range(1, len(prices)):\n pre = max(pre + (prices[i] - prices[i - 1]), 0)\n opt_profit = max(opt_profit, pre)\nreturn opt_profit",
"if not prices:\n return 0\nmin_price = float('inf')\nopt = 0\nfor price in prices:\n min_price = min(price... | <|body_start_0|>
if not prices:
return 0
pre = 0
opt_profit = 0
for i in range(1, len(prices)):
pre = max(pre + (prices[i] - prices[i - 1]), 0)
opt_profit = max(opt_profit, pre)
return opt_profit
<|end_body_0|>
<|body_start_1|>
if not ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def max_profit(self, prices):
"""The meaning of dp[i] is the maximum profit of selling the stock at i-th day. And the stock has to be bought on or before that day. dp[i+1] is max(dp[i] + (prices[i+1] - prices[i]), 0). This is because the sell day is fixed and bought day must be... | stack_v2_sparse_classes_36k_train_023242 | 1,473 | no_license | [
{
"docstring": "The meaning of dp[i] is the maximum profit of selling the stock at i-th day. And the stock has to be bought on or before that day. dp[i+1] is max(dp[i] + (prices[i+1] - prices[i]), 0). This is because the sell day is fixed and bought day must be the same as bought day of dp[i]. However, if this ... | 2 | stack_v2_sparse_classes_30k_train_016092 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def max_profit(self, prices): The meaning of dp[i] is the maximum profit of selling the stock at i-th day. And the stock has to be bought on or before that day. dp[i+1] is max(dp... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def max_profit(self, prices): The meaning of dp[i] is the maximum profit of selling the stock at i-th day. And the stock has to be bought on or before that day. dp[i+1] is max(dp... | 5625e6396b746255f3343253c75447ead95879c7 | <|skeleton|>
class Solution:
def max_profit(self, prices):
"""The meaning of dp[i] is the maximum profit of selling the stock at i-th day. And the stock has to be bought on or before that day. dp[i+1] is max(dp[i] + (prices[i+1] - prices[i]), 0). This is because the sell day is fixed and bought day must be... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def max_profit(self, prices):
"""The meaning of dp[i] is the maximum profit of selling the stock at i-th day. And the stock has to be bought on or before that day. dp[i+1] is max(dp[i] + (prices[i+1] - prices[i]), 0). This is because the sell day is fixed and bought day must be the same as b... | the_stack_v2_python_sparse | 121_best_time_to_buy_and_sell_stock/solution.py | FluffyFu/Leetcode | train | 0 | |
2b64e35c62cf86cf6d7af1214ec8f9e22c3ca8fc | [
"assert len(hidden_layers_sizes) > 0\nself.n_layers = len(hidden_layers_sizes)\nself.layers = []\nself.rbm_layers = []\nself.params = []\nself.x = tf.placeholder(tf.float32, shape=[None, n_in])\nself.y = tf.placeholder(tf.float32, shape=[None, n_out])\nfor i in range(self.n_layers):\n if i == 0:\n layer_i... | <|body_start_0|>
assert len(hidden_layers_sizes) > 0
self.n_layers = len(hidden_layers_sizes)
self.layers = []
self.rbm_layers = []
self.params = []
self.x = tf.placeholder(tf.float32, shape=[None, n_in])
self.y = tf.placeholder(tf.float32, shape=[None, n_out])
... | An implement of deep belief network The hidden layers are firstly pretrained by RBM, then DBN is treated as a normal MLP by adding a output layer. | DBN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DBN:
"""An implement of deep belief network The hidden layers are firstly pretrained by RBM, then DBN is treated as a normal MLP by adding a output layer."""
def __init__(self, n_in=784, n_out=10, hidden_layers_sizes=[500, 500]):
""":param n_in: int, the dimension of input :param n_o... | stack_v2_sparse_classes_36k_train_023243 | 5,942 | no_license | [
{
"docstring": ":param n_in: int, the dimension of input :param n_out: int, the dimension of output :param hidden_layers_sizes: list or tuple, the hidden layer sizes",
"name": "__init__",
"signature": "def __init__(self, n_in=784, n_out=10, hidden_layers_sizes=[500, 500])"
},
{
"docstring": "Pre... | 3 | null | Implement the Python class `DBN` described below.
Class description:
An implement of deep belief network The hidden layers are firstly pretrained by RBM, then DBN is treated as a normal MLP by adding a output layer.
Method signatures and docstrings:
- def __init__(self, n_in=784, n_out=10, hidden_layers_sizes=[500, 5... | Implement the Python class `DBN` described below.
Class description:
An implement of deep belief network The hidden layers are firstly pretrained by RBM, then DBN is treated as a normal MLP by adding a output layer.
Method signatures and docstrings:
- def __init__(self, n_in=784, n_out=10, hidden_layers_sizes=[500, 5... | a9b356636988ee920be5933155cd3d7c7559e201 | <|skeleton|>
class DBN:
"""An implement of deep belief network The hidden layers are firstly pretrained by RBM, then DBN is treated as a normal MLP by adding a output layer."""
def __init__(self, n_in=784, n_out=10, hidden_layers_sizes=[500, 500]):
""":param n_in: int, the dimension of input :param n_o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DBN:
"""An implement of deep belief network The hidden layers are firstly pretrained by RBM, then DBN is treated as a normal MLP by adding a output layer."""
def __init__(self, n_in=784, n_out=10, hidden_layers_sizes=[500, 500]):
""":param n_in: int, the dimension of input :param n_out: int, the ... | the_stack_v2_python_sparse | deepLearning/08_dbn.py | robot-Yang/Ewenwan_vision | train | 11 |
9cfb684630fd561a1d06f476701dba6620760258 | [
"if self._locked:\n raise AlreadyLockedException('File %s is already locked' % self._filename)\nstart_time = time.time()\nvalidate_file(self._filename)\ntry:\n self._fh = open(self._filename, self._mode)\nexcept IOError as e:\n if e.errno == errno.EACCES:\n self._fh = open(self._filename, self._fall... | <|body_start_0|>
if self._locked:
raise AlreadyLockedException('File %s is already locked' % self._filename)
start_time = time.time()
validate_file(self._filename)
try:
self._fh = open(self._filename, self._mode)
except IOError as e:
if e.errno... | Open, lock, and unlock a file using windows primitives. | _Win32Opener | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Win32Opener:
"""Open, lock, and unlock a file using windows primitives."""
def open_and_lock(self, timeout, delay):
"""Open the file and lock it. Args: timeout: float, How long to try to lock for. delay: float, How long to wait between retries Raises: AlreadyLockedException: if the ... | stack_v2_sparse_classes_36k_train_023244 | 11,504 | permissive | [
{
"docstring": "Open the file and lock it. Args: timeout: float, How long to try to lock for. delay: float, How long to wait between retries Raises: AlreadyLockedException: if the lock is already acquired. IOError: if the open fails. CredentialsFileSymbolicLinkError if the file is a symbolic link.",
"name":... | 2 | null | Implement the Python class `_Win32Opener` described below.
Class description:
Open, lock, and unlock a file using windows primitives.
Method signatures and docstrings:
- def open_and_lock(self, timeout, delay): Open the file and lock it. Args: timeout: float, How long to try to lock for. delay: float, How long to wai... | Implement the Python class `_Win32Opener` described below.
Class description:
Open, lock, and unlock a file using windows primitives.
Method signatures and docstrings:
- def open_and_lock(self, timeout, delay): Open the file and lock it. Args: timeout: float, How long to try to lock for. delay: float, How long to wai... | 53102de187a48ac2cfc241fef54dcbc29c453a8e | <|skeleton|>
class _Win32Opener:
"""Open, lock, and unlock a file using windows primitives."""
def open_and_lock(self, timeout, delay):
"""Open the file and lock it. Args: timeout: float, How long to try to lock for. delay: float, How long to wait between retries Raises: AlreadyLockedException: if the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _Win32Opener:
"""Open, lock, and unlock a file using windows primitives."""
def open_and_lock(self, timeout, delay):
"""Open the file and lock it. Args: timeout: float, How long to try to lock for. delay: float, How long to wait between retries Raises: AlreadyLockedException: if the lock is alrea... | the_stack_v2_python_sparse | third_party/gae_ts_mon/gae_ts_mon/third_party/oauth2client/locked_file.py | catapult-project/catapult | train | 2,032 |
dae4d394219df204507c79475d1475a8fef54d4c | [
"logging.info('Building component: %s', self.spec.name)\nif self.spec.fixed_feature:\n raise RuntimeError('Fixed features are not compatible with bulk annotation. Use the \"bulk-features\" component instead.')\nlinked_embeddings = [fetch_linked_embedding(self, network_states, spec) for spec in self.spec.linked_f... | <|body_start_0|>
logging.info('Building component: %s', self.spec.name)
if self.spec.fixed_feature:
raise RuntimeError('Fixed features are not compatible with bulk annotation. Use the "bulk-features" component instead.')
linked_embeddings = [fetch_linked_embedding(self, network_state... | A component builder to bulk annotate or compute the cost of a gold path. This component can be used with features that don't depend on the transition system state. Since no feature extraction is performed, only non-recurrent 'identity' linked features are supported. If a FeedForwardNetwork is configured with no hidden ... | BulkAnnotatorComponentBuilder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BulkAnnotatorComponentBuilder:
"""A component builder to bulk annotate or compute the cost of a gold path. This component can be used with features that don't depend on the transition system state. Since no feature extraction is performed, only non-recurrent 'identity' linked features are support... | stack_v2_sparse_classes_36k_train_023245 | 18,694 | permissive | [
{
"docstring": "Advances a batch using oracle paths, returning the overall CE cost. Args: state: MasterState from the 'AdvanceMaster' op that advances the underlying master to this component. network_states: dictionary of component NetworkState objects Returns: (state handle, cost, correct, total): TF ops corre... | 2 | null | Implement the Python class `BulkAnnotatorComponentBuilder` described below.
Class description:
A component builder to bulk annotate or compute the cost of a gold path. This component can be used with features that don't depend on the transition system state. Since no feature extraction is performed, only non-recurrent... | Implement the Python class `BulkAnnotatorComponentBuilder` described below.
Class description:
A component builder to bulk annotate or compute the cost of a gold path. This component can be used with features that don't depend on the transition system state. Since no feature extraction is performed, only non-recurrent... | 7f8c93c96a7ab5e150f217b7c369bec9d4b8bb81 | <|skeleton|>
class BulkAnnotatorComponentBuilder:
"""A component builder to bulk annotate or compute the cost of a gold path. This component can be used with features that don't depend on the transition system state. Since no feature extraction is performed, only non-recurrent 'identity' linked features are support... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BulkAnnotatorComponentBuilder:
"""A component builder to bulk annotate or compute the cost of a gold path. This component can be used with features that don't depend on the transition system state. Since no feature extraction is performed, only non-recurrent 'identity' linked features are supported. If a Feed... | the_stack_v2_python_sparse | syntaxnet/dragnn/python/bulk_component.py | sshleifer/object_detection_kitti | train | 35 |
f15a19cd880e9aa2493ba5c09890ab222f517f1d | [
"assert category in ERROR_CATEGORIES\nself.relpath = relpath\nself.category = category\nself.message = message\nself.fix_it = fix_it\nERROR_COUNTS[category] += 1\nif not FLAGS.counts and self.category not in FLAGS.ignore:\n print(f'\\r\\x1b[K{relpath}: {shell.ShellEscapeCodes.YELLOW}{message}{shell.ShellEscapeC... | <|body_start_0|>
assert category in ERROR_CATEGORIES
self.relpath = relpath
self.category = category
self.message = message
self.fix_it = fix_it
ERROR_COUNTS[category] += 1
if not FLAGS.counts and self.category not in FLAGS.ignore:
print(f'\r\x1b[K{rel... | A linter error. | Error | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Error:
"""A linter error."""
def __init__(self, relpath: str, category: str, message: str, fix_it: str=None):
"""Report an error. If --counts flag was passed, this updates the running totals of error counts. If --fix_it flag was passed, the command is printed to stdout. All other out... | stack_v2_sparse_classes_36k_train_023246 | 24,661 | permissive | [
{
"docstring": "Report an error. If --counts flag was passed, this updates the running totals of error counts. If --fix_it flag was passed, the command is printed to stdout. All other output is to stderr.",
"name": "__init__",
"signature": "def __init__(self, relpath: str, category: str, message: str, f... | 2 | null | Implement the Python class `Error` described below.
Class description:
A linter error.
Method signatures and docstrings:
- def __init__(self, relpath: str, category: str, message: str, fix_it: str=None): Report an error. If --counts flag was passed, this updates the running totals of error counts. If --fix_it flag wa... | Implement the Python class `Error` described below.
Class description:
A linter error.
Method signatures and docstrings:
- def __init__(self, relpath: str, category: str, message: str, fix_it: str=None): Report an error. If --counts flag was passed, this updates the running totals of error counts. If --fix_it flag wa... | aab7f16bd1f3546f81e349fc6e2325fb17beb851 | <|skeleton|>
class Error:
"""A linter error."""
def __init__(self, relpath: str, category: str, message: str, fix_it: str=None):
"""Report an error. If --counts flag was passed, this updates the running totals of error counts. If --fix_it flag was passed, the command is printed to stdout. All other out... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Error:
"""A linter error."""
def __init__(self, relpath: str, category: str, message: str, fix_it: str=None):
"""Report an error. If --counts flag was passed, this updates the running totals of error counts. If --fix_it flag was passed, the command is printed to stdout. All other output is to std... | the_stack_v2_python_sparse | util/photolib/linters.py | tszdanger/phd | train | 0 |
910d5a6aea48c9e81292d29b9751e5d6b96e3000 | [
"self.check_config(config)\ncond = config['number_bootstraps'] == 1 or not isinstance(catalogue.data['sigmaMagnitude'], np.ndarray) or len(catalogue.data['sigmaMagnitude']) == 0 or np.all(np.isnan(catalogue.data['sigmaMagnitude']))\nif cond:\n return (self.cumulative_moment(catalogue.data['year'], catalogue.data... | <|body_start_0|>
self.check_config(config)
cond = config['number_bootstraps'] == 1 or not isinstance(catalogue.data['sigmaMagnitude'], np.ndarray) or len(catalogue.data['sigmaMagnitude']) == 0 or np.all(np.isnan(catalogue.data['sigmaMagnitude']))
if cond:
return (self.cumulative_mome... | Class to implement the bootstrapped cumulative moment estimator of maximum magnitude. Adapted by G. Weatherill from the Cumulative Strain Energy approach originally suggested by Makropoulos & Burton (1983) | CumulativeMoment | [
"BSD-3-Clause",
"AGPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CumulativeMoment:
"""Class to implement the bootstrapped cumulative moment estimator of maximum magnitude. Adapted by G. Weatherill from the Cumulative Strain Energy approach originally suggested by Makropoulos & Burton (1983)"""
def get_mmax(self, catalogue, config):
"""Calculates M... | stack_v2_sparse_classes_36k_train_023247 | 6,425 | permissive | [
{
"docstring": "Calculates Maximum magnitude and its uncertainty :param catalogue: Instance of openquake.hmtk.seismicity.catalogue.Catalogue class Earthquake calatalogue data as dictionary containing - * 'year' - Year of event * 'magnitude' - Magnitude of event * 'sigmaMagnitude' - Uncertainty on magnitude (opt... | 3 | stack_v2_sparse_classes_30k_train_018801 | Implement the Python class `CumulativeMoment` described below.
Class description:
Class to implement the bootstrapped cumulative moment estimator of maximum magnitude. Adapted by G. Weatherill from the Cumulative Strain Energy approach originally suggested by Makropoulos & Burton (1983)
Method signatures and docstrin... | Implement the Python class `CumulativeMoment` described below.
Class description:
Class to implement the bootstrapped cumulative moment estimator of maximum magnitude. Adapted by G. Weatherill from the Cumulative Strain Energy approach originally suggested by Makropoulos & Burton (1983)
Method signatures and docstrin... | 0da9ba5a575360081715e8b90c71d4b16c6687c8 | <|skeleton|>
class CumulativeMoment:
"""Class to implement the bootstrapped cumulative moment estimator of maximum magnitude. Adapted by G. Weatherill from the Cumulative Strain Energy approach originally suggested by Makropoulos & Burton (1983)"""
def get_mmax(self, catalogue, config):
"""Calculates M... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CumulativeMoment:
"""Class to implement the bootstrapped cumulative moment estimator of maximum magnitude. Adapted by G. Weatherill from the Cumulative Strain Energy approach originally suggested by Makropoulos & Burton (1983)"""
def get_mmax(self, catalogue, config):
"""Calculates Maximum magnit... | the_stack_v2_python_sparse | openquake/hmtk/seismicity/max_magnitude/cumulative_moment_release.py | GFZ-Centre-for-Early-Warning/shakyground | train | 1 |
15774ba744ea6456b49bca281a0da434323ca343 | [
"firebase_token = self.get_token(request)\nif firebase_token is None:\n return None\ntry:\n payload = auth.verify_id_token(firebase_token)\nexcept ValueError:\n msg = _('Signature has expired.')\n raise exceptions.AuthenticationFailed(msg)\nexcept auth.AuthError:\n msg = _('Could not log in.')\n r... | <|body_start_0|>
firebase_token = self.get_token(request)
if firebase_token is None:
return None
try:
payload = auth.verify_id_token(firebase_token)
except ValueError:
msg = _('Signature has expired.')
raise exceptions.AuthenticationFailed(... | Token based authentication using firebase. | BaseFirebaseuthentication | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseFirebaseuthentication:
"""Token based authentication using firebase."""
def authenticate(self, request):
"""Returns a two-tuple of `User` and token if a valid signature has been supplied using Firebase authentication. Otherwise returns `None`."""
<|body_0|>
def authe... | stack_v2_sparse_classes_36k_train_023248 | 5,651 | no_license | [
{
"docstring": "Returns a two-tuple of `User` and token if a valid signature has been supplied using Firebase authentication. Otherwise returns `None`.",
"name": "authenticate",
"signature": "def authenticate(self, request)"
},
{
"docstring": "Returns an active user that matches the payload's us... | 2 | stack_v2_sparse_classes_30k_train_020886 | Implement the Python class `BaseFirebaseuthentication` described below.
Class description:
Token based authentication using firebase.
Method signatures and docstrings:
- def authenticate(self, request): Returns a two-tuple of `User` and token if a valid signature has been supplied using Firebase authentication. Other... | Implement the Python class `BaseFirebaseuthentication` described below.
Class description:
Token based authentication using firebase.
Method signatures and docstrings:
- def authenticate(self, request): Returns a two-tuple of `User` and token if a valid signature has been supplied using Firebase authentication. Other... | 5714b02deb0acc8fa185eb02bd6b561e2f5f185e | <|skeleton|>
class BaseFirebaseuthentication:
"""Token based authentication using firebase."""
def authenticate(self, request):
"""Returns a two-tuple of `User` and token if a valid signature has been supplied using Firebase authentication. Otherwise returns `None`."""
<|body_0|>
def authe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseFirebaseuthentication:
"""Token based authentication using firebase."""
def authenticate(self, request):
"""Returns a two-tuple of `User` and token if a valid signature has been supplied using Firebase authentication. Otherwise returns `None`."""
firebase_token = self.get_token(reques... | the_stack_v2_python_sparse | user_repo3/user_management/authentication.py | jyothinaidu/user_management | train | 1 |
8d23cae2da9030d36c597c9c755b6a0d3e61d0b3 | [
"self.set_header('Access-Control-Allow-Origin', '*')\nself.set_header('Access-Control-Allow-Methods', self.request.method)\nself.set_header('Access-Control-Allow-Headers', 'x-requested-with,content-type')",
"self.set_header('Access-Control-Allow-Origin', '*')\nself.set_header('Access-Control-Allow-Methods', self.... | <|body_start_0|>
self.set_header('Access-Control-Allow-Origin', '*')
self.set_header('Access-Control-Allow-Methods', self.request.method)
self.set_header('Access-Control-Allow-Headers', 'x-requested-with,content-type')
<|end_body_0|>
<|body_start_1|>
self.set_header('Access-Control-Allo... | BaseHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseHandler:
def setGetRequestHeader(self):
"""deal with cross domain trouble"""
<|body_0|>
def setPostRequestHeader(self):
"""deal with cross domain trouble"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.set_header('Access-Control-Allow-Origi... | stack_v2_sparse_classes_36k_train_023249 | 4,791 | no_license | [
{
"docstring": "deal with cross domain trouble",
"name": "setGetRequestHeader",
"signature": "def setGetRequestHeader(self)"
},
{
"docstring": "deal with cross domain trouble",
"name": "setPostRequestHeader",
"signature": "def setPostRequestHeader(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004365 | Implement the Python class `BaseHandler` described below.
Class description:
Implement the BaseHandler class.
Method signatures and docstrings:
- def setGetRequestHeader(self): deal with cross domain trouble
- def setPostRequestHeader(self): deal with cross domain trouble | Implement the Python class `BaseHandler` described below.
Class description:
Implement the BaseHandler class.
Method signatures and docstrings:
- def setGetRequestHeader(self): deal with cross domain trouble
- def setPostRequestHeader(self): deal with cross domain trouble
<|skeleton|>
class BaseHandler:
def set... | c86f916fe8439d096eac966e2dd7555f47b1c5b6 | <|skeleton|>
class BaseHandler:
def setGetRequestHeader(self):
"""deal with cross domain trouble"""
<|body_0|>
def setPostRequestHeader(self):
"""deal with cross domain trouble"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseHandler:
def setGetRequestHeader(self):
"""deal with cross domain trouble"""
self.set_header('Access-Control-Allow-Origin', '*')
self.set_header('Access-Control-Allow-Methods', self.request.method)
self.set_header('Access-Control-Allow-Headers', 'x-requested-with,content-ty... | the_stack_v2_python_sparse | couplet/demo/runServer.py | ChenLiangbo/MyPoetry | train | 1 | |
a491772258a52bdfc93083343d2a2e48a240340d | [
"self.topk = topk\nself.sum = [0.0] * len(topk)\nself.data_num = 0\nself.pfm = [0.0] * len(topk)",
"if isinstance(output, tuple):\n output = output[0]\nif isinstance(target, tuple) or isinstance(target, list):\n target = target[0]\nres = accuracy(output, target, self.topk)\nn = output.size(0)\nself.data_num... | <|body_start_0|>
self.topk = topk
self.sum = [0.0] * len(topk)
self.data_num = 0
self.pfm = [0.0] * len(topk)
<|end_body_0|>
<|body_start_1|>
if isinstance(output, tuple):
output = output[0]
if isinstance(target, tuple) or isinstance(target, list):
... | Calculate classification accuracy between output and target. | Accuracy | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Accuracy:
"""Calculate classification accuracy between output and target."""
def __init__(self, topk=(1, 5)):
"""Init Accuracy metric."""
<|body_0|>
def __call__(self, output, target, *args, **kwargs):
"""Perform top k accuracy. :param output: output of classific... | stack_v2_sparse_classes_36k_train_023250 | 4,324 | permissive | [
{
"docstring": "Init Accuracy metric.",
"name": "__init__",
"signature": "def __init__(self, topk=(1, 5))"
},
{
"docstring": "Perform top k accuracy. :param output: output of classification network :param target: ground truth from dataset :return: pfm",
"name": "__call__",
"signature": "... | 4 | stack_v2_sparse_classes_30k_train_012374 | Implement the Python class `Accuracy` described below.
Class description:
Calculate classification accuracy between output and target.
Method signatures and docstrings:
- def __init__(self, topk=(1, 5)): Init Accuracy metric.
- def __call__(self, output, target, *args, **kwargs): Perform top k accuracy. :param output... | Implement the Python class `Accuracy` described below.
Class description:
Calculate classification accuracy between output and target.
Method signatures and docstrings:
- def __init__(self, topk=(1, 5)): Init Accuracy metric.
- def __call__(self, output, target, *args, **kwargs): Perform top k accuracy. :param output... | 12e37a1991eb6771a2999fe0a46ddda920c47948 | <|skeleton|>
class Accuracy:
"""Calculate classification accuracy between output and target."""
def __init__(self, topk=(1, 5)):
"""Init Accuracy metric."""
<|body_0|>
def __call__(self, output, target, *args, **kwargs):
"""Perform top k accuracy. :param output: output of classific... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Accuracy:
"""Calculate classification accuracy between output and target."""
def __init__(self, topk=(1, 5)):
"""Init Accuracy metric."""
self.topk = topk
self.sum = [0.0] * len(topk)
self.data_num = 0
self.pfm = [0.0] * len(topk)
def __call__(self, output, ta... | the_stack_v2_python_sparse | vega/metrics/pytorch/classifier_metric.py | huawei-noah/vega | train | 850 |
6eeb2d6be78771a9465d6d2e7b9be50ccaa4674f | [
"super().__init__(num_locations, coverages_per_location)\nself.dtypes = OrderedDict([('item_id', 'i'), ('summary_id', 'i'), ('summaryset_id', 'i')])\nself.data_length = num_locations * coverages_per_location\nself.file_name = os.path.join(directory, 'gulsummaryxref.bin')",
"summary_id = 1\nsummaryset_id = 1\nfor ... | <|body_start_0|>
super().__init__(num_locations, coverages_per_location)
self.dtypes = OrderedDict([('item_id', 'i'), ('summary_id', 'i'), ('summaryset_id', 'i')])
self.data_length = num_locations * coverages_per_location
self.file_name = os.path.join(directory, 'gulsummaryxref.bin')
<|e... | Generate data for Ground Up Losses Summary Cross Reference dummy model Oasis file. This file shows how item ground up losses are summed together at various summary levels in summarycalc. Attributes: generate_data: Generate Ground Up Losses Summary Cross Reference dummy model Oasis file data. | GULSummaryXrefFile | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GULSummaryXrefFile:
"""Generate data for Ground Up Losses Summary Cross Reference dummy model Oasis file. This file shows how item ground up losses are summed together at various summary levels in summarycalc. Attributes: generate_data: Generate Ground Up Losses Summary Cross Reference dummy mode... | stack_v2_sparse_classes_36k_train_023251 | 39,722 | permissive | [
{
"docstring": "Initialise Ground Up Losses Summary Cross Reference file class. Args: num_locations (int): number of locations. coverages_per_location (int): number of coverage types per location. directory (str): dummy model file destination.",
"name": "__init__",
"signature": "def __init__(self, num_l... | 2 | null | Implement the Python class `GULSummaryXrefFile` described below.
Class description:
Generate data for Ground Up Losses Summary Cross Reference dummy model Oasis file. This file shows how item ground up losses are summed together at various summary levels in summarycalc. Attributes: generate_data: Generate Ground Up Lo... | Implement the Python class `GULSummaryXrefFile` described below.
Class description:
Generate data for Ground Up Losses Summary Cross Reference dummy model Oasis file. This file shows how item ground up losses are summed together at various summary levels in summarycalc. Attributes: generate_data: Generate Ground Up Lo... | 23e704c335629ccd010969b1090446cfa3f384d5 | <|skeleton|>
class GULSummaryXrefFile:
"""Generate data for Ground Up Losses Summary Cross Reference dummy model Oasis file. This file shows how item ground up losses are summed together at various summary levels in summarycalc. Attributes: generate_data: Generate Ground Up Losses Summary Cross Reference dummy mode... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GULSummaryXrefFile:
"""Generate data for Ground Up Losses Summary Cross Reference dummy model Oasis file. This file shows how item ground up losses are summed together at various summary levels in summarycalc. Attributes: generate_data: Generate Ground Up Losses Summary Cross Reference dummy model Oasis file ... | the_stack_v2_python_sparse | oasislmf/computation/data/dummy_model/generate.py | OasisLMF/OasisLMF | train | 122 |
e3d81a88d2beae1934c4d4bd3cc410487944496d | [
"self.is_entire_drive_required = is_entire_drive_required\nself.restore_drive_id = restore_drive_id\nself.restore_drive_name = restore_drive_name\nself.restore_path_vec = restore_path_vec",
"if dictionary is None:\n return None\nis_entire_drive_required = dictionary.get('isEntireDriveRequired')\nrestore_drive_... | <|body_start_0|>
self.is_entire_drive_required = is_entire_drive_required
self.restore_drive_id = restore_drive_id
self.restore_drive_name = restore_drive_name
self.restore_path_vec = restore_path_vec
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None... | Implementation of the 'RestoreSiteParams_SiteOwner_Drive' model. TODO: type description here. Attributes: is_entire_drive_required (bool): Specify if the entire drive is to be restored. This field should be false if restore_item_vec size > 0. restore_drive_id (string): Id of the drive whose items are being restored. re... | RestoreSiteParams_SiteOwner_Drive | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoreSiteParams_SiteOwner_Drive:
"""Implementation of the 'RestoreSiteParams_SiteOwner_Drive' model. TODO: type description here. Attributes: is_entire_drive_required (bool): Specify if the entire drive is to be restored. This field should be false if restore_item_vec size > 0. restore_drive_id... | stack_v2_sparse_classes_36k_train_023252 | 3,026 | permissive | [
{
"docstring": "Constructor for the RestoreSiteParams_SiteOwner_Drive class",
"name": "__init__",
"signature": "def __init__(self, is_entire_drive_required=None, restore_drive_id=None, restore_drive_name=None, restore_path_vec=None)"
},
{
"docstring": "Creates an instance of this model from a di... | 2 | stack_v2_sparse_classes_30k_test_000001 | Implement the Python class `RestoreSiteParams_SiteOwner_Drive` described below.
Class description:
Implementation of the 'RestoreSiteParams_SiteOwner_Drive' model. TODO: type description here. Attributes: is_entire_drive_required (bool): Specify if the entire drive is to be restored. This field should be false if rest... | Implement the Python class `RestoreSiteParams_SiteOwner_Drive` described below.
Class description:
Implementation of the 'RestoreSiteParams_SiteOwner_Drive' model. TODO: type description here. Attributes: is_entire_drive_required (bool): Specify if the entire drive is to be restored. This field should be false if rest... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RestoreSiteParams_SiteOwner_Drive:
"""Implementation of the 'RestoreSiteParams_SiteOwner_Drive' model. TODO: type description here. Attributes: is_entire_drive_required (bool): Specify if the entire drive is to be restored. This field should be false if restore_item_vec size > 0. restore_drive_id... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RestoreSiteParams_SiteOwner_Drive:
"""Implementation of the 'RestoreSiteParams_SiteOwner_Drive' model. TODO: type description here. Attributes: is_entire_drive_required (bool): Specify if the entire drive is to be restored. This field should be false if restore_item_vec size > 0. restore_drive_id (string): Id... | the_stack_v2_python_sparse | cohesity_management_sdk/models/restore_site_params_site_owner_drive.py | cohesity/management-sdk-python | train | 24 |
e8d6fb4131f44494825d4448c8fde31b67fb09ef | [
"try:\n extensions_config = getattr(current_app.extensions['invenio-app-ils'], 'document_metadata_extensions')\nexcept AttributeError:\n return {}\nExtensionSchema = extensions_config.to_schema()\nreturn ExtensionSchema().dump(obj)",
"try:\n extensions_config = getattr(current_app.extensions['invenio-app... | <|body_start_0|>
try:
extensions_config = getattr(current_app.extensions['invenio-app-ils'], 'document_metadata_extensions')
except AttributeError:
return {}
ExtensionSchema = extensions_config.to_schema()
return ExtensionSchema().dump(obj)
<|end_body_0|>
<|body_... | Document schema. | DocumentSchemaV1 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DocumentSchemaV1:
"""Document schema."""
def dump_extensions(self, obj):
"""Dumps the extensions value. :params obj: content of the object's 'extensions' field"""
<|body_0|>
def load_extensions(self, value):
"""Loads the 'extensions' field. :params value: content... | stack_v2_sparse_classes_36k_train_023253 | 7,755 | permissive | [
{
"docstring": "Dumps the extensions value. :params obj: content of the object's 'extensions' field",
"name": "dump_extensions",
"signature": "def dump_extensions(self, obj)"
},
{
"docstring": "Loads the 'extensions' field. :params value: content of the input's 'extensions' field",
"name": "... | 3 | null | Implement the Python class `DocumentSchemaV1` described below.
Class description:
Document schema.
Method signatures and docstrings:
- def dump_extensions(self, obj): Dumps the extensions value. :params obj: content of the object's 'extensions' field
- def load_extensions(self, value): Loads the 'extensions' field. :... | Implement the Python class `DocumentSchemaV1` described below.
Class description:
Document schema.
Method signatures and docstrings:
- def dump_extensions(self, obj): Dumps the extensions value. :params obj: content of the object's 'extensions' field
- def load_extensions(self, value): Loads the 'extensions' field. :... | 1c36526e85510100c5f64059518d1b716d87ac10 | <|skeleton|>
class DocumentSchemaV1:
"""Document schema."""
def dump_extensions(self, obj):
"""Dumps the extensions value. :params obj: content of the object's 'extensions' field"""
<|body_0|>
def load_extensions(self, value):
"""Loads the 'extensions' field. :params value: content... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DocumentSchemaV1:
"""Document schema."""
def dump_extensions(self, obj):
"""Dumps the extensions value. :params obj: content of the object's 'extensions' field"""
try:
extensions_config = getattr(current_app.extensions['invenio-app-ils'], 'document_metadata_extensions')
... | the_stack_v2_python_sparse | invenio_app_ils/documents/loaders/jsonschemas/document.py | inveniosoftware/invenio-app-ils | train | 64 |
a913e82b3e50378e503ca850344acc086be15245 | [
"resp = None\nurl = '{}ammo/{}'.format(self.epoint, ammo_id)\ntry:\n resp = requests.get(url, timeout=self.to)\n resp.raise_for_status()\n return resp.json()\nexcept Exception as e:\n panic(e=e, resp=resp)",
"resp = None\ncodes_allowed = [201]\nurl = '{}ammo/'.format(self.epoint)\nkw = {'data': {}}\ni... | <|body_start_0|>
resp = None
url = '{}ammo/{}'.format(self.epoint, ammo_id)
try:
resp = requests.get(url, timeout=self.to)
resp.raise_for_status()
return resp.json()
except Exception as e:
panic(e=e, resp=resp)
<|end_body_0|>
<|body_start_... | Ammo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ammo:
def ammo_get(self, ammo_id):
"""Fetch ammo entrie **not ammo file** passing uniq identificator. Args: ammo_id: int Returns: dict: Ammo entrie respresentation. Throws: LunaportClientError"""
<|body_0|>
def ammo_post(self, case, descr=None, files=None, data=None):
... | stack_v2_sparse_classes_36k_train_023254 | 1,984 | permissive | [
{
"docstring": "Fetch ammo entrie **not ammo file** passing uniq identificator. Args: ammo_id: int Returns: dict: Ammo entrie respresentation. Throws: LunaportClientError",
"name": "ammo_get",
"signature": "def ammo_get(self, ammo_id)"
},
{
"docstring": "Upload file to Lunaport service and get n... | 2 | stack_v2_sparse_classes_30k_train_010523 | Implement the Python class `Ammo` described below.
Class description:
Implement the Ammo class.
Method signatures and docstrings:
- def ammo_get(self, ammo_id): Fetch ammo entrie **not ammo file** passing uniq identificator. Args: ammo_id: int Returns: dict: Ammo entrie respresentation. Throws: LunaportClientError
- ... | Implement the Python class `Ammo` described below.
Class description:
Implement the Ammo class.
Method signatures and docstrings:
- def ammo_get(self, ammo_id): Fetch ammo entrie **not ammo file** passing uniq identificator. Args: ammo_id: int Returns: dict: Ammo entrie respresentation. Throws: LunaportClientError
- ... | d22cad17536fb8931bf69956e45299cde8c1b8db | <|skeleton|>
class Ammo:
def ammo_get(self, ammo_id):
"""Fetch ammo entrie **not ammo file** passing uniq identificator. Args: ammo_id: int Returns: dict: Ammo entrie respresentation. Throws: LunaportClientError"""
<|body_0|>
def ammo_post(self, case, descr=None, files=None, data=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ammo:
def ammo_get(self, ammo_id):
"""Fetch ammo entrie **not ammo file** passing uniq identificator. Args: ammo_id: int Returns: dict: Ammo entrie respresentation. Throws: LunaportClientError"""
resp = None
url = '{}ammo/{}'.format(self.epoint, ammo_id)
try:
resp =... | the_stack_v2_python_sparse | lunaport_client/mix_ammo.py | maklaut/lunaport_client | train | 0 | |
1d166b8f0b7b1709415b76919b7253f405756438 | [
"self.create_and_verify_stack('single/basic_layer')\nlayer_logical_id_1 = self.get_logical_id_by_type('AWS::Lambda::LayerVersion')\nself.set_template_resource_property('MyLayerVersion', 'Description', 'A basic layer')\nself.update_stack()\nlayer_logical_id_2 = self.get_logical_id_by_type('AWS::Lambda::LayerVersion'... | <|body_start_0|>
self.create_and_verify_stack('single/basic_layer')
layer_logical_id_1 = self.get_logical_id_by_type('AWS::Lambda::LayerVersion')
self.set_template_resource_property('MyLayerVersion', 'Description', 'A basic layer')
self.update_stack()
layer_logical_id_2 = self.ge... | Basic AWS::Lambda::LayerVersion tests | TestBasicLayerVersion | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestBasicLayerVersion:
"""Basic AWS::Lambda::LayerVersion tests"""
def test_basic_layer_version(self):
"""Creates a basic lambda layer version"""
<|body_0|>
def test_basic_layer_with_parameters(self):
"""Creates a basic lambda layer version with parameters"""
... | stack_v2_sparse_classes_36k_train_023255 | 2,605 | permissive | [
{
"docstring": "Creates a basic lambda layer version",
"name": "test_basic_layer_version",
"signature": "def test_basic_layer_version(self)"
},
{
"docstring": "Creates a basic lambda layer version with parameters",
"name": "test_basic_layer_with_parameters",
"signature": "def test_basic_... | 3 | null | Implement the Python class `TestBasicLayerVersion` described below.
Class description:
Basic AWS::Lambda::LayerVersion tests
Method signatures and docstrings:
- def test_basic_layer_version(self): Creates a basic lambda layer version
- def test_basic_layer_with_parameters(self): Creates a basic lambda layer version w... | Implement the Python class `TestBasicLayerVersion` described below.
Class description:
Basic AWS::Lambda::LayerVersion tests
Method signatures and docstrings:
- def test_basic_layer_version(self): Creates a basic lambda layer version
- def test_basic_layer_with_parameters(self): Creates a basic lambda layer version w... | 0bb862ea715a4aafbb7984b407a81856b3ae19c4 | <|skeleton|>
class TestBasicLayerVersion:
"""Basic AWS::Lambda::LayerVersion tests"""
def test_basic_layer_version(self):
"""Creates a basic lambda layer version"""
<|body_0|>
def test_basic_layer_with_parameters(self):
"""Creates a basic lambda layer version with parameters"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestBasicLayerVersion:
"""Basic AWS::Lambda::LayerVersion tests"""
def test_basic_layer_version(self):
"""Creates a basic lambda layer version"""
self.create_and_verify_stack('single/basic_layer')
layer_logical_id_1 = self.get_logical_id_by_type('AWS::Lambda::LayerVersion')
... | the_stack_v2_python_sparse | integration/single/test_basic_layer_version.py | aws/serverless-application-model | train | 2,055 |
624cffbc146116a84c54b3a6f044bb14d3f803ee | [
"self._initialization()\nself.logfile = logfile\nself.sp_descriptormodel = spdescmodel\nself.lim_rows = lim_rows\nself.bool_inform = True if self.lim_rows != 0 else False\nself.prompt_inform = prompt_inform\nself.n_procs = n_procs\nself.proc_desc = 'Computation %s with %s'",
"m_aux0 = self.sp_descriptormodel.feat... | <|body_start_0|>
self._initialization()
self.logfile = logfile
self.sp_descriptormodel = spdescmodel
self.lim_rows = lim_rows
self.bool_inform = True if self.lim_rows != 0 else False
self.prompt_inform = prompt_inform
self.n_procs = n_procs
self.proc_desc ... | Spatial descriptor model processer. | SpatialDescriptorModelProcess | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpatialDescriptorModelProcess:
"""Spatial descriptor model processer."""
def __init__(self, spdescmodel, logfile, lim_rows=0, n_procs=0, prompt_inform=False):
"""The spatialdescriptor model process instantiation. Parameters ---------- logfile: str the file we want to log all the proc... | stack_v2_sparse_classes_36k_train_023256 | 4,723 | permissive | [
{
"docstring": "The spatialdescriptor model process instantiation. Parameters ---------- logfile: str the file we want to log all the process. lim_rows: int (default=0) the limit number of rows uninformed. If is 0, there are not partial information of the process. n_procs: int (default=0) the number of cpu used... | 4 | null | Implement the Python class `SpatialDescriptorModelProcess` described below.
Class description:
Spatial descriptor model processer.
Method signatures and docstrings:
- def __init__(self, spdescmodel, logfile, lim_rows=0, n_procs=0, prompt_inform=False): The spatialdescriptor model process instantiation. Parameters ---... | Implement the Python class `SpatialDescriptorModelProcess` described below.
Class description:
Spatial descriptor model processer.
Method signatures and docstrings:
- def __init__(self, spdescmodel, logfile, lim_rows=0, n_procs=0, prompt_inform=False): The spatialdescriptor model process instantiation. Parameters ---... | e028008f9750521bf7d311f7cd3323c88d621ea4 | <|skeleton|>
class SpatialDescriptorModelProcess:
"""Spatial descriptor model processer."""
def __init__(self, spdescmodel, logfile, lim_rows=0, n_procs=0, prompt_inform=False):
"""The spatialdescriptor model process instantiation. Parameters ---------- logfile: str the file we want to log all the proc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpatialDescriptorModelProcess:
"""Spatial descriptor model processer."""
def __init__(self, spdescmodel, logfile, lim_rows=0, n_procs=0, prompt_inform=False):
"""The spatialdescriptor model process instantiation. Parameters ---------- logfile: str the file we want to log all the process. lim_rows... | the_stack_v2_python_sparse | pySpatialTools/FeatureManagement/process_descriptormodel.py | tgquintela/pySpatialTools | train | 8 |
605863f12dc9602d132c797dd65eafc0ab2e301e | [
"HttpFile.__init__(self, name, mode, upload='')\nif 'w' not in mode:\n raise ValueError('Only write operations allowed.')\nself._url = url + ('/' if not url.endswith('/') else '')\nself._headers = {'Authorization': 'Token ' + token} if token is not None else {}",
"async with aiohttp.ClientSession() as session:... | <|body_start_0|>
HttpFile.__init__(self, name, mode, upload='')
if 'w' not in mode:
raise ValueError('Only write operations allowed.')
self._url = url + ('/' if not url.endswith('/') else '')
self._headers = {'Authorization': 'Token ' + token} if token is not None else {}
<|e... | Wraps a file in an archive. To be used in combination with pyobs-archive. | ArchiveFile | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArchiveFile:
"""Wraps a file in an archive. To be used in combination with pyobs-archive."""
def __init__(self, name: str, url: str, mode: str='w', token: Optional[str]=None):
"""Creates a new archive file. Args: name: Name of file. mode: Open mode (r/w). url: Archive url url. token:... | stack_v2_sparse_classes_36k_train_023257 | 2,402 | permissive | [
{
"docstring": "Creates a new archive file. Args: name: Name of file. mode: Open mode (r/w). url: Archive url url. token: Authorization token.",
"name": "__init__",
"signature": "def __init__(self, name: str, url: str, mode: str='w', token: Optional[str]=None)"
},
{
"docstring": "If in write mod... | 2 | null | Implement the Python class `ArchiveFile` described below.
Class description:
Wraps a file in an archive. To be used in combination with pyobs-archive.
Method signatures and docstrings:
- def __init__(self, name: str, url: str, mode: str='w', token: Optional[str]=None): Creates a new archive file. Args: name: Name of ... | Implement the Python class `ArchiveFile` described below.
Class description:
Wraps a file in an archive. To be used in combination with pyobs-archive.
Method signatures and docstrings:
- def __init__(self, name: str, url: str, mode: str='w', token: Optional[str]=None): Creates a new archive file. Args: name: Name of ... | 2d7a06e5485b61b6ca7e51d99b08651ea6021086 | <|skeleton|>
class ArchiveFile:
"""Wraps a file in an archive. To be used in combination with pyobs-archive."""
def __init__(self, name: str, url: str, mode: str='w', token: Optional[str]=None):
"""Creates a new archive file. Args: name: Name of file. mode: Open mode (r/w). url: Archive url url. token:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArchiveFile:
"""Wraps a file in an archive. To be used in combination with pyobs-archive."""
def __init__(self, name: str, url: str, mode: str='w', token: Optional[str]=None):
"""Creates a new archive file. Args: name: Name of file. mode: Open mode (r/w). url: Archive url url. token: Authorizatio... | the_stack_v2_python_sparse | pyobs/vfs/archivefile.py | pyobs/pyobs-core | train | 9 |
eaf71b28a5b2935bc49068733c9c08253718054c | [
"dp = [0] * (n + 1)\nfor i in range(1, n + 1):\n dp[i] = (dp[i - 1] + m) % i\nreturn dp[-1]",
"if n == 1:\n return 0\nreturn (self.lastRemaining_2(n - 1, m) + m) % n"
] | <|body_start_0|>
dp = [0] * (n + 1)
for i in range(1, n + 1):
dp[i] = (dp[i - 1] + m) % i
return dp[-1]
<|end_body_0|>
<|body_start_1|>
if n == 1:
return 0
return (self.lastRemaining_2(n - 1, m) + m) % n
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lastRemaining(self, n, m):
""":type n: int :type m: int :rtype: int"""
<|body_0|>
def lastRemaining_2(self, n, m):
""":type n: int :type m: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dp = [0] * (n + 1)
for ... | stack_v2_sparse_classes_36k_train_023258 | 743 | no_license | [
{
"docstring": ":type n: int :type m: int :rtype: int",
"name": "lastRemaining",
"signature": "def lastRemaining(self, n, m)"
},
{
"docstring": ":type n: int :type m: int :rtype: int",
"name": "lastRemaining_2",
"signature": "def lastRemaining_2(self, n, m)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lastRemaining(self, n, m): :type n: int :type m: int :rtype: int
- def lastRemaining_2(self, n, m): :type n: int :type m: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lastRemaining(self, n, m): :type n: int :type m: int :rtype: int
- def lastRemaining_2(self, n, m): :type n: int :type m: int :rtype: int
<|skeleton|>
class Solution:
d... | 967b0fbb40ae491b552bc3365a481e66324cb6f2 | <|skeleton|>
class Solution:
def lastRemaining(self, n, m):
""":type n: int :type m: int :rtype: int"""
<|body_0|>
def lastRemaining_2(self, n, m):
""":type n: int :type m: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lastRemaining(self, n, m):
""":type n: int :type m: int :rtype: int"""
dp = [0] * (n + 1)
for i in range(1, n + 1):
dp[i] = (dp[i - 1] + m) % i
return dp[-1]
def lastRemaining_2(self, n, m):
""":type n: int :type m: int :rtype: int"""
... | the_stack_v2_python_sparse | jianzhi_offer/60_圆圈中最后剩下的数字.py | ryanatgz/data_structure_and_algorithm | train | 0 | |
99414251a2973dca978cc8fcf7746bab074b8e6a | [
"bin, *_ = packager.identify(installation=self)\nself.version, _ = packager.info(package=bin)\nflavor = self.flavor\nself.compiler = 'cython' if flavor == 'cython2' else flavor\ncompiler = 'bin/{}'.format(self.compiler)\nprefix = packager.findfirst(target=compiler, contents=packager.contents(package=bin))\nself.bin... | <|body_start_0|>
bin, *_ = packager.identify(installation=self)
self.version, _ = packager.info(package=bin)
flavor = self.flavor
self.compiler = 'cython' if flavor == 'cython2' else flavor
compiler = 'bin/{}'.format(self.compiler)
prefix = packager.findfirst(target=compi... | The package manager for cython instances | Default | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Default:
"""The package manager for cython instances"""
def dpkg(self, packager):
"""Attempt to repair my configuration"""
<|body_0|>
def macports(self, packager):
"""Attempt to repair my configuration"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_023259 | 6,451 | permissive | [
{
"docstring": "Attempt to repair my configuration",
"name": "dpkg",
"signature": "def dpkg(self, packager)"
},
{
"docstring": "Attempt to repair my configuration",
"name": "macports",
"signature": "def macports(self, packager)"
}
] | 2 | null | Implement the Python class `Default` described below.
Class description:
The package manager for cython instances
Method signatures and docstrings:
- def dpkg(self, packager): Attempt to repair my configuration
- def macports(self, packager): Attempt to repair my configuration | Implement the Python class `Default` described below.
Class description:
The package manager for cython instances
Method signatures and docstrings:
- def dpkg(self, packager): Attempt to repair my configuration
- def macports(self, packager): Attempt to repair my configuration
<|skeleton|>
class Default:
"""The ... | d741c44ffb3e9e1f726bf492202ac8738bb4aa1c | <|skeleton|>
class Default:
"""The package manager for cython instances"""
def dpkg(self, packager):
"""Attempt to repair my configuration"""
<|body_0|>
def macports(self, packager):
"""Attempt to repair my configuration"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Default:
"""The package manager for cython instances"""
def dpkg(self, packager):
"""Attempt to repair my configuration"""
bin, *_ = packager.identify(installation=self)
self.version, _ = packager.info(package=bin)
flavor = self.flavor
self.compiler = 'cython' if f... | the_stack_v2_python_sparse | packages/pyre/externals/Cython.py | pyre/pyre | train | 27 |
eb94ced011c9acf1bca48a1051ba75aaf66dcd48 | [
"if l1 is None:\n return l2\nelif l2 is None:\n return l1\nelif l1.val < l2.val:\n l1.next = self.merge_two_lists(l1.next, l2)\n return l1\nelse:\n l2.next = self.merge_two_lists(l1, l2.next)\n return l2",
"head = ListNode()\ncurr = head\nwhile l1 and l2:\n if l1.val < l2.val:\n curr.n... | <|body_start_0|>
if l1 is None:
return l2
elif l2 is None:
return l1
elif l1.val < l2.val:
l1.next = self.merge_two_lists(l1.next, l2)
return l1
else:
l2.next = self.merge_two_lists(l1, l2.next)
return l2
<|end_body_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def merge_two_lists(self, l1, l2):
"""递归实现"""
<|body_0|>
def merge_two_lists2(self, l1, l2):
"""非递归实现"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if l1 is None:
return l2
elif l2 is None:
return l1
... | stack_v2_sparse_classes_36k_train_023260 | 1,894 | no_license | [
{
"docstring": "递归实现",
"name": "merge_two_lists",
"signature": "def merge_two_lists(self, l1, l2)"
},
{
"docstring": "非递归实现",
"name": "merge_two_lists2",
"signature": "def merge_two_lists2(self, l1, l2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014468 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge_two_lists(self, l1, l2): 递归实现
- def merge_two_lists2(self, l1, l2): 非递归实现 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge_two_lists(self, l1, l2): 递归实现
- def merge_two_lists2(self, l1, l2): 非递归实现
<|skeleton|>
class Solution:
def merge_two_lists(self, l1, l2):
"""递归实现"""
... | a20497048f45e18e99648c46e8ee3f0058b650c7 | <|skeleton|>
class Solution:
def merge_two_lists(self, l1, l2):
"""递归实现"""
<|body_0|>
def merge_two_lists2(self, l1, l2):
"""非递归实现"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def merge_two_lists(self, l1, l2):
"""递归实现"""
if l1 is None:
return l2
elif l2 is None:
return l1
elif l1.val < l2.val:
l1.next = self.merge_two_lists(l1.next, l2)
return l1
else:
l2.next = self.merge... | the_stack_v2_python_sparse | Week_01/mergeTwoLists.py | liqian7979/algorithm016 | train | 0 | |
ece1c7c642d730d38a41a8bd8efaf23ce4d538b0 | [
"if not strs:\n return ''\nif len(strs) == 1:\n return strs[0]\nminl = min([len(x) for x in strs])\nend = 0\nwhile end < minl:\n for i in range(1, len(strs)):\n if strs[i][end] != strs[i - 1][end]:\n print('sdsdsd')\n return strs[0][:end]\n end += 1\nprint(strs[0][:end])\nre... | <|body_start_0|>
if not strs:
return ''
if len(strs) == 1:
return strs[0]
minl = min([len(x) for x in strs])
end = 0
while end < minl:
for i in range(1, len(strs)):
if strs[i][end] != strs[i - 1][end]:
print(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_0|>
def longestCommonPrefix1(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not strs:
ret... | stack_v2_sparse_classes_36k_train_023261 | 2,588 | no_license | [
{
"docstring": ":type strs: List[str] :rtype: str",
"name": "longestCommonPrefix",
"signature": "def longestCommonPrefix(self, strs)"
},
{
"docstring": ":type strs: List[str] :rtype: str",
"name": "longestCommonPrefix1",
"signature": "def longestCommonPrefix1(self, strs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002388 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str
- def longestCommonPrefix1(self, strs): :type strs: List[str] :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str
- def longestCommonPrefix1(self, strs): :type strs: List[str] :rtype: str
<|skeleton|>
class Solution:
... | f022677c042db3598003df1a320a70f0edc4f870 | <|skeleton|>
class Solution:
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_0|>
def longestCommonPrefix1(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str"""
if not strs:
return ''
if len(strs) == 1:
return strs[0]
minl = min([len(x) for x in strs])
end = 0
while end < minl:
for i in range(1, len... | the_stack_v2_python_sparse | StringDeal/zuichanggonggongqianzui.py | daisyzl/program-exercise-python | train | 0 | |
44600ea2f5cc3a65c8728e5f89347e4aeb7f7c20 | [
"if public_ip is not None:\n self.vn_data['gcpAssignPublicIP'] = public_ip\nreturn self",
"if zone == '':\n self.vn_data['gcpZone'] = None\nelif zone is not None:\n self.vn_data['gcpZone'] = zone\nif project_id == '':\n self.vn_data['gcpProjectIdForCreatedResources'] = None\nelif project_id is not Non... | <|body_start_0|>
if public_ip is not None:
self.vn_data['gcpAssignPublicIP'] = public_ip
return self
<|end_body_0|>
<|body_start_1|>
if zone == '':
self.vn_data['gcpZone'] = None
elif zone is not None:
self.vn_data['gcpZone'] = zone
if project... | FMGCPVirtualNetwork | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FMGCPVirtualNetwork:
def set_assign_public_ip(self, public_ip=True):
"""Sets whether the instances on this network will have a publicly accessible IP :param bool public_ip: if False, the instances will not be accessible from outside GCP"""
<|body_0|>
def set_location_for_cre... | stack_v2_sparse_classes_36k_train_023262 | 13,612 | permissive | [
{
"docstring": "Sets whether the instances on this network will have a publicly accessible IP :param bool public_ip: if False, the instances will not be accessible from outside GCP",
"name": "set_assign_public_ip",
"signature": "def set_assign_public_ip(self, public_ip=True)"
},
{
"docstring": "... | 3 | stack_v2_sparse_classes_30k_train_001226 | Implement the Python class `FMGCPVirtualNetwork` described below.
Class description:
Implement the FMGCPVirtualNetwork class.
Method signatures and docstrings:
- def set_assign_public_ip(self, public_ip=True): Sets whether the instances on this network will have a publicly accessible IP :param bool public_ip: if Fals... | Implement the Python class `FMGCPVirtualNetwork` described below.
Class description:
Implement the FMGCPVirtualNetwork class.
Method signatures and docstrings:
- def set_assign_public_ip(self, public_ip=True): Sets whether the instances on this network will have a publicly accessible IP :param bool public_ip: if Fals... | 2f218b45b6354998cc2403ff517c5ef132fe8fdb | <|skeleton|>
class FMGCPVirtualNetwork:
def set_assign_public_ip(self, public_ip=True):
"""Sets whether the instances on this network will have a publicly accessible IP :param bool public_ip: if False, the instances will not be accessible from outside GCP"""
<|body_0|>
def set_location_for_cre... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FMGCPVirtualNetwork:
def set_assign_public_ip(self, public_ip=True):
"""Sets whether the instances on this network will have a publicly accessible IP :param bool public_ip: if False, the instances will not be accessible from outside GCP"""
if public_ip is not None:
self.vn_data['gc... | the_stack_v2_python_sparse | dataikuapi/fm/virtualnetworks.py | dataiku/dataiku-api-client-python | train | 33 | |
b2a5772a1888b790a6ada64bff0f2fe5cb0f2c46 | [
"super(AdamWeightDecayOptimizer, self).__init__(False, name)\nself.learning_rate = learning_rate\nself.weight_decay_rate = weight_decay_rate\nself.beta_1 = beta_1\nself.beta_2 = beta_2\nself.epsilon = epsilon\nself.exclude_from_weight_decay = exclude_from_weight_decay\nself.include_in_weight_decay = include_in_weig... | <|body_start_0|>
super(AdamWeightDecayOptimizer, self).__init__(False, name)
self.learning_rate = learning_rate
self.weight_decay_rate = weight_decay_rate
self.beta_1 = beta_1
self.beta_2 = beta_2
self.epsilon = epsilon
self.exclude_from_weight_decay = exclude_fro... | A basic Adam optimizer that includes "correct" L2 weight decay. | AdamWeightDecayOptimizer | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdamWeightDecayOptimizer:
"""A basic Adam optimizer that includes "correct" L2 weight decay."""
def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, include_in_weight_decay=('r_s_bias', 'r_r_bias', 'r_w_bias'), name... | stack_v2_sparse_classes_36k_train_023263 | 11,858 | permissive | [
{
"docstring": "Constructs a AdamWeightDecayOptimizer.",
"name": "__init__",
"signature": "def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, include_in_weight_decay=('r_s_bias', 'r_r_bias', 'r_w_bias'), name='AdamWeightDecay... | 4 | null | Implement the Python class `AdamWeightDecayOptimizer` described below.
Class description:
A basic Adam optimizer that includes "correct" L2 weight decay.
Method signatures and docstrings:
- def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None... | Implement the Python class `AdamWeightDecayOptimizer` described below.
Class description:
A basic Adam optimizer that includes "correct" L2 weight decay.
Method signatures and docstrings:
- def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class AdamWeightDecayOptimizer:
"""A basic Adam optimizer that includes "correct" L2 weight decay."""
def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, include_in_weight_decay=('r_s_bias', 'r_r_bias', 'r_w_bias'), name... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdamWeightDecayOptimizer:
"""A basic Adam optimizer that includes "correct" L2 weight decay."""
def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, include_in_weight_decay=('r_s_bias', 'r_r_bias', 'r_w_bias'), name='AdamWeightD... | the_stack_v2_python_sparse | spreadsheet_coder/model_utils.py | Jimmy-INL/google-research | train | 1 |
f01b95eb85ae3affcc8d4fce1512af20d772dd75 | [
"super().validate(data)\nif not data.get('cost_type'):\n data['cost_type'] = get_cost_type(self.context.get('request'))\nerror = {}\nif 'delta' in data.get('order_by', {}) and 'delta' not in data:\n error['order_by'] = _('Cannot order by delta without a delta param')\n raise serializers.ValidationError(err... | <|body_start_0|>
super().validate(data)
if not data.get('cost_type'):
data['cost_type'] = get_cost_type(self.context.get('request'))
error = {}
if 'delta' in data.get('order_by', {}) and 'delta' not in data:
error['order_by'] = _('Cannot order by delta without a d... | Serializer for handling query parameters. | AWSQueryParamSerializer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AWSQueryParamSerializer:
"""Serializer for handling query parameters."""
def validate(self, data):
"""Validate incoming data. Args: data (Dict): data to be validated Returns: (Dict): Validated data Raises: (ValidationError): if field inputs are invalid"""
<|body_0|>
def ... | stack_v2_sparse_classes_36k_train_023264 | 8,520 | permissive | [
{
"docstring": "Validate incoming data. Args: data (Dict): data to be validated Returns: (Dict): Validated data Raises: (ValidationError): if field inputs are invalid",
"name": "validate",
"signature": "def validate(self, data)"
},
{
"docstring": "Validate incoming group_by data. Args: data (Dic... | 2 | stack_v2_sparse_classes_30k_train_008207 | Implement the Python class `AWSQueryParamSerializer` described below.
Class description:
Serializer for handling query parameters.
Method signatures and docstrings:
- def validate(self, data): Validate incoming data. Args: data (Dict): data to be validated Returns: (Dict): Validated data Raises: (ValidationError): if... | Implement the Python class `AWSQueryParamSerializer` described below.
Class description:
Serializer for handling query parameters.
Method signatures and docstrings:
- def validate(self, data): Validate incoming data. Args: data (Dict): data to be validated Returns: (Dict): Validated data Raises: (ValidationError): if... | 0416e5216eb1ec4b41c8dd4999adde218b1ab2e1 | <|skeleton|>
class AWSQueryParamSerializer:
"""Serializer for handling query parameters."""
def validate(self, data):
"""Validate incoming data. Args: data (Dict): data to be validated Returns: (Dict): Validated data Raises: (ValidationError): if field inputs are invalid"""
<|body_0|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AWSQueryParamSerializer:
"""Serializer for handling query parameters."""
def validate(self, data):
"""Validate incoming data. Args: data (Dict): data to be validated Returns: (Dict): Validated data Raises: (ValidationError): if field inputs are invalid"""
super().validate(data)
if... | the_stack_v2_python_sparse | koku/api/report/aws/serializers.py | project-koku/koku | train | 225 |
622f265f10cd073d10096cfffdc1e7b0a1f0fde5 | [
"self.next = [None] * 26\nself.word = False\nif len(suffix) == 0:\n self.word = True\n return\nidx = ord(suffix[0]) - BaseA\nif self.next[idx] is None:\n self.next[idx] = PrefixNode(suffix[1:])\nelse:\n self.next[idx].add(suffix[1:])",
"if suffix == '':\n if self.word:\n return False\n se... | <|body_start_0|>
self.next = [None] * 26
self.word = False
if len(suffix) == 0:
self.word = True
return
idx = ord(suffix[0]) - BaseA
if self.next[idx] is None:
self.next[idx] = PrefixNode(suffix[1:])
else:
self.next[idx].add... | PrefixNode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrefixNode:
def __init__(self, suffix):
"""Node in a Prefix Tree."""
<|body_0|>
def add(self, suffix):
"""Add rest of suffix."""
<|body_1|>
def remove(self, suffix):
"""Remove rest of suffix."""
<|body_2|>
def __repr__(self):
... | stack_v2_sparse_classes_36k_train_023265 | 3,958 | no_license | [
{
"docstring": "Node in a Prefix Tree.",
"name": "__init__",
"signature": "def __init__(self, suffix)"
},
{
"docstring": "Add rest of suffix.",
"name": "add",
"signature": "def add(self, suffix)"
},
{
"docstring": "Remove rest of suffix.",
"name": "remove",
"signature": "... | 4 | stack_v2_sparse_classes_30k_train_020050 | Implement the Python class `PrefixNode` described below.
Class description:
Implement the PrefixNode class.
Method signatures and docstrings:
- def __init__(self, suffix): Node in a Prefix Tree.
- def add(self, suffix): Add rest of suffix.
- def remove(self, suffix): Remove rest of suffix.
- def __repr__(self): Repre... | Implement the Python class `PrefixNode` described below.
Class description:
Implement the PrefixNode class.
Method signatures and docstrings:
- def __init__(self, suffix): Node in a Prefix Tree.
- def add(self, suffix): Add rest of suffix.
- def remove(self, suffix): Remove rest of suffix.
- def __repr__(self): Repre... | ec8837af1df91167fdc8666863ac9b390095a441 | <|skeleton|>
class PrefixNode:
def __init__(self, suffix):
"""Node in a Prefix Tree."""
<|body_0|>
def add(self, suffix):
"""Add rest of suffix."""
<|body_1|>
def remove(self, suffix):
"""Remove rest of suffix."""
<|body_2|>
def __repr__(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrefixNode:
def __init__(self, suffix):
"""Node in a Prefix Tree."""
self.next = [None] * 26
self.word = False
if len(suffix) == 0:
self.word = True
return
idx = ord(suffix[0]) - BaseA
if self.next[idx] is None:
self.next[idx]... | the_stack_v2_python_sparse | 3. Pointer Structures/prefixTreeLinkedList.py | RANUX/python-algorithms | train | 0 | |
c6b22da551eb21565714b289562bbbe23eecdd02 | [
"for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n if nums[i] + nums[j] == target:\n return [i, j]",
"ht = {}\nfor i in range(len(nums)):\n ht[nums[i]] = i\nfor j in range(len(nums)):\n if target - nums[j] in ht and j != ht[target - nums[j]]:\n return [j, ht[target... | <|body_start_0|>
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
<|end_body_0|>
<|body_start_1|>
ht = {}
for i in range(len(nums)):
ht[nums[i]] = i
for j in range(len(n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_023266 | 836 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum1",
"signature": "def twoSum1(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum2",
"signature": "def twoSum2(self, nums, target)"
... | 2 | stack_v2_sparse_classes_30k_train_002029 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum1(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum2(self, nums, target): :type nums: List[int] :type target: int :rtype: List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum1(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum2(self, nums, target): :type nums: List[int] :type target: int :rtype: List... | 8dfbb10a87d8a3fdde466ab16fff8b67503e41f4 | <|skeleton|>
class Solution:
def twoSum1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
def twoSum2(self, nums, tar... | the_stack_v2_python_sparse | easy/0001.two-sum.py | codershenghai/PyLeetcode | train | 0 | |
1476efeb3e657995a52da993a83b207470af6553 | [
"re = cloudparking_service().mockCarInOut(send_data['carNum'], 1, send_data['outClientID'])\nresult = re\nAssertions().assert_in_text(result, expect['mockCarOutMessage'])",
"re = CarInOutHandle(sentryLogin).carInOutHandle(send_data['carNum'], send_data['carOutHandleType'], send_data['carOut_jobId'])\nresult = re\... | <|body_start_0|>
re = cloudparking_service().mockCarInOut(send_data['carNum'], 1, send_data['outClientID'])
result = re
Assertions().assert_in_text(result, expect['mockCarOutMessage'])
<|end_body_0|>
<|body_start_1|>
re = CarInOutHandle(sentryLogin).carInOutHandle(send_data['carNum'], s... | 临时车无在场需缴费宽出(岗亭收费处收费放行) | TestCarOutNoInside | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCarOutNoInside:
"""临时车无在场需缴费宽出(岗亭收费处收费放行)"""
def test_mockCarOut(self, sentryLogin, send_data, expect):
"""离场"""
<|body_0|>
def test_sentryAbnormalPay(self, sentryLogin, send_data, expect):
"""岗亭端收费异常放行"""
<|body_1|>
def test_carLeaveHistory(self... | stack_v2_sparse_classes_36k_train_023267 | 1,943 | no_license | [
{
"docstring": "离场",
"name": "test_mockCarOut",
"signature": "def test_mockCarOut(self, sentryLogin, send_data, expect)"
},
{
"docstring": "岗亭端收费异常放行",
"name": "test_sentryAbnormalPay",
"signature": "def test_sentryAbnormalPay(self, sentryLogin, send_data, expect)"
},
{
"docstrin... | 3 | stack_v2_sparse_classes_30k_train_002109 | Implement the Python class `TestCarOutNoInside` described below.
Class description:
临时车无在场需缴费宽出(岗亭收费处收费放行)
Method signatures and docstrings:
- def test_mockCarOut(self, sentryLogin, send_data, expect): 离场
- def test_sentryAbnormalPay(self, sentryLogin, send_data, expect): 岗亭端收费异常放行
- def test_carLeaveHistory(self, us... | Implement the Python class `TestCarOutNoInside` described below.
Class description:
临时车无在场需缴费宽出(岗亭收费处收费放行)
Method signatures and docstrings:
- def test_mockCarOut(self, sentryLogin, send_data, expect): 离场
- def test_sentryAbnormalPay(self, sentryLogin, send_data, expect): 岗亭端收费异常放行
- def test_carLeaveHistory(self, us... | 34c368c109867da26d9256bca85f872b0fac2ea7 | <|skeleton|>
class TestCarOutNoInside:
"""临时车无在场需缴费宽出(岗亭收费处收费放行)"""
def test_mockCarOut(self, sentryLogin, send_data, expect):
"""离场"""
<|body_0|>
def test_sentryAbnormalPay(self, sentryLogin, send_data, expect):
"""岗亭端收费异常放行"""
<|body_1|>
def test_carLeaveHistory(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCarOutNoInside:
"""临时车无在场需缴费宽出(岗亭收费处收费放行)"""
def test_mockCarOut(self, sentryLogin, send_data, expect):
"""离场"""
re = cloudparking_service().mockCarInOut(send_data['carNum'], 1, send_data['outClientID'])
result = re
Assertions().assert_in_text(result, expect['mockCarOu... | the_stack_v2_python_sparse | test_suite/sentryDutyRoom/carInOutHandle/test_carOutNoInside.py | oyebino/pomp_api | train | 1 |
5ace2ac98aa864df1be860d394a977fdfbe13d0c | [
"if not type_name_conflicts and (not renamed_to_builtin_scalar_conflicts):\n raise ValueError('Cannot raise SchemaRenameNameConflictError without at least one conflict, but type_name_conflicts and renamed_to_builtin_scalar_conflicts arguments were both empty dictionaries.')\nsuper().__init__()\nself.type_name_co... | <|body_start_0|>
if not type_name_conflicts and (not renamed_to_builtin_scalar_conflicts):
raise ValueError('Cannot raise SchemaRenameNameConflictError without at least one conflict, but type_name_conflicts and renamed_to_builtin_scalar_conflicts arguments were both empty dictionaries.')
sup... | Raised when renaming causes name conflicts. | SchemaRenameNameConflictError | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchemaRenameNameConflictError:
"""Raised when renaming causes name conflicts."""
def __init__(self, type_name_conflicts: Dict[str, Set[str]], renamed_to_builtin_scalar_conflicts: Dict[str, str]) -> None:
"""Record all renaming conflicts."""
<|body_0|>
def __str__(self) -... | stack_v2_sparse_classes_36k_train_023268 | 28,678 | permissive | [
{
"docstring": "Record all renaming conflicts.",
"name": "__init__",
"signature": "def __init__(self, type_name_conflicts: Dict[str, Set[str]], renamed_to_builtin_scalar_conflicts: Dict[str, str]) -> None"
},
{
"docstring": "Explain renaming conflict and the fix.",
"name": "__str__",
"si... | 2 | null | Implement the Python class `SchemaRenameNameConflictError` described below.
Class description:
Raised when renaming causes name conflicts.
Method signatures and docstrings:
- def __init__(self, type_name_conflicts: Dict[str, Set[str]], renamed_to_builtin_scalar_conflicts: Dict[str, str]) -> None: Record all renaming ... | Implement the Python class `SchemaRenameNameConflictError` described below.
Class description:
Raised when renaming causes name conflicts.
Method signatures and docstrings:
- def __init__(self, type_name_conflicts: Dict[str, Set[str]], renamed_to_builtin_scalar_conflicts: Dict[str, str]) -> None: Record all renaming ... | 4e68d592fc97855ca043dc20bdf59be4298647ab | <|skeleton|>
class SchemaRenameNameConflictError:
"""Raised when renaming causes name conflicts."""
def __init__(self, type_name_conflicts: Dict[str, Set[str]], renamed_to_builtin_scalar_conflicts: Dict[str, str]) -> None:
"""Record all renaming conflicts."""
<|body_0|>
def __str__(self) -... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SchemaRenameNameConflictError:
"""Raised when renaming causes name conflicts."""
def __init__(self, type_name_conflicts: Dict[str, Set[str]], renamed_to_builtin_scalar_conflicts: Dict[str, str]) -> None:
"""Record all renaming conflicts."""
if not type_name_conflicts and (not renamed_to_b... | the_stack_v2_python_sparse | graphql_compiler/schema_transformation/utils.py | justinaustin/graphql-compiler | train | 0 |
6c823a3000b44dc9f90077193c7e8f0ca3c40e4f | [
"self.lexicon = set([line.strip() for line in open(lexicon)])\nself.type = type\nself.feature_index = None",
"result = []\nf = open(corpus)\nfor line in f:\n data = line.strip().split('\\t')\n target = data[1].strip()\n if target in self.lexicon:\n if self.type == 'simple':\n result.app... | <|body_start_0|>
self.lexicon = set([line.strip() for line in open(lexicon)])
self.type = type
self.feature_index = None
<|end_body_0|>
<|body_start_1|>
result = []
f = open(corpus)
for line in f:
data = line.strip().split('\t')
target = data[1].s... | LexiconIdentifier | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LexiconIdentifier:
def __init__(self, lexicon, type):
"""Creates a LexiconIdentifier instance. @param lexicon: Lexicon containing simple or complex, one word per line. @param type: Type of lexicon. Values: 'complex', 'simple'"""
<|body_0|>
def identifyComplexWords(self, corp... | stack_v2_sparse_classes_36k_train_023269 | 10,931 | no_license | [
{
"docstring": "Creates a LexiconIdentifier instance. @param lexicon: Lexicon containing simple or complex, one word per line. @param type: Type of lexicon. Values: 'complex', 'simple'",
"name": "__init__",
"signature": "def __init__(self, lexicon, type)"
},
{
"docstring": "Judge if the target w... | 2 | null | Implement the Python class `LexiconIdentifier` described below.
Class description:
Implement the LexiconIdentifier class.
Method signatures and docstrings:
- def __init__(self, lexicon, type): Creates a LexiconIdentifier instance. @param lexicon: Lexicon containing simple or complex, one word per line. @param type: T... | Implement the Python class `LexiconIdentifier` described below.
Class description:
Implement the LexiconIdentifier class.
Method signatures and docstrings:
- def __init__(self, lexicon, type): Creates a LexiconIdentifier instance. @param lexicon: Lexicon containing simple or complex, one word per line. @param type: T... | 6f5eee43e34baa796efb16db0bc8562243a049b6 | <|skeleton|>
class LexiconIdentifier:
def __init__(self, lexicon, type):
"""Creates a LexiconIdentifier instance. @param lexicon: Lexicon containing simple or complex, one word per line. @param type: Type of lexicon. Values: 'complex', 'simple'"""
<|body_0|>
def identifyComplexWords(self, corp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LexiconIdentifier:
def __init__(self, lexicon, type):
"""Creates a LexiconIdentifier instance. @param lexicon: Lexicon containing simple or complex, one word per line. @param type: Type of lexicon. Values: 'complex', 'simple'"""
self.lexicon = set([line.strip() for line in open(lexicon)])
... | the_stack_v2_python_sparse | sr_userstudy/scripts/rankers/modified_svmrank/lexenstein/identifiers.py | ghpaetzold/phd-backup | train | 0 | |
8fc595d72b418dde888143fb790f919814147dd7 | [
"super(SelfAttention, self).__init__()\nself.W = tf.keras.layers.Dense(units)\nself.U = tf.keras.layers.Dense(units)\nself.V = tf.keras.layers.Dense(1)",
"Q = tf.expand_dims(s_prev, axis=1)\nw = self.W(Q)\nu = self.U(hidden_states)\nscore = self.V(tf.nn.tanh(w + u))\nweights = tf.nn.softmax(score, axis=1)\ncontex... | <|body_start_0|>
super(SelfAttention, self).__init__()
self.W = tf.keras.layers.Dense(units)
self.U = tf.keras.layers.Dense(units)
self.V = tf.keras.layers.Dense(1)
<|end_body_0|>
<|body_start_1|>
Q = tf.expand_dims(s_prev, axis=1)
w = self.W(Q)
u = self.U(hidden... | Calculate the attention for machine translation | SelfAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfAttention:
"""Calculate the attention for machine translation"""
def __init__(self, units):
"""Class constructor Arguments: - units is an integer representing the number of hidden units in the alignment model Public instance attributes: - W - a Dense layer with units units, to be... | stack_v2_sparse_classes_36k_train_023270 | 1,862 | no_license | [
{
"docstring": "Class constructor Arguments: - units is an integer representing the number of hidden units in the alignment model Public instance attributes: - W - a Dense layer with units units, to be applied to the previous decoder hidden state - U - a Dense layer with units units, to be applied to the encode... | 2 | stack_v2_sparse_classes_30k_train_005701 | Implement the Python class `SelfAttention` described below.
Class description:
Calculate the attention for machine translation
Method signatures and docstrings:
- def __init__(self, units): Class constructor Arguments: - units is an integer representing the number of hidden units in the alignment model Public instanc... | Implement the Python class `SelfAttention` described below.
Class description:
Calculate the attention for machine translation
Method signatures and docstrings:
- def __init__(self, units): Class constructor Arguments: - units is an integer representing the number of hidden units in the alignment model Public instanc... | fc2cec306961f7ca2448965ddd3a2f656bbe10c7 | <|skeleton|>
class SelfAttention:
"""Calculate the attention for machine translation"""
def __init__(self, units):
"""Class constructor Arguments: - units is an integer representing the number of hidden units in the alignment model Public instance attributes: - W - a Dense layer with units units, to be... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SelfAttention:
"""Calculate the attention for machine translation"""
def __init__(self, units):
"""Class constructor Arguments: - units is an integer representing the number of hidden units in the alignment model Public instance attributes: - W - a Dense layer with units units, to be applied to t... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/1-self_attention.py | dalexach/holbertonschool-machine_learning | train | 2 |
f657eaaf55e9e126de9af2fb7720d09e6e5eb84b | [
"if data is None:\n if lambtha <= 0:\n raise ValueError('lambtha must be a positive value')\n self.lambtha = lambtha\nelse:\n if type(data) is not list:\n raise TypeError('data must be a list')\n if len(data) < 2:\n raise ValueError('data must contain multiple values')\n self.lam... | <|body_start_0|>
if data is None:
if lambtha <= 0:
raise ValueError('lambtha must be a positive value')
self.lambtha = lambtha
else:
if type(data) is not list:
raise TypeError('data must be a list')
if len(data) < 2:
... | data distrubution | Poisson | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Poisson:
"""data distrubution"""
def __init__(self, data=None, lambtha=1.0):
"""initialize data"""
<|body_0|>
def pmf(self, k):
"""Calculate PMF at k successes"""
<|body_1|>
def cdf(self, k):
"""Calculates the value of the CDF for successes""... | stack_v2_sparse_classes_36k_train_023271 | 1,179 | no_license | [
{
"docstring": "initialize data",
"name": "__init__",
"signature": "def __init__(self, data=None, lambtha=1.0)"
},
{
"docstring": "Calculate PMF at k successes",
"name": "pmf",
"signature": "def pmf(self, k)"
},
{
"docstring": "Calculates the value of the CDF for successes",
... | 3 | null | Implement the Python class `Poisson` described below.
Class description:
data distrubution
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): initialize data
- def pmf(self, k): Calculate PMF at k successes
- def cdf(self, k): Calculates the value of the CDF for successes | Implement the Python class `Poisson` described below.
Class description:
data distrubution
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): initialize data
- def pmf(self, k): Calculate PMF at k successes
- def cdf(self, k): Calculates the value of the CDF for successes
<|skeleton|>
cl... | 4ac942126918c7acaa9ef88d18efe299b2f726fe | <|skeleton|>
class Poisson:
"""data distrubution"""
def __init__(self, data=None, lambtha=1.0):
"""initialize data"""
<|body_0|>
def pmf(self, k):
"""Calculate PMF at k successes"""
<|body_1|>
def cdf(self, k):
"""Calculates the value of the CDF for successes""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Poisson:
"""data distrubution"""
def __init__(self, data=None, lambtha=1.0):
"""initialize data"""
if data is None:
if lambtha <= 0:
raise ValueError('lambtha must be a positive value')
self.lambtha = lambtha
else:
if type(data) ... | the_stack_v2_python_sparse | math/0x03-probability/poisson.py | DracoMindz/holbertonschool-machine_learning | train | 2 |
a8b6dbd03e3a4ac9264eefde33822a6864bd520c | [
"if isinstance(s, str):\n emname, emaddr = parseaddr(s)\n return formataddr((Header(emname, 'utf-8').encode(), emaddr))\nelif isinstance(s, list):\n res = []\n for li in s:\n emname, emaddr = parseaddr(li)\n res.append(formataddr((Header(emname, 'utf-8').encode(), emaddr)))\n return ','... | <|body_start_0|>
if isinstance(s, str):
emname, emaddr = parseaddr(s)
return formataddr((Header(emname, 'utf-8').encode(), emaddr))
elif isinstance(s, list):
res = []
for li in s:
emname, emaddr = parseaddr(li)
res.append(fo... | EmailSend | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailSend:
def format_header_addr(s):
""":param s: [简称 <邮箱地址>] or 简称 <邮箱地址> :return: Header"""
<|body_0|>
def get_email_addr(s):
""":param s: [简称 <邮箱地址>] :return: addr列表"""
<|body_1|>
def get_email_type(s):
""":param s: [简称 <邮箱地址>] :return: 邮件类型列... | stack_v2_sparse_classes_36k_train_023272 | 4,798 | no_license | [
{
"docstring": ":param s: [简称 <邮箱地址>] or 简称 <邮箱地址> :return: Header",
"name": "format_header_addr",
"signature": "def format_header_addr(s)"
},
{
"docstring": ":param s: [简称 <邮箱地址>] :return: addr列表",
"name": "get_email_addr",
"signature": "def get_email_addr(s)"
},
{
"docstring": ... | 4 | null | Implement the Python class `EmailSend` described below.
Class description:
Implement the EmailSend class.
Method signatures and docstrings:
- def format_header_addr(s): :param s: [简称 <邮箱地址>] or 简称 <邮箱地址> :return: Header
- def get_email_addr(s): :param s: [简称 <邮箱地址>] :return: addr列表
- def get_email_type(s): :param s: ... | Implement the Python class `EmailSend` described below.
Class description:
Implement the EmailSend class.
Method signatures and docstrings:
- def format_header_addr(s): :param s: [简称 <邮箱地址>] or 简称 <邮箱地址> :return: Header
- def get_email_addr(s): :param s: [简称 <邮箱地址>] :return: addr列表
- def get_email_type(s): :param s: ... | 2bf74cc28a30b7eaa6674b9684dd7f8c6205e869 | <|skeleton|>
class EmailSend:
def format_header_addr(s):
""":param s: [简称 <邮箱地址>] or 简称 <邮箱地址> :return: Header"""
<|body_0|>
def get_email_addr(s):
""":param s: [简称 <邮箱地址>] :return: addr列表"""
<|body_1|>
def get_email_type(s):
""":param s: [简称 <邮箱地址>] :return: 邮件类型列... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmailSend:
def format_header_addr(s):
""":param s: [简称 <邮箱地址>] or 简称 <邮箱地址> :return: Header"""
if isinstance(s, str):
emname, emaddr = parseaddr(s)
return formataddr((Header(emname, 'utf-8').encode(), emaddr))
elif isinstance(s, list):
res = []
... | the_stack_v2_python_sparse | emailSend.py | horsewzh/src | train | 0 | |
40f8b7dc8fd44e4e7b8a9bc89b8325814ef42b70 | [
"splitresult = urlsplit(self.url)\nscheme, netloc, path, query, fragment = splitresult\nroom_id = path.strip('/')\nif not room_id.isnumeric():\n raise TypeError(f'url输入不正确,得到room_id为:{room_id}')\nself.live_room(room_id)\nctx.upload(item=live_daemon(export_func(lambda: self.get_live(room_id))))",
"api = 'https:... | <|body_start_0|>
splitresult = urlsplit(self.url)
scheme, netloc, path, query, fragment = splitresult
room_id = path.strip('/')
if not room_id.isnumeric():
raise TypeError(f'url输入不正确,得到room_id为:{room_id}')
self.live_room(room_id)
ctx.upload(item=live_daemon(ex... | BilibiliLive | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BilibiliLive:
def run(self):
"""__NEPTUNE_IS_MY_WAIFU__"""
<|body_0|>
def live_room(self, room_id):
"""直播间信息。"""
<|body_1|>
def get_live(self, room_id):
"""api: https://api.live.bilibili.com/xlive/web-room/v2/index/getRoomPlayInfo? Params: room_i... | stack_v2_sparse_classes_36k_train_023273 | 13,302 | permissive | [
{
"docstring": "__NEPTUNE_IS_MY_WAIFU__",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "直播间信息。",
"name": "live_room",
"signature": "def live_room(self, room_id)"
},
{
"docstring": "api: https://api.live.bilibili.com/xlive/web-room/v2/index/getRoomPlayInfo? Params... | 3 | stack_v2_sparse_classes_30k_train_007586 | Implement the Python class `BilibiliLive` described below.
Class description:
Implement the BilibiliLive class.
Method signatures and docstrings:
- def run(self): __NEPTUNE_IS_MY_WAIFU__
- def live_room(self, room_id): 直播间信息。
- def get_live(self, room_id): api: https://api.live.bilibili.com/xlive/web-room/v2/index/ge... | Implement the Python class `BilibiliLive` described below.
Class description:
Implement the BilibiliLive class.
Method signatures and docstrings:
- def run(self): __NEPTUNE_IS_MY_WAIFU__
- def live_room(self, room_id): 直播间信息。
- def get_live(self, room_id): api: https://api.live.bilibili.com/xlive/web-room/v2/index/ge... | 994933d91d85bb87ae8dfba1295f7a69f6d50097 | <|skeleton|>
class BilibiliLive:
def run(self):
"""__NEPTUNE_IS_MY_WAIFU__"""
<|body_0|>
def live_room(self, room_id):
"""直播间信息。"""
<|body_1|>
def get_live(self, room_id):
"""api: https://api.live.bilibili.com/xlive/web-room/v2/index/getRoomPlayInfo? Params: room_i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BilibiliLive:
def run(self):
"""__NEPTUNE_IS_MY_WAIFU__"""
splitresult = urlsplit(self.url)
scheme, netloc, path, query, fragment = splitresult
room_id = path.strip('/')
if not room_id.isnumeric():
raise TypeError(f'url输入不正确,得到room_id为:{room_id}')
se... | the_stack_v2_python_sparse | repo/bilibili.py | gasbarroni8/VideoCrawlerEngine | train | 0 | |
4465bedab331f4fc1378cddb2d4933ed199d76f4 | [
"super(ResBlock, self).__init__()\nself.block = nn.Sequential(conv3x3(channels, channels), nn.BatchNorm2d(channels), nn.PReLU(), conv3x3(channels, channels), nn.BatchNorm2d(channels))\nself.relu = nn.ReLU(inplace=True)",
"residual = x\nout = self.block(x)\nout += residual\nreturn out"
] | <|body_start_0|>
super(ResBlock, self).__init__()
self.block = nn.Sequential(conv3x3(channels, channels), nn.BatchNorm2d(channels), nn.PReLU(), conv3x3(channels, channels), nn.BatchNorm2d(channels))
self.relu = nn.ReLU(inplace=True)
<|end_body_0|>
<|body_start_1|>
residual = x
o... | Residual Block. The residual block consists of the following: - 3x3 Convolution with padding - 2D Batch Normalization - PReLU - 3x3 Convolution with padding - 2D Batch Normalization - ReLU | ResBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResBlock:
"""Residual Block. The residual block consists of the following: - 3x3 Convolution with padding - 2D Batch Normalization - PReLU - 3x3 Convolution with padding - 2D Batch Normalization - ReLU"""
def __init__(self, channels):
"""Initialize a Residual Block."""
<|body... | stack_v2_sparse_classes_36k_train_023274 | 22,492 | no_license | [
{
"docstring": "Initialize a Residual Block.",
"name": "__init__",
"signature": "def __init__(self, channels)"
},
{
"docstring": "Forward propagation.",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010605 | Implement the Python class `ResBlock` described below.
Class description:
Residual Block. The residual block consists of the following: - 3x3 Convolution with padding - 2D Batch Normalization - PReLU - 3x3 Convolution with padding - 2D Batch Normalization - ReLU
Method signatures and docstrings:
- def __init__(self, ... | Implement the Python class `ResBlock` described below.
Class description:
Residual Block. The residual block consists of the following: - 3x3 Convolution with padding - 2D Batch Normalization - PReLU - 3x3 Convolution with padding - 2D Batch Normalization - ReLU
Method signatures and docstrings:
- def __init__(self, ... | 70d344d80425e7bbcc7984737dbe50a6638293c9 | <|skeleton|>
class ResBlock:
"""Residual Block. The residual block consists of the following: - 3x3 Convolution with padding - 2D Batch Normalization - PReLU - 3x3 Convolution with padding - 2D Batch Normalization - ReLU"""
def __init__(self, channels):
"""Initialize a Residual Block."""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResBlock:
"""Residual Block. The residual block consists of the following: - 3x3 Convolution with padding - 2D Batch Normalization - PReLU - 3x3 Convolution with padding - 2D Batch Normalization - ReLU"""
def __init__(self, channels):
"""Initialize a Residual Block."""
super(ResBlock, sel... | the_stack_v2_python_sparse | TeleGAN/model.py | ails-lab/teleGAN | train | 1 |
8152f09c997f91ef365c48efc0d060f3ac71fec5 | [
"self.size = size\nself._array = []\nself._sum = 0",
"self._sum += val\nself._array.append(val)\nif len(self._array) > self.size:\n self._sum -= self._sum.pop(0)\nreturn self._sum / len(self._array)"
] | <|body_start_0|>
self.size = size
self._array = []
self._sum = 0
<|end_body_0|>
<|body_start_1|>
self._sum += val
self._array.append(val)
if len(self._array) > self.size:
self._sum -= self._sum.pop(0)
return self._sum / len(self._array)
<|end_body_1|>... | MovingAverage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.size = size
self._array ... | stack_v2_sparse_classes_36k_train_023275 | 1,425 | no_license | [
{
"docstring": "Initialize your data structure here. :type size: int",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": ":type val: int :rtype: float",
"name": "next",
"signature": "def next(self, val)"
}
] | 2 | null | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float
<|skeleton|>
class MovingAverage:
... | 96836da905526b47f0cdee8c0bb4790c4cdd6c79 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
self.size = size
self._array = []
self._sum = 0
def next(self, val):
""":type val: int :rtype: float"""
self._sum += val
self._array.append(val)
... | the_stack_v2_python_sparse | Array_String/346.Moving_Average_from_Data_Stream.py | grg909/LCtrip | train | 2 | |
be19e5d1064215aac455524301e620f168c0261a | [
"edts_subtype = vals['edts_subtype'] if 'edts_subtype' in vals else False\nprefix = self._get_sequence_prefix(vals['code'], edts_subtype, refund)\nseq_name = refund and vals['code'] + _(': Refund') or vals['code']\nseq = {'name': _('%s Sequence') % seq_name, 'implementation': 'no_gap', 'prefix': prefix, 'padding': ... | <|body_start_0|>
edts_subtype = vals['edts_subtype'] if 'edts_subtype' in vals else False
prefix = self._get_sequence_prefix(vals['code'], edts_subtype, refund)
seq_name = refund and vals['code'] + _(': Refund') or vals['code']
seq = {'name': _('%s Sequence') % seq_name, 'implementation'... | AccountJournalInherit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountJournalInherit:
def _create_sequence(self, vals, refund=False):
"""Overriden method to pass edts_subtype value to set default desired EDTS prefix"""
<|body_0|>
def _get_sequence_prefix(self, code, edts_subtype=False, refund=False):
"""Overriden method to set d... | stack_v2_sparse_classes_36k_train_023276 | 11,015 | no_license | [
{
"docstring": "Overriden method to pass edts_subtype value to set default desired EDTS prefix",
"name": "_create_sequence",
"signature": "def _create_sequence(self, vals, refund=False)"
},
{
"docstring": "Overriden method to set desired EDTS prefix",
"name": "_get_sequence_prefix",
"sig... | 2 | null | Implement the Python class `AccountJournalInherit` described below.
Class description:
Implement the AccountJournalInherit class.
Method signatures and docstrings:
- def _create_sequence(self, vals, refund=False): Overriden method to pass edts_subtype value to set default desired EDTS prefix
- def _get_sequence_prefi... | Implement the Python class `AccountJournalInherit` described below.
Class description:
Implement the AccountJournalInherit class.
Method signatures and docstrings:
- def _create_sequence(self, vals, refund=False): Overriden method to pass edts_subtype value to set default desired EDTS prefix
- def _get_sequence_prefi... | ebf8f4f7452190c986fbc9c225b8660fe0bd4bd4 | <|skeleton|>
class AccountJournalInherit:
def _create_sequence(self, vals, refund=False):
"""Overriden method to pass edts_subtype value to set default desired EDTS prefix"""
<|body_0|>
def _get_sequence_prefix(self, code, edts_subtype=False, refund=False):
"""Overriden method to set d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccountJournalInherit:
def _create_sequence(self, vals, refund=False):
"""Overriden method to pass edts_subtype value to set default desired EDTS prefix"""
edts_subtype = vals['edts_subtype'] if 'edts_subtype' in vals else False
prefix = self._get_sequence_prefix(vals['code'], edts_sub... | the_stack_v2_python_sparse | edts/models/account.py | hassanfadl/vendor_portal_app | train | 0 | |
15a6fb3d487d1de8eeacf6b37a3dba6b462ac162 | [
"self.subclass = subclass\nself.shape = shape\nself.order = order\nself.dtype = dtype\nself.allow_mmap = allow_mmap",
"buffersize = max(16 * 1024 ** 2 // array.itemsize, 1)\nif array.dtype.hasobject:\n pickle.dump(array, pickler.file_handle, protocol=2)\nelse:\n for chunk in pickler.np.nditer(array, flags=[... | <|body_start_0|>
self.subclass = subclass
self.shape = shape
self.order = order
self.dtype = dtype
self.allow_mmap = allow_mmap
<|end_body_0|>
<|body_start_1|>
buffersize = max(16 * 1024 ** 2 // array.itemsize, 1)
if array.dtype.hasobject:
pickle.dump... | An object to be persisted instead of numpy arrays. This object is used to hack into the pickle machinery and read numpy array data from our custom persistence format. More precisely, this object is used for: * carrying the information of the persisted array: subclass, shape, order, dtype. Those ndarray metadata are use... | NumpyArrayWrapper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumpyArrayWrapper:
"""An object to be persisted instead of numpy arrays. This object is used to hack into the pickle machinery and read numpy array data from our custom persistence format. More precisely, this object is used for: * carrying the information of the persisted array: subclass, shape,... | stack_v2_sparse_classes_36k_train_023277 | 23,222 | permissive | [
{
"docstring": "Constructor. Store the useful information for later.",
"name": "__init__",
"signature": "def __init__(self, subclass, shape, order, dtype, allow_mmap=False)"
},
{
"docstring": "Write array bytes to pickler file handle. This function is an adaptation of the numpy write_array funct... | 5 | null | Implement the Python class `NumpyArrayWrapper` described below.
Class description:
An object to be persisted instead of numpy arrays. This object is used to hack into the pickle machinery and read numpy array data from our custom persistence format. More precisely, this object is used for: * carrying the information o... | Implement the Python class `NumpyArrayWrapper` described below.
Class description:
An object to be persisted instead of numpy arrays. This object is used to hack into the pickle machinery and read numpy array data from our custom persistence format. More precisely, this object is used for: * carrying the information o... | f5042e35b945aded77b23470ead62d7eacefde92 | <|skeleton|>
class NumpyArrayWrapper:
"""An object to be persisted instead of numpy arrays. This object is used to hack into the pickle machinery and read numpy array data from our custom persistence format. More precisely, this object is used for: * carrying the information of the persisted array: subclass, shape,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumpyArrayWrapper:
"""An object to be persisted instead of numpy arrays. This object is used to hack into the pickle machinery and read numpy array data from our custom persistence format. More precisely, this object is used for: * carrying the information of the persisted array: subclass, shape, order, dtype... | the_stack_v2_python_sparse | contrib/python/scikit-learn/py2/sklearn/externals/joblib/numpy_pickle.py | catboost/catboost | train | 8,012 |
cdd14029693a27413334c24ab83d6362f3a2dbbe | [
"pars = inspect.signature(AnGaFIS_Seg_Estimator.__init__)\nfor par in pars.parameters.keys():\n if par != 'self':\n setattr(self, par, eval(par))",
"pars = inspect.signature(AnGaFIS_Seg_Estimator.__init__)\ntry:\n ret = segment_enhance(image, **{par: eval('self.{}'.format(par), {'self': self}) for pa... | <|body_start_0|>
pars = inspect.signature(AnGaFIS_Seg_Estimator.__init__)
for par in pars.parameters.keys():
if par != 'self':
setattr(self, par, eval(par))
<|end_body_0|>
<|body_start_1|>
pars = inspect.signature(AnGaFIS_Seg_Estimator.__init__)
try:
... | AnGaFIS_Seg_Estimator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnGaFIS_Seg_Estimator:
def __init__(self, brightness: float=0.35, leftCut: float=0.25, rightCut: float=0.5, histSmooth: int=25, reparSmooth: int=10, minVariation: float=0.01, cropSimpleMarg: int=5, scanAreaAmount: float=0.1, gradientFilterWidth: float=0.25, gaussianFilterSide: int=5, binarizatio... | stack_v2_sparse_classes_36k_train_023278 | 7,349 | permissive | [
{
"docstring": "Initializes and stores all the algorithm's parameters",
"name": "__init__",
"signature": "def __init__(self, brightness: float=0.35, leftCut: float=0.25, rightCut: float=0.5, histSmooth: int=25, reparSmooth: int=10, minVariation: float=0.01, cropSimpleMarg: int=5, scanAreaAmount: float=0... | 2 | stack_v2_sparse_classes_30k_train_003480 | Implement the Python class `AnGaFIS_Seg_Estimator` described below.
Class description:
Implement the AnGaFIS_Seg_Estimator class.
Method signatures and docstrings:
- def __init__(self, brightness: float=0.35, leftCut: float=0.25, rightCut: float=0.5, histSmooth: int=25, reparSmooth: int=10, minVariation: float=0.01, ... | Implement the Python class `AnGaFIS_Seg_Estimator` described below.
Class description:
Implement the AnGaFIS_Seg_Estimator class.
Method signatures and docstrings:
- def __init__(self, brightness: float=0.35, leftCut: float=0.25, rightCut: float=0.5, histSmooth: int=25, reparSmooth: int=10, minVariation: float=0.01, ... | 9a24b43a2170234e5059a54ed20329e036260b0a | <|skeleton|>
class AnGaFIS_Seg_Estimator:
def __init__(self, brightness: float=0.35, leftCut: float=0.25, rightCut: float=0.5, histSmooth: int=25, reparSmooth: int=10, minVariation: float=0.01, cropSimpleMarg: int=5, scanAreaAmount: float=0.1, gradientFilterWidth: float=0.25, gaussianFilterSide: int=5, binarizatio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnGaFIS_Seg_Estimator:
def __init__(self, brightness: float=0.35, leftCut: float=0.25, rightCut: float=0.5, histSmooth: int=25, reparSmooth: int=10, minVariation: float=0.01, cropSimpleMarg: int=5, scanAreaAmount: float=0.1, gradientFilterWidth: float=0.25, gaussianFilterSide: int=5, binarizationLevel: float=... | the_stack_v2_python_sparse | pynger/fingerprint/tuning_segmentation.py | Manjushanair/pynger | train | 0 | |
43de5891bb8509bb22797882e7503f861d645224 | [
"self.preferences.clear()\nfor name, member in tagged_members(self, 'pref').items():\n val = getattr(self, name)\n self.preferences[name] = member_to_pref(self, member, val)",
"task = cls()\nupdate_members_from_preferences(task, config)\nreturn task"
] | <|body_start_0|>
self.preferences.clear()
for name, member in tagged_members(self, 'pref').items():
val = getattr(self, name)
self.preferences[name] = member_to_pref(self, member, val)
<|end_body_0|>
<|body_start_1|>
task = cls()
update_members_from_preferences(t... | Task with no child task, written in pure Python. This class is mainly used to avoid having a linear ancestry relationship between SimpleTask and ComplexTask. | SimpleTask | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleTask:
"""Task with no child task, written in pure Python. This class is mainly used to avoid having a linear ancestry relationship between SimpleTask and ComplexTask."""
def register_preferences(self):
"""Register the task preferences into the preferences system."""
<|b... | stack_v2_sparse_classes_36k_train_023279 | 44,199 | permissive | [
{
"docstring": "Register the task preferences into the preferences system.",
"name": "register_preferences",
"signature": "def register_preferences(self)"
},
{
"docstring": "Create a new instance using the provided infos for initialisation. Parameters ---------- config : dict(str) Dictionary hol... | 2 | null | Implement the Python class `SimpleTask` described below.
Class description:
Task with no child task, written in pure Python. This class is mainly used to avoid having a linear ancestry relationship between SimpleTask and ComplexTask.
Method signatures and docstrings:
- def register_preferences(self): Register the tas... | Implement the Python class `SimpleTask` described below.
Class description:
Task with no child task, written in pure Python. This class is mainly used to avoid having a linear ancestry relationship between SimpleTask and ComplexTask.
Method signatures and docstrings:
- def register_preferences(self): Register the tas... | bb003a0ec74b622e1fb0e1dbfdd052f43531bfbd | <|skeleton|>
class SimpleTask:
"""Task with no child task, written in pure Python. This class is mainly used to avoid having a linear ancestry relationship between SimpleTask and ComplexTask."""
def register_preferences(self):
"""Register the task preferences into the preferences system."""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleTask:
"""Task with no child task, written in pure Python. This class is mainly used to avoid having a linear ancestry relationship between SimpleTask and ComplexTask."""
def register_preferences(self):
"""Register the task preferences into the preferences system."""
self.preferences... | the_stack_v2_python_sparse | exopy/tasks/tasks/base_tasks.py | Exopy/exopy | train | 17 |
4a3512564d2c6686a7305dcf26fcaa55d3d6e208 | [
"req = self.create_api(get_agent, CoopSts=1, RecordIndex=0, RecordSize=9999)\nagentlist = req.json()['Data']['RecordList']\nself.agentid = None\nfor i in range(len(agentlist)):\n if agentname == agentlist[i]['LaborName']:\n self.agentid = agentlist[i]['SpId']\nreturn self.agentid",
"print(entname)\nreq ... | <|body_start_0|>
req = self.create_api(get_agent, CoopSts=1, RecordIndex=0, RecordSize=9999)
agentlist = req.json()['Data']['RecordList']
self.agentid = None
for i in range(len(agentlist)):
if agentname == agentlist[i]['LaborName']:
self.agentid = agentlist[i]... | AdvanceManage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdvanceManage:
def get_agent(self, agentname):
"""获取来源id :param agentname: 来源名称 :return: self.agentid 来源id"""
<|body_0|>
def get_ent(self, entname):
"""获取标准企业id :param entname: 标准企业名称 :return: self.entid 标准企业id"""
<|body_1|>
def advance_import(self, entn... | stack_v2_sparse_classes_36k_train_023280 | 6,131 | no_license | [
{
"docstring": "获取来源id :param agentname: 来源名称 :return: self.agentid 来源id",
"name": "get_agent",
"signature": "def get_agent(self, agentname)"
},
{
"docstring": "获取标准企业id :param entname: 标准企业名称 :return: self.entid 标准企业id",
"name": "get_ent",
"signature": "def get_ent(self, entname)"
},
... | 5 | stack_v2_sparse_classes_30k_train_003163 | Implement the Python class `AdvanceManage` described below.
Class description:
Implement the AdvanceManage class.
Method signatures and docstrings:
- def get_agent(self, agentname): 获取来源id :param agentname: 来源名称 :return: self.agentid 来源id
- def get_ent(self, entname): 获取标准企业id :param entname: 标准企业名称 :return: self.ent... | Implement the Python class `AdvanceManage` described below.
Class description:
Implement the AdvanceManage class.
Method signatures and docstrings:
- def get_agent(self, agentname): 获取来源id :param agentname: 来源名称 :return: self.agentid 来源id
- def get_ent(self, entname): 获取标准企业id :param entname: 标准企业名称 :return: self.ent... | 7240500e63599033d904ac60b788ce4e8eec8746 | <|skeleton|>
class AdvanceManage:
def get_agent(self, agentname):
"""获取来源id :param agentname: 来源名称 :return: self.agentid 来源id"""
<|body_0|>
def get_ent(self, entname):
"""获取标准企业id :param entname: 标准企业名称 :return: self.entid 标准企业id"""
<|body_1|>
def advance_import(self, entn... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdvanceManage:
def get_agent(self, agentname):
"""获取来源id :param agentname: 来源名称 :return: self.agentid 来源id"""
req = self.create_api(get_agent, CoopSts=1, RecordIndex=0, RecordSize=9999)
agentlist = req.json()['Data']['RecordList']
self.agentid = None
for i in range(len(... | the_stack_v2_python_sparse | common/lib/comm_func/advance_management.py | yhtnumberone/automatic_test | train | 0 | |
3a53a7e9c91af1b4a8f4a7a57d8d4911018b71a9 | [
"permitted_blocklist_entries = self.permissioned_queryset(CommandPublishingBlocklist, SYSTEM_READ)\nresponse = {'command_publishing_blocklist': CommandPublishingBlocklistSchema(many=True).dump(permitted_blocklist_entries).data}\nself.write(response)",
"commands = self.schema_validated_body(CommandPublishingBlockl... | <|body_start_0|>
permitted_blocklist_entries = self.permissioned_queryset(CommandPublishingBlocklist, SYSTEM_READ)
response = {'command_publishing_blocklist': CommandPublishingBlocklistSchema(many=True).dump(permitted_blocklist_entries).data}
self.write(response)
<|end_body_0|>
<|body_start_1|>... | CommandPublishingBlocklistAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommandPublishingBlocklistAPI:
def get(self):
"""--- summary: Retrieve list of commands in publishing block list responses: 200: description: list of commands in publishing block list schema: $ref: '#/definitions/CommandPublishingBlocklistListSchema' 400: $ref: '#/definitions/400Error' 5... | stack_v2_sparse_classes_36k_train_023281 | 5,880 | permissive | [
{
"docstring": "--- summary: Retrieve list of commands in publishing block list responses: 200: description: list of commands in publishing block list schema: $ref: '#/definitions/CommandPublishingBlocklistListSchema' 400: $ref: '#/definitions/400Error' 50x: $ref: '#/definitions/50xError' tags: - Command Block ... | 2 | null | Implement the Python class `CommandPublishingBlocklistAPI` described below.
Class description:
Implement the CommandPublishingBlocklistAPI class.
Method signatures and docstrings:
- def get(self): --- summary: Retrieve list of commands in publishing block list responses: 200: description: list of commands in publishi... | Implement the Python class `CommandPublishingBlocklistAPI` described below.
Class description:
Implement the CommandPublishingBlocklistAPI class.
Method signatures and docstrings:
- def get(self): --- summary: Retrieve list of commands in publishing block list responses: 200: description: list of commands in publishi... | a5fd2dcc2444409e243d3fdaa43d86695e5cb142 | <|skeleton|>
class CommandPublishingBlocklistAPI:
def get(self):
"""--- summary: Retrieve list of commands in publishing block list responses: 200: description: list of commands in publishing block list schema: $ref: '#/definitions/CommandPublishingBlocklistListSchema' 400: $ref: '#/definitions/400Error' 5... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommandPublishingBlocklistAPI:
def get(self):
"""--- summary: Retrieve list of commands in publishing block list responses: 200: description: list of commands in publishing block list schema: $ref: '#/definitions/CommandPublishingBlocklistListSchema' 400: $ref: '#/definitions/400Error' 50x: $ref: '#/d... | the_stack_v2_python_sparse | src/app/beer_garden/api/http/handlers/v1/command_publishing_blocklist.py | beer-garden/beer-garden | train | 254 | |
6c905590b4d8407d9a4e1e333c1457eb2a8676df | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn RetentionEvent()",
"from ..entity import Entity\nfrom ..identity_set import IdentitySet\nfrom .event_propagation_result import EventPropagationResult\nfrom .event_query import EventQuery\nfrom .retention_event_status import RetentionEv... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return RetentionEvent()
<|end_body_0|>
<|body_start_1|>
from ..entity import Entity
from ..identity_set import IdentitySet
from .event_propagation_result import EventPropagationResult
... | RetentionEvent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RetentionEvent:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RetentionEvent:
"""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... | stack_v2_sparse_classes_36k_train_023282 | 6,338 | 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: RetentionEvent",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_valu... | 3 | stack_v2_sparse_classes_30k_train_005215 | Implement the Python class `RetentionEvent` described below.
Class description:
Implement the RetentionEvent class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RetentionEvent: Creates a new instance of the appropriate class based on discriminator va... | Implement the Python class `RetentionEvent` described below.
Class description:
Implement the RetentionEvent class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RetentionEvent: Creates a new instance of the appropriate class based on discriminator va... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class RetentionEvent:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RetentionEvent:
"""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... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RetentionEvent:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RetentionEvent:
"""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: RetentionE... | the_stack_v2_python_sparse | msgraph/generated/models/security/retention_event.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
150dab3c950dc6f2fd49ce9aabb95bacb86d938e | [
"pts1 = veh1.get_bounding_points()\npts2 = veh2.get_bounding_points()\nedges = []\nedges.append(np.subtract(pts1[1], pts1[0]))\nedges.append(np.subtract(pts1[2], pts1[1]))\nedges.append(np.subtract(pts2[1], pts2[0]))\nedges.append(np.subtract(pts2[2], pts2[1]))\nfor edge in edges:\n if self.separating(pts1, pts2... | <|body_start_0|>
pts1 = veh1.get_bounding_points()
pts2 = veh2.get_bounding_points()
edges = []
edges.append(np.subtract(pts1[1], pts1[0]))
edges.append(np.subtract(pts1[2], pts1[1]))
edges.append(np.subtract(pts2[1], pts2[0]))
edges.append(np.subtract(pts2[2], pt... | Surface is the parent class for Road an Intersection, and provides the implementation for vehicle collisions | Surface | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Surface:
"""Surface is the parent class for Road an Intersection, and provides the implementation for vehicle collisions"""
def have_collided(self, veh1, veh2):
"""Returns true if the two vehicles are collided, and false otherwise :param veh1: :param veh2: :return:"""
<|body_... | stack_v2_sparse_classes_36k_train_023283 | 1,856 | permissive | [
{
"docstring": "Returns true if the two vehicles are collided, and false otherwise :param veh1: :param veh2: :return:",
"name": "have_collided",
"signature": "def have_collided(self, veh1, veh2)"
},
{
"docstring": "Returns true if the projection of pts1 onto vector does not overlap with the proj... | 2 | null | Implement the Python class `Surface` described below.
Class description:
Surface is the parent class for Road an Intersection, and provides the implementation for vehicle collisions
Method signatures and docstrings:
- def have_collided(self, veh1, veh2): Returns true if the two vehicles are collided, and false otherw... | Implement the Python class `Surface` described below.
Class description:
Surface is the parent class for Road an Intersection, and provides the implementation for vehicle collisions
Method signatures and docstrings:
- def have_collided(self, veh1, veh2): Returns true if the two vehicles are collided, and false otherw... | 69ba3bfddc8b8772b80a99fb7bb6b4367b417e5d | <|skeleton|>
class Surface:
"""Surface is the parent class for Road an Intersection, and provides the implementation for vehicle collisions"""
def have_collided(self, veh1, veh2):
"""Returns true if the two vehicles are collided, and false otherwise :param veh1: :param veh2: :return:"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Surface:
"""Surface is the parent class for Road an Intersection, and provides the implementation for vehicle collisions"""
def have_collided(self, veh1, veh2):
"""Returns true if the two vehicles are collided, and false otherwise :param veh1: :param veh2: :return:"""
pts1 = veh1.get_boun... | the_stack_v2_python_sparse | src/Surface.py | DLance96/TrafficSim-Simulator | train | 0 |
35d798bd86f77e55c5f43e51d83a9da2de041b8a | [
"super().__init__()\nif not inputs:\n inputs = []\nif len(inputs) > 20:\n raise ValueError('TRNSYS allows only up to 20 different INPUTS to be removed')\nself.inputs = inputs\nself.doc = 'CHECK Statement'",
"head = 'NOCHECK {}\\n'.format(len(self.inputs))\ncore = '\\t'.join(['{}, {}'.format(input.model.unit... | <|body_start_0|>
super().__init__()
if not inputs:
inputs = []
if len(inputs) > 20:
raise ValueError('TRNSYS allows only up to 20 different INPUTS to be removed')
self.inputs = inputs
self.doc = 'CHECK Statement'
<|end_body_0|>
<|body_start_1|>
he... | NoCheck Statement. TRNSYS allows up to 20 different INPUTS to be removed from the list of INPUTS to be checked for convergence (see Section 1.9). | NoCheck | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoCheck:
"""NoCheck Statement. TRNSYS allows up to 20 different INPUTS to be removed from the list of INPUTS to be checked for convergence (see Section 1.9)."""
def __init__(self, inputs=None):
"""Initialize object. Args: inputs (list of Input): The list of Inputs."""
<|body_... | stack_v2_sparse_classes_36k_train_023284 | 1,070 | permissive | [
{
"docstring": "Initialize object. Args: inputs (list of Input): The list of Inputs.",
"name": "__init__",
"signature": "def __init__(self, inputs=None)"
},
{
"docstring": "Return deck representation of self.",
"name": "_to_deck",
"signature": "def _to_deck(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001472 | Implement the Python class `NoCheck` described below.
Class description:
NoCheck Statement. TRNSYS allows up to 20 different INPUTS to be removed from the list of INPUTS to be checked for convergence (see Section 1.9).
Method signatures and docstrings:
- def __init__(self, inputs=None): Initialize object. Args: input... | Implement the Python class `NoCheck` described below.
Class description:
NoCheck Statement. TRNSYS allows up to 20 different INPUTS to be removed from the list of INPUTS to be checked for convergence (see Section 1.9).
Method signatures and docstrings:
- def __init__(self, inputs=None): Initialize object. Args: input... | f2deb5eb340a2814722eead5f8b6278a945c730d | <|skeleton|>
class NoCheck:
"""NoCheck Statement. TRNSYS allows up to 20 different INPUTS to be removed from the list of INPUTS to be checked for convergence (see Section 1.9)."""
def __init__(self, inputs=None):
"""Initialize object. Args: inputs (list of Input): The list of Inputs."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NoCheck:
"""NoCheck Statement. TRNSYS allows up to 20 different INPUTS to be removed from the list of INPUTS to be checked for convergence (see Section 1.9)."""
def __init__(self, inputs=None):
"""Initialize object. Args: inputs (list of Input): The list of Inputs."""
super().__init__()
... | the_stack_v2_python_sparse | trnsystor/statement/nocheck.py | sturmianseq/trnsystor | train | 0 |
4ca725b2ceddda6c2718ea2e1b12f4a7cd92f451 | [
"import itertools\nparts = []\nsets = []\nfor c in S:\n seen = False\n merge_start = -1\n for i in range(0, len(sets)):\n if c in sets[i]:\n seen = True\n merge_start = i\n break\n parts.append([c])\n sets.append({c})\n if seen:\n parts_tmp = []\n ... | <|body_start_0|>
import itertools
parts = []
sets = []
for c in S:
seen = False
merge_start = -1
for i in range(0, len(sets)):
if c in sets[i]:
seen = True
merge_start = i
brea... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def partitionLabels(self, S):
"""Linear scan the input string, store the previous partitions into a list. If the current char belongs to any of the previous partitions, merge them with the current char into one partition. :type S: str :rtype: List[int]"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_023285 | 2,059 | no_license | [
{
"docstring": "Linear scan the input string, store the previous partitions into a list. If the current char belongs to any of the previous partitions, merge them with the current char into one partition. :type S: str :rtype: List[int]",
"name": "partitionLabels",
"signature": "def partitionLabels(self,... | 2 | stack_v2_sparse_classes_30k_train_002214 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def partitionLabels(self, S): Linear scan the input string, store the previous partitions into a list. If the current char belongs to any of the previous partitions, merge them w... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def partitionLabels(self, S): Linear scan the input string, store the previous partitions into a list. If the current char belongs to any of the previous partitions, merge them w... | 143aa25f92f3827aa379f29c67a9b7ec3757fef9 | <|skeleton|>
class Solution:
def partitionLabels(self, S):
"""Linear scan the input string, store the previous partitions into a list. If the current char belongs to any of the previous partitions, merge them with the current char into one partition. :type S: str :rtype: List[int]"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def partitionLabels(self, S):
"""Linear scan the input string, store the previous partitions into a list. If the current char belongs to any of the previous partitions, merge them with the current char into one partition. :type S: str :rtype: List[int]"""
import itertools
par... | the_stack_v2_python_sparse | py/leetcode_py/763.py | imsure/tech-interview-prep | train | 0 | |
1a1a1961fd6805a8d208a63e22b447c6fa2da7da | [
"self._sizes = sizes\nself._opts = opts\nself._X = X\nself._Y = Y\nself.w_list = []\nself.b_list = []\ninput_size = X.shape[1]\nfor size in self._sizes + [Y.shape[1]]:\n max_range = 4 * math.sqrt(6.0 / (input_size + size))\n self.w_list.append(np.random.uniform(-max_range, max_range, [input_size, size]).astyp... | <|body_start_0|>
self._sizes = sizes
self._opts = opts
self._X = X
self._Y = Y
self.w_list = []
self.b_list = []
input_size = X.shape[1]
for size in self._sizes + [Y.shape[1]]:
max_range = 4 * math.sqrt(6.0 / (input_size + size))
se... | Docstring for NN. | NN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NN:
"""Docstring for NN."""
def __init__(self, sizes, opts, X, Y):
"""TODO: to be defined1. :sizes: TODO :opts: TODO :X: TODO"""
<|body_0|>
def load_from_dbn(self, dbn):
"""TODO: Docstring for load_from_dbn. :dbn: TODO :returns: TODO"""
<|body_1|>
de... | stack_v2_sparse_classes_36k_train_023286 | 4,462 | permissive | [
{
"docstring": "TODO: to be defined1. :sizes: TODO :opts: TODO :X: TODO",
"name": "__init__",
"signature": "def __init__(self, sizes, opts, X, Y)"
},
{
"docstring": "TODO: Docstring for load_from_dbn. :dbn: TODO :returns: TODO",
"name": "load_from_dbn",
"signature": "def load_from_dbn(se... | 4 | stack_v2_sparse_classes_30k_train_013230 | Implement the Python class `NN` described below.
Class description:
Docstring for NN.
Method signatures and docstrings:
- def __init__(self, sizes, opts, X, Y): TODO: to be defined1. :sizes: TODO :opts: TODO :X: TODO
- def load_from_dbn(self, dbn): TODO: Docstring for load_from_dbn. :dbn: TODO :returns: TODO
- def tr... | Implement the Python class `NN` described below.
Class description:
Docstring for NN.
Method signatures and docstrings:
- def __init__(self, sizes, opts, X, Y): TODO: to be defined1. :sizes: TODO :opts: TODO :X: TODO
- def load_from_dbn(self, dbn): TODO: Docstring for load_from_dbn. :dbn: TODO :returns: TODO
- def tr... | 289f230a609554db32552670c300f992a3fe068f | <|skeleton|>
class NN:
"""Docstring for NN."""
def __init__(self, sizes, opts, X, Y):
"""TODO: to be defined1. :sizes: TODO :opts: TODO :X: TODO"""
<|body_0|>
def load_from_dbn(self, dbn):
"""TODO: Docstring for load_from_dbn. :dbn: TODO :returns: TODO"""
<|body_1|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NN:
"""Docstring for NN."""
def __init__(self, sizes, opts, X, Y):
"""TODO: to be defined1. :sizes: TODO :opts: TODO :X: TODO"""
self._sizes = sizes
self._opts = opts
self._X = X
self._Y = Y
self.w_list = []
self.b_list = []
input_size = X.s... | the_stack_v2_python_sparse | bagging-svm/nn_tf.py | ishidaira233/TX-Credit-Assessement | train | 0 |
fcbddb3511bf200f06e703bc14f8642c592e3ca2 | [
"timestamps = sorted({state.timestamp for state in chain(measured_states, truth_states)})\nospa_distances = []\nfor timestamp in timestamps:\n meas_points = [state for state in measured_states if state.timestamp == timestamp]\n truth_points = [state for state in truth_states if state.timestamp == timestamp]\n... | <|body_start_0|>
timestamps = sorted({state.timestamp for state in chain(measured_states, truth_states)})
ospa_distances = []
for timestamp in timestamps:
meas_points = [state for state in measured_states if state.timestamp == timestamp]
truth_points = [state for state in... | Computes the Optimal SubPattern Assignment (OSPA) distance [1] for two sets of :class:`~.Track` objects. The OSPA distance is measured between two point patterns. The OSPA metric is calculated at each time step in which a :class:`~.Track` object is present Reference: [1] A Consistent Metric for Performance Evaluation o... | OSPAMetric | [
"LicenseRef-scancode-proprietary-license",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"Python-2.0",
"LicenseRef-scancode-secret-labs-2011"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OSPAMetric:
"""Computes the Optimal SubPattern Assignment (OSPA) distance [1] for two sets of :class:`~.Track` objects. The OSPA distance is measured between two point patterns. The OSPA metric is calculated at each time step in which a :class:`~.Track` object is present Reference: [1] A Consiste... | stack_v2_sparse_classes_36k_train_023287 | 19,882 | permissive | [
{
"docstring": "Compute the OSPA metric at every timestep from a list of measured states and truth states Parameters ---------- measured_states: list of :class:`~.State` Created by a filter truth_states: list of :class:`~.State` Truth states to compare against Returns ------- TimeRangeMetric Covering the durati... | 2 | stack_v2_sparse_classes_30k_train_020233 | Implement the Python class `OSPAMetric` described below.
Class description:
Computes the Optimal SubPattern Assignment (OSPA) distance [1] for two sets of :class:`~.Track` objects. The OSPA distance is measured between two point patterns. The OSPA metric is calculated at each time step in which a :class:`~.Track` obje... | Implement the Python class `OSPAMetric` described below.
Class description:
Computes the Optimal SubPattern Assignment (OSPA) distance [1] for two sets of :class:`~.Track` objects. The OSPA distance is measured between two point patterns. The OSPA metric is calculated at each time step in which a :class:`~.Track` obje... | f24090cc919b3b590b84f965a3884ed1293d181d | <|skeleton|>
class OSPAMetric:
"""Computes the Optimal SubPattern Assignment (OSPA) distance [1] for two sets of :class:`~.Track` objects. The OSPA distance is measured between two point patterns. The OSPA metric is calculated at each time step in which a :class:`~.Track` object is present Reference: [1] A Consiste... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OSPAMetric:
"""Computes the Optimal SubPattern Assignment (OSPA) distance [1] for two sets of :class:`~.Track` objects. The OSPA distance is measured between two point patterns. The OSPA metric is calculated at each time step in which a :class:`~.Track` object is present Reference: [1] A Consistent Metric for... | the_stack_v2_python_sparse | stonesoup/metricgenerator/ospametric.py | dstl/Stone-Soup | train | 315 |
c9c7f22445ffae69a295439507e290923d1d11e2 | [
"self.capacity = capacity\nself.map = {}\nself.haven = 0\nself.old_index = None\nself.new_index = None",
"if key not in self.map:\n return -1\nnow_node = self.map[key]\nif now_node is self.new_index:\n return now_node.v\nfront = now_node.front\nnext1 = now_node.next\nfront.next = next1\nnext1.front = front\... | <|body_start_0|>
self.capacity = capacity
self.map = {}
self.haven = 0
self.old_index = None
self.new_index = None
<|end_body_0|>
<|body_start_1|>
if key not in self.map:
return -1
now_node = self.map[key]
if now_node is self.new_index:
... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
"""思入: 在字典中找到该元素,并调整双线链表中的次序 :type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
"""在字典中插入新的元素,并双线链表中的次序,可能删除最少使用的节点 :type key: int :... | stack_v2_sparse_classes_36k_train_023288 | 2,840 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": "思入: 在字典中找到该元素,并调整双线链表中的次序 :type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": "在字典中插入新的元素,并双线链表中的次序,可能删除最少使用的节点 :ty... | 3 | stack_v2_sparse_classes_30k_train_019152 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): 思入: 在字典中找到该元素,并调整双线链表中的次序 :type key: int :rtype: int
- def put(self, key, value): 在字典中插入新的元素,并双线链表中的次序,可能删... | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): 思入: 在字典中找到该元素,并调整双线链表中的次序 :type key: int :rtype: int
- def put(self, key, value): 在字典中插入新的元素,并双线链表中的次序,可能删... | d1ddcbabfa7cc4d4f41b46f21f3227984f57bc40 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
"""思入: 在字典中找到该元素,并调整双线链表中的次序 :type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
"""在字典中插入新的元素,并双线链表中的次序,可能删除最少使用的节点 :type key: int :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.map = {}
self.haven = 0
self.old_index = None
self.new_index = None
def get(self, key):
"""思入: 在字典中找到该元素,并调整双线链表中的次序 :type key: int :rtype: int"""
... | the_stack_v2_python_sparse | 哈希/146_lru_cache.py | whitefly/leetcode_python | train | 6 | |
32e94d41a79dfd8efdea0552edda2bebd0bb8f0f | [
"if self:\n iterator = iter(self.subtrees)\n try:\n iterator.next()\n except StopIteration:\n ret = True\n else:\n ret = False\nelse:\n ret = True\nreturn ret",
"if self:\n yield self.cargo\n for subtree in self.subtrees:\n for elem in subtree:\n yield e... | <|body_start_0|>
if self:
iterator = iter(self.subtrees)
try:
iterator.next()
except StopIteration:
ret = True
else:
ret = False
else:
ret = True
return ret
<|end_body_0|>
<|body_start_1|... | The mixin MTree class, containing generic tree methods. | MTree | [
"Python-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MTree:
"""The mixin MTree class, containing generic tree methods."""
def isAtom(self):
"""Return True if it has no subtrees, False otherwise."""
<|body_0|>
def __iter__(self):
"""The standard preorder traversal iterator."""
<|body_1|>
def postorder(s... | stack_v2_sparse_classes_36k_train_023289 | 7,189 | permissive | [
{
"docstring": "Return True if it has no subtrees, False otherwise.",
"name": "isAtom",
"signature": "def isAtom(self)"
},
{
"docstring": "The standard preorder traversal iterator.",
"name": "__iter__",
"signature": "def __iter__(self)"
},
{
"docstring": "Postorder traversal of a... | 6 | null | Implement the Python class `MTree` described below.
Class description:
The mixin MTree class, containing generic tree methods.
Method signatures and docstrings:
- def isAtom(self): Return True if it has no subtrees, False otherwise.
- def __iter__(self): The standard preorder traversal iterator.
- def postorder(self)... | Implement the Python class `MTree` described below.
Class description:
The mixin MTree class, containing generic tree methods.
Method signatures and docstrings:
- def isAtom(self): Return True if it has no subtrees, False otherwise.
- def __iter__(self): The standard preorder traversal iterator.
- def postorder(self)... | d097ca0ad6a6aee2180d32dce6a3322621f655fd | <|skeleton|>
class MTree:
"""The mixin MTree class, containing generic tree methods."""
def isAtom(self):
"""Return True if it has no subtrees, False otherwise."""
<|body_0|>
def __iter__(self):
"""The standard preorder traversal iterator."""
<|body_1|>
def postorder(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MTree:
"""The mixin MTree class, containing generic tree methods."""
def isAtom(self):
"""Return True if it has no subtrees, False otherwise."""
if self:
iterator = iter(self.subtrees)
try:
iterator.next()
except StopIteration:
... | the_stack_v2_python_sparse | recipes/Python/201423_Trees_and_more_trees_part_II/recipe-201423.py | betty29/code-1 | train | 0 |
0a5295cddbf0ad0211dd45d8ef0c23cbff53aef7 | [
"email = request.data.get('email')\nuser = get_user_model().objects.filter(email=email).first()\nrandom_number = random_token.generate_verification_token(10)\nif not user:\n msg = {'status': 'error', 'message': messages.MESSAGES['UNREGISTER_USER']}\n return Response(msg, status=status.HTTP_404_NOT_FOUND)\nuse... | <|body_start_0|>
email = request.data.get('email')
user = get_user_model().objects.filter(email=email).first()
random_number = random_token.generate_verification_token(10)
if not user:
msg = {'status': 'error', 'message': messages.MESSAGES['UNREGISTER_USER']}
retu... | Class representing the endpoints for user's password reset | UserPasswordReset | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserPasswordReset:
"""Class representing the endpoints for user's password reset"""
def post(self, request):
"""Post method to send out password reset email"""
<|body_0|>
def patch(self, request):
"""Patch method to reset password"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k_train_023290 | 6,510 | permissive | [
{
"docstring": "Post method to send out password reset email",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "Patch method to reset password",
"name": "patch",
"signature": "def patch(self, request)"
}
] | 2 | null | Implement the Python class `UserPasswordReset` described below.
Class description:
Class representing the endpoints for user's password reset
Method signatures and docstrings:
- def post(self, request): Post method to send out password reset email
- def patch(self, request): Patch method to reset password | Implement the Python class `UserPasswordReset` described below.
Class description:
Class representing the endpoints for user's password reset
Method signatures and docstrings:
- def post(self, request): Post method to send out password reset email
- def patch(self, request): Patch method to reset password
<|skeleton... | 24d70d61b3b723b1ed1bd7dc2bafa173b4dc21b3 | <|skeleton|>
class UserPasswordReset:
"""Class representing the endpoints for user's password reset"""
def post(self, request):
"""Post method to send out password reset email"""
<|body_0|>
def patch(self, request):
"""Patch method to reset password"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserPasswordReset:
"""Class representing the endpoints for user's password reset"""
def post(self, request):
"""Post method to send out password reset email"""
email = request.data.get('email')
user = get_user_model().objects.filter(email=email).first()
random_number = ran... | the_stack_v2_python_sparse | src/apps/user/api/views.py | veeqtor/API-Trisixty | train | 0 |
c3a569abc61fdf6861eb8aa14c4e93c191548e44 | [
"if nums == []:\n return 0\nj = 0\ncount = 1\nfor i in range(1, len(nums)):\n if nums[i] == nums[j] and count < 2:\n j += 1\n nums[j] = nums[i]\n count += 1\n elif nums[i] != nums[j]:\n j += 1\n nums[j] = nums[i]\n count = 1\nreturn j + 1",
"if nums == []:\n r... | <|body_start_0|>
if nums == []:
return 0
j = 0
count = 1
for i in range(1, len(nums)):
if nums[i] == nums[j] and count < 2:
j += 1
nums[j] = nums[i]
count += 1
elif nums[i] != nums[j]:
j +... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def removeDuplicates2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if nums == []:
return ... | stack_v2_sparse_classes_36k_train_023291 | 2,170 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "removeDuplicates",
"signature": "def removeDuplicates(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "removeDuplicates2",
"signature": "def removeDuplicates2(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicates(self, nums): :type nums: List[int] :rtype: int
- def removeDuplicates2(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicates(self, nums): :type nums: List[int] :rtype: int
- def removeDuplicates2(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def ... | c55b0cfd2967a2221c27ed738e8de15034775945 | <|skeleton|>
class Solution:
def removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def removeDuplicates2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
if nums == []:
return 0
j = 0
count = 1
for i in range(1, len(nums)):
if nums[i] == nums[j] and count < 2:
j += 1
nums[j] = nums[i... | the_stack_v2_python_sparse | PycharmProjects/leetcode/UsingArray/MoveElements/removeDuplicates80.py | crystal30/DataStructure | train | 0 | |
40156aeda5db65df5bac7d87240906e4c30c5f1b | [
"super().__init__(num_heads, block)\nself.num_sliding_window_blocks = num_sliding_window_blocks\nself.attention = attention",
"num_blocks = layout.shape[1]\nif num_blocks < self.num_sliding_window_blocks:\n raise ValueError(f'Number of sliding window blocks, {self.num_sliding_window_blocks}, must be smaller th... | <|body_start_0|>
super().__init__(num_heads, block)
self.num_sliding_window_blocks = num_sliding_window_blocks
self.attention = attention
<|end_body_0|>
<|body_start_1|>
num_blocks = layout.shape[1]
if num_blocks < self.num_sliding_window_blocks:
raise ValueError(f'N... | Configuration class to store `Local Sliding Window` sparsity configuration - a purely-local sliding window attention. This class extends parent class of `SparsityConfig` and customizes it for `Local` sparsity. | LocalSlidingWindowSparsityConfig | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocalSlidingWindowSparsityConfig:
"""Configuration class to store `Local Sliding Window` sparsity configuration - a purely-local sliding window attention. This class extends parent class of `SparsityConfig` and customizes it for `Local` sparsity."""
def __init__(self, num_heads, block=16, nu... | stack_v2_sparse_classes_36k_train_023292 | 42,463 | permissive | [
{
"docstring": "Initialize the Local Sliding Window Sparsity Pattern Config. For usage example please see, TODO DeepSpeed Sparse Transformer Tutorial Arguments: num_heads: required: an integer determining number of attention heads of the layer. block: optional: an integer determining the block size. Current imp... | 3 | null | Implement the Python class `LocalSlidingWindowSparsityConfig` described below.
Class description:
Configuration class to store `Local Sliding Window` sparsity configuration - a purely-local sliding window attention. This class extends parent class of `SparsityConfig` and customizes it for `Local` sparsity.
Method sig... | Implement the Python class `LocalSlidingWindowSparsityConfig` described below.
Class description:
Configuration class to store `Local Sliding Window` sparsity configuration - a purely-local sliding window attention. This class extends parent class of `SparsityConfig` and customizes it for `Local` sparsity.
Method sig... | 55d9964c59c0c6e23158b5789a5c36c28939a7b0 | <|skeleton|>
class LocalSlidingWindowSparsityConfig:
"""Configuration class to store `Local Sliding Window` sparsity configuration - a purely-local sliding window attention. This class extends parent class of `SparsityConfig` and customizes it for `Local` sparsity."""
def __init__(self, num_heads, block=16, nu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LocalSlidingWindowSparsityConfig:
"""Configuration class to store `Local Sliding Window` sparsity configuration - a purely-local sliding window attention. This class extends parent class of `SparsityConfig` and customizes it for `Local` sparsity."""
def __init__(self, num_heads, block=16, num_sliding_win... | the_stack_v2_python_sparse | deepspeed/ops/sparse_attention/sparsity_config.py | microsoft/DeepSpeed | train | 27,557 |
2e7f37a250c9756984f1672ea51b26f386c7e40d | [
"super(InRange, self).__init__(*args, **kw)\nself.from_value = from_value\nself.to_value = to_value",
"result = is_in_range(value, self.from_value, self.to_value)\nmessage = self._build_message(value, self.from_value, self.to_value, result)\nreturn ValidationResult(value, result, message)"
] | <|body_start_0|>
super(InRange, self).__init__(*args, **kw)
self.from_value = from_value
self.to_value = to_value
<|end_body_0|>
<|body_start_1|>
result = is_in_range(value, self.from_value, self.to_value)
message = self._build_message(value, self.from_value, self.to_value, resu... | Validator is checking that value is in specified range. .. code-block:: python validation_expression = InRange(0, 20) validation_expression.validate(10) # returns ValidationResult object | InRange | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InRange:
"""Validator is checking that value is in specified range. .. code-block:: python validation_expression = InRange(0, 20) validation_expression.validate(10) # returns ValidationResult object"""
def __init__(self, from_value, to_value, *args, **kw):
""":param number from_value... | stack_v2_sparse_classes_36k_train_023293 | 16,665 | no_license | [
{
"docstring": ":param number from_value: Beginning of range. :param number to_value: Ending of range.",
"name": "__init__",
"signature": "def __init__(self, from_value, to_value, *args, **kw)"
},
{
"docstring": "Method checks if specified value meet requirements.",
"name": "validate",
"... | 2 | null | Implement the Python class `InRange` described below.
Class description:
Validator is checking that value is in specified range. .. code-block:: python validation_expression = InRange(0, 20) validation_expression.validate(10) # returns ValidationResult object
Method signatures and docstrings:
- def __init__(self, fro... | Implement the Python class `InRange` described below.
Class description:
Validator is checking that value is in specified range. .. code-block:: python validation_expression = InRange(0, 20) validation_expression.validate(10) # returns ValidationResult object
Method signatures and docstrings:
- def __init__(self, fro... | 75487a40ac2cc5f24f70d011ad6cd3924908f783 | <|skeleton|>
class InRange:
"""Validator is checking that value is in specified range. .. code-block:: python validation_expression = InRange(0, 20) validation_expression.validate(10) # returns ValidationResult object"""
def __init__(self, from_value, to_value, *args, **kw):
""":param number from_value... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InRange:
"""Validator is checking that value is in specified range. .. code-block:: python validation_expression = InRange(0, 20) validation_expression.validate(10) # returns ValidationResult object"""
def __init__(self, from_value, to_value, *args, **kw):
""":param number from_value: Beginning o... | the_stack_v2_python_sparse | bts_infomodel/ute_common_validator/validator.py | jufei/BtsShell | train | 0 |
10a82fe1eccc22aa6fbc0a41f406b7f6576b43d8 | [
"self._destination_dir = destination_dir\nself._bucketName = bucket_name\nself._s3client = boto3.client('s3', config=Config(signature_version=UNSIGNED))",
"dest_path = os.path.join(self._destination_dir, object_name)\nos.makedirs(Path(dest_path).parent.absolute(), exist_ok=True)\nlogger.info('Now downloading {} f... | <|body_start_0|>
self._destination_dir = destination_dir
self._bucketName = bucket_name
self._s3client = boto3.client('s3', config=Config(signature_version=UNSIGNED))
<|end_body_0|>
<|body_start_1|>
dest_path = os.path.join(self._destination_dir, object_name)
os.makedirs(Path(de... | Class used to download bucket files from an s3 bucket. | BucketFileDownloader | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BucketFileDownloader:
"""Class used to download bucket files from an s3 bucket."""
def __init__(self, destination_dir, bucket_name):
"""Init bucket file downloader. Args: destination_dir: Path to the folder where to save the element to bucket_name: Name of the s3 bucket where to find... | stack_v2_sparse_classes_36k_train_023294 | 5,962 | permissive | [
{
"docstring": "Init bucket file downloader. Args: destination_dir: Path to the folder where to save the element to bucket_name: Name of the s3 bucket where to find the elements to download",
"name": "__init__",
"signature": "def __init__(self, destination_dir, bucket_name)"
},
{
"docstring": "D... | 2 | stack_v2_sparse_classes_30k_train_004240 | Implement the Python class `BucketFileDownloader` described below.
Class description:
Class used to download bucket files from an s3 bucket.
Method signatures and docstrings:
- def __init__(self, destination_dir, bucket_name): Init bucket file downloader. Args: destination_dir: Path to the folder where to save the el... | Implement the Python class `BucketFileDownloader` described below.
Class description:
Class used to download bucket files from an s3 bucket.
Method signatures and docstrings:
- def __init__(self, destination_dir, bucket_name): Init bucket file downloader. Args: destination_dir: Path to the folder where to save the el... | ddcfeb6262124e793fcee385405365417e57f91f | <|skeleton|>
class BucketFileDownloader:
"""Class used to download bucket files from an s3 bucket."""
def __init__(self, destination_dir, bucket_name):
"""Init bucket file downloader. Args: destination_dir: Path to the folder where to save the element to bucket_name: Name of the s3 bucket where to find... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BucketFileDownloader:
"""Class used to download bucket files from an s3 bucket."""
def __init__(self, destination_dir, bucket_name):
"""Init bucket file downloader. Args: destination_dir: Path to the folder where to save the element to bucket_name: Name of the s3 bucket where to find the elements... | the_stack_v2_python_sparse | src/Sorel20mDataset/utils/download_utils.py | cmikke97/Automatic-Malware-Signature-Generation | train | 11 |
d7382b7f90092b43f6de06c437ca10a095f4b5ea | [
"super(AbSeqModel, self).__init__()\nself.conv1 = nn.Conv1d(NUM_FEATURES, NUM_FEATURES, 3, padding=1)\nself.elu = nn.ELU()\nself.dropout1 = nn.Dropout(0.15)\nself.bidir_lstm = nn.LSTM(NUM_FEATURES, 256, bidirectional=True)\nself.dropout2 = nn.Dropout(0.3)\nself.fc = nn.Conv1d(512, 1, 1)\nfor m in self.modules():\n ... | <|body_start_0|>
super(AbSeqModel, self).__init__()
self.conv1 = nn.Conv1d(NUM_FEATURES, NUM_FEATURES, 3, padding=1)
self.elu = nn.ELU()
self.dropout1 = nn.Dropout(0.15)
self.bidir_lstm = nn.LSTM(NUM_FEATURES, 256, bidirectional=True)
self.dropout2 = nn.Dropout(0.3)
... | AbSeqModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbSeqModel:
def __init__(self):
"""Parapred's building blocks."""
<|body_0|>
def weights_init(self, m):
"""Parameter initialisation for Parapred architecture. Xavier and orthogonal are used, depending on layer. :param m: :return:"""
<|body_1|>
def forwar... | stack_v2_sparse_classes_36k_train_023295 | 2,664 | no_license | [
{
"docstring": "Parapred's building blocks.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Parameter initialisation for Parapred architecture. Xavier and orthogonal are used, depending on layer. :param m: :return:",
"name": "weights_init",
"signature": "def we... | 3 | stack_v2_sparse_classes_30k_train_008494 | Implement the Python class `AbSeqModel` described below.
Class description:
Implement the AbSeqModel class.
Method signatures and docstrings:
- def __init__(self): Parapred's building blocks.
- def weights_init(self, m): Parameter initialisation for Parapred architecture. Xavier and orthogonal are used, depending on ... | Implement the Python class `AbSeqModel` described below.
Class description:
Implement the AbSeqModel class.
Method signatures and docstrings:
- def __init__(self): Parapred's building blocks.
- def weights_init(self, m): Parameter initialisation for Parapred architecture. Xavier and orthogonal are used, depending on ... | 7cc895017b942c0ef5a600f170f7a0e574377132 | <|skeleton|>
class AbSeqModel:
def __init__(self):
"""Parapred's building blocks."""
<|body_0|>
def weights_init(self, m):
"""Parameter initialisation for Parapred architecture. Xavier and orthogonal are used, depending on layer. :param m: :return:"""
<|body_1|>
def forwar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AbSeqModel:
def __init__(self):
"""Parapred's building blocks."""
super(AbSeqModel, self).__init__()
self.conv1 = nn.Conv1d(NUM_FEATURES, NUM_FEATURES, 3, padding=1)
self.elu = nn.ELU()
self.dropout1 = nn.Dropout(0.15)
self.bidir_lstm = nn.LSTM(NUM_FEATURES, 256... | the_stack_v2_python_sparse | paratope/model.py | chasingtim/attentive-parapred | train | 0 | |
a267803a63bbba81c5d15d60d0fb094e95b2cb21 | [
"self._blinkt = blinkt\nself._attr_name = f'{name}_{index}'\nself._index = index\nself._attr_is_on = False\nself._attr_brightness = 255\nself._attr_hs_color = [0, 0]",
"if ATTR_HS_COLOR in kwargs:\n self._attr_hs_color = kwargs[ATTR_HS_COLOR]\nif ATTR_BRIGHTNESS in kwargs:\n self._attr_brightness = kwargs[A... | <|body_start_0|>
self._blinkt = blinkt
self._attr_name = f'{name}_{index}'
self._index = index
self._attr_is_on = False
self._attr_brightness = 255
self._attr_hs_color = [0, 0]
<|end_body_0|>
<|body_start_1|>
if ATTR_HS_COLOR in kwargs:
self._attr_hs_... | Representation of a Blinkt! Light. | BlinktLight | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlinktLight:
"""Representation of a Blinkt! Light."""
def __init__(self, blinkt, name, index):
"""Initialize a Blinkt Light. Default brightness and white color."""
<|body_0|>
def turn_on(self, **kwargs):
"""Instruct the light to turn on and set correct brightness... | stack_v2_sparse_classes_36k_train_023296 | 2,384 | permissive | [
{
"docstring": "Initialize a Blinkt Light. Default brightness and white color.",
"name": "__init__",
"signature": "def __init__(self, blinkt, name, index)"
},
{
"docstring": "Instruct the light to turn on and set correct brightness & color.",
"name": "turn_on",
"signature": "def turn_on(... | 3 | stack_v2_sparse_classes_30k_train_017217 | Implement the Python class `BlinktLight` described below.
Class description:
Representation of a Blinkt! Light.
Method signatures and docstrings:
- def __init__(self, blinkt, name, index): Initialize a Blinkt Light. Default brightness and white color.
- def turn_on(self, **kwargs): Instruct the light to turn on and s... | Implement the Python class `BlinktLight` described below.
Class description:
Representation of a Blinkt! Light.
Method signatures and docstrings:
- def __init__(self, blinkt, name, index): Initialize a Blinkt Light. Default brightness and white color.
- def turn_on(self, **kwargs): Instruct the light to turn on and s... | 8de7966104911bca6f855a1755a6d71a07afb9de | <|skeleton|>
class BlinktLight:
"""Representation of a Blinkt! Light."""
def __init__(self, blinkt, name, index):
"""Initialize a Blinkt Light. Default brightness and white color."""
<|body_0|>
def turn_on(self, **kwargs):
"""Instruct the light to turn on and set correct brightness... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BlinktLight:
"""Representation of a Blinkt! Light."""
def __init__(self, blinkt, name, index):
"""Initialize a Blinkt Light. Default brightness and white color."""
self._blinkt = blinkt
self._attr_name = f'{name}_{index}'
self._index = index
self._attr_is_on = Fals... | the_stack_v2_python_sparse | homeassistant/components/blinkt/light.py | AlexxIT/home-assistant | train | 9 |
68ca44d1c3c9e46d5d1fa0305c4d7e7dba66c155 | [
"self.abs_coeff = abs_coeff\nlambda_max = Material.hc / band_gap\nself.extinct_coeff = lambda_max * abs_coeff / (10000000.0 * 4.0 * math.pi)\nself.band_gap = band_gap",
"if self.band_gap > Material.hc / photon.wavelength:\n return False\nalpha = 10000000.0 * 4.0 * math.pi * self.extinct_coeff / photon.waveleng... | <|body_start_0|>
self.abs_coeff = abs_coeff
lambda_max = Material.hc / band_gap
self.extinct_coeff = lambda_max * abs_coeff / (10000000.0 * 4.0 * math.pi)
self.band_gap = band_gap
<|end_body_0|>
<|body_start_1|>
if self.band_gap > Material.hc / photon.wavelength:
ret... | Represents the material that a tower is coated with. Is responsible for determining whether a photon is absorbed with the proper probability | Material | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Material:
"""Represents the material that a tower is coated with. Is responsible for determining whether a photon is absorbed with the proper probability"""
def __init__(self, abs_coeff, band_gap):
"""Create a material with the given absorption coefficient and band gap @type abs_coef... | stack_v2_sparse_classes_36k_train_023297 | 1,841 | no_license | [
{
"docstring": "Create a material with the given absorption coefficient and band gap @type abs_coeff: floating point number @param abs_coeff: The absorption coefficient of the material @type band_gap: floating point number @param band_gap: The bandgap of the material",
"name": "__init__",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_021591 | Implement the Python class `Material` described below.
Class description:
Represents the material that a tower is coated with. Is responsible for determining whether a photon is absorbed with the proper probability
Method signatures and docstrings:
- def __init__(self, abs_coeff, band_gap): Create a material with the... | Implement the Python class `Material` described below.
Class description:
Represents the material that a tower is coated with. Is responsible for determining whether a photon is absorbed with the proper probability
Method signatures and docstrings:
- def __init__(self, abs_coeff, band_gap): Create a material with the... | 824591a0d6fd2f4a74ea30d5e73bf1c3331188bc | <|skeleton|>
class Material:
"""Represents the material that a tower is coated with. Is responsible for determining whether a photon is absorbed with the proper probability"""
def __init__(self, abs_coeff, band_gap):
"""Create a material with the given absorption coefficient and band gap @type abs_coef... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Material:
"""Represents the material that a tower is coated with. Is responsible for determining whether a photon is absorbed with the proper probability"""
def __init__(self, abs_coeff, band_gap):
"""Create a material with the given absorption coefficient and band gap @type abs_coeff: floating p... | the_stack_v2_python_sparse | Tower/Material.py | agiron123/3DPhotovoltaics | train | 0 |
607153bdb517be58178440b07e85fecf7e3c9e91 | [
"if not self.supports_type_lookup():\n raise Unimplemented()\ntry:\n from . import sessions\nexcept ImportError:\n raise\ntry:\n session = sessions.TypeLookupSession(runtime=self._runtime)\nexcept AttributeError:\n raise\nreturn session",
"pass\nif not self.supports_type_admin():\n raise Unimple... | <|body_start_0|>
if not self.supports_type_lookup():
raise Unimplemented()
try:
from . import sessions
except ImportError:
raise
try:
session = sessions.TypeLookupSession(runtime=self._runtime)
except AttributeError:
rai... | This manager provides access to the available sessions of the type service. The TypeLookupSession is used for looking up Types and the TypeAdminSession is used for managing and registering new Types. | TypeManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TypeManager:
"""This manager provides access to the available sessions of the type service. The TypeLookupSession is used for looking up Types and the TypeAdminSession is used for managing and registering new Types."""
def get_type_lookup_session(self):
"""Gets the OsidSession associ... | stack_v2_sparse_classes_36k_train_023298 | 3,429 | permissive | [
{
"docstring": "Gets the OsidSession associated with the type lookup service. return: (osid.type.TypeLookupSession) - a TypeLookupSession raise: OperationFailed - unable to complete request raise: Unimplemented - supports_type_lookup() is false compliance: optional - This method must be implemented if supports_... | 2 | stack_v2_sparse_classes_30k_train_016612 | Implement the Python class `TypeManager` described below.
Class description:
This manager provides access to the available sessions of the type service. The TypeLookupSession is used for looking up Types and the TypeAdminSession is used for managing and registering new Types.
Method signatures and docstrings:
- def g... | Implement the Python class `TypeManager` described below.
Class description:
This manager provides access to the available sessions of the type service. The TypeLookupSession is used for looking up Types and the TypeAdminSession is used for managing and registering new Types.
Method signatures and docstrings:
- def g... | 445f968a175d61c8d92c0f617a3c17dc1dc7c584 | <|skeleton|>
class TypeManager:
"""This manager provides access to the available sessions of the type service. The TypeLookupSession is used for looking up Types and the TypeAdminSession is used for managing and registering new Types."""
def get_type_lookup_session(self):
"""Gets the OsidSession associ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TypeManager:
"""This manager provides access to the available sessions of the type service. The TypeLookupSession is used for looking up Types and the TypeAdminSession is used for managing and registering new Types."""
def get_type_lookup_session(self):
"""Gets the OsidSession associated with the... | the_stack_v2_python_sparse | dlkit/handcar/type/managers.py | mitsei/dlkit | train | 2 |
9386662bd14635c1430e84fa95349c87a7e023bc | [
"if dtype not in DATA_TYPES:\n msg = \"unknown data type '{}'\"\n raise err.InvalidTemplateError(msg.format(dtype))\nself.column_id = column_id\nself.name = name\nself.dtype = dtype\nself.path = path\nself.required = required if required is not None else True",
"if self.dtype == PARA_INT:\n return int(va... | <|body_start_0|>
if dtype not in DATA_TYPES:
msg = "unknown data type '{}'"
raise err.InvalidTemplateError(msg.format(dtype))
self.column_id = column_id
self.name = name
self.dtype = dtype
self.path = path
self.required = required if required is no... | Column in the result schema of a benchmark. Each column has a unique identifier and unique name. The identifier is used as column name in the database schema. The name is for display purposes in a user interface. The optional path element is used to extract the column value from nested result files. | ResultColumn | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResultColumn:
"""Column in the result schema of a benchmark. Each column has a unique identifier and unique name. The identifier is used as column name in the database schema. The name is for display purposes in a user interface. The optional path element is used to extract the column value from ... | stack_v2_sparse_classes_36k_train_023299 | 11,903 | permissive | [
{
"docstring": "Initialize the unique column identifier, name, and the data type. If the value of dtype is not in the list of supported data types an error is raised. The optional path element references the column value in nested result files. If no path is given the column identifier is used instead. Paramete... | 5 | stack_v2_sparse_classes_30k_test_000936 | Implement the Python class `ResultColumn` described below.
Class description:
Column in the result schema of a benchmark. Each column has a unique identifier and unique name. The identifier is used as column name in the database schema. The name is for display purposes in a user interface. The optional path element is... | Implement the Python class `ResultColumn` described below.
Class description:
Column in the result schema of a benchmark. Each column has a unique identifier and unique name. The identifier is used as column name in the database schema. The name is for display purposes in a user interface. The optional path element is... | 7116b7060aa68ab36bf08e6393be166dc5db955f | <|skeleton|>
class ResultColumn:
"""Column in the result schema of a benchmark. Each column has a unique identifier and unique name. The identifier is used as column name in the database schema. The name is for display purposes in a user interface. The optional path element is used to extract the column value from ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResultColumn:
"""Column in the result schema of a benchmark. Each column has a unique identifier and unique name. The identifier is used as column name in the database schema. The name is for display purposes in a user interface. The optional path element is used to extract the column value from nested result... | the_stack_v2_python_sparse | flowserv/model/template/schema.py | anrunw/flowserv-core-1 | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.