blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bea455fe7a70fbb28bed089de125be7eedbc3c20 | [
"self.__wrapped = wrapped\nself.__retry_if = retry_if\nself.__backoff = backoff\nif self.__backoff <= 0:\n raise ValueError('backoff must be positive')\nself.__multiplier = multiplier\nif self.__multiplier < 1:\n raise ValueError('multiplier must be at least one!')\nself.__max_tries = max_tries\nself.__max_ba... | <|body_start_0|>
self.__wrapped = wrapped
self.__retry_if = retry_if
self.__backoff = backoff
if self.__backoff <= 0:
raise ValueError('backoff must be positive')
self.__multiplier = multiplier
if self.__multiplier < 1:
raise ValueError('multiplier... | Handle transient errors, with configurable backoff. This class can wrap any object. The wrapped object will behave like the original one, except that if you call a function and it raises a retriable exception, we'll back off for a certain number of seconds and call the function again, until it succeeds or we get a non-... | RetryWrapper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RetryWrapper:
"""Handle transient errors, with configurable backoff. This class can wrap any object. The wrapped object will behave like the original one, except that if you call a function and it raises a retriable exception, we'll back off for a certain number of seconds and call the function a... | stack_v2_sparse_classes_75kplus_train_066500 | 4,804 | permissive | [
{
"docstring": "Wrap the given object. :param wrapped: the object to wrap :param retry_if: a method that takes an exception, and returns whether we should retry :type backoff: float :param backoff: the number of seconds to wait the first time we get a retriable error :type multiplier: float :param multiplier: i... | 3 | stack_v2_sparse_classes_30k_train_013941 | Implement the Python class `RetryWrapper` described below.
Class description:
Handle transient errors, with configurable backoff. This class can wrap any object. The wrapped object will behave like the original one, except that if you call a function and it raises a retriable exception, we'll back off for a certain nu... | Implement the Python class `RetryWrapper` described below.
Class description:
Handle transient errors, with configurable backoff. This class can wrap any object. The wrapped object will behave like the original one, except that if you call a function and it raises a retriable exception, we'll back off for a certain nu... | fe21995e0402878437a828c6a4244025eac8c43b | <|skeleton|>
class RetryWrapper:
"""Handle transient errors, with configurable backoff. This class can wrap any object. The wrapped object will behave like the original one, except that if you call a function and it raises a retriable exception, we'll back off for a certain number of seconds and call the function a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RetryWrapper:
"""Handle transient errors, with configurable backoff. This class can wrap any object. The wrapped object will behave like the original one, except that if you call a function and it raises a retriable exception, we'll back off for a certain number of seconds and call the function again, until i... | the_stack_v2_python_sparse | python_modules/libraries/dagster-aws/dagster_aws/utils/mrjob/retry.py | dagster-io/dagster | train | 8,565 |
ef651b320319ae1796350323b512628639ff77ae | [
"super().__init__()\nself.item = item\nself.inputs = []\nself.input_changed = self._get_input_changed_func(main_window)\nhbox = QHBoxLayout()\nself.setLayout(hbox)\nhbox.setSpacing(0)\nrows = 5\nfor i, arg_name in enumerate(item):\n if i % rows == 0:\n try:\n vbox.addStretch(10)\n except... | <|body_start_0|>
super().__init__()
self.item = item
self.inputs = []
self.input_changed = self._get_input_changed_func(main_window)
hbox = QHBoxLayout()
self.setLayout(hbox)
hbox.setSpacing(0)
rows = 5
for i, arg_name in enumerate(item):
... | Frame represents attributes of a single item. Contains form layouts - labels and inputs | AttributesFrame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttributesFrame:
"""Frame represents attributes of a single item. Contains form layouts - labels and inputs"""
def __init__(self, main_window, item):
"""main_window: MainWindow instance item: CalculableObject instance"""
<|body_0|>
def _get_input_changed_func(self, main_... | stack_v2_sparse_classes_75kplus_train_066501 | 1,723 | no_license | [
{
"docstring": "main_window: MainWindow instance item: CalculableObject instance",
"name": "__init__",
"signature": "def __init__(self, main_window, item)"
},
{
"docstring": "I don't want to keep reference to the MainWindow",
"name": "_get_input_changed_func",
"signature": "def _get_inpu... | 2 | stack_v2_sparse_classes_30k_train_011433 | Implement the Python class `AttributesFrame` described below.
Class description:
Frame represents attributes of a single item. Contains form layouts - labels and inputs
Method signatures and docstrings:
- def __init__(self, main_window, item): main_window: MainWindow instance item: CalculableObject instance
- def _ge... | Implement the Python class `AttributesFrame` described below.
Class description:
Frame represents attributes of a single item. Contains form layouts - labels and inputs
Method signatures and docstrings:
- def __init__(self, main_window, item): main_window: MainWindow instance item: CalculableObject instance
- def _ge... | 606e188e88ee3a2b2e1daee60c71948c678228e1 | <|skeleton|>
class AttributesFrame:
"""Frame represents attributes of a single item. Contains form layouts - labels and inputs"""
def __init__(self, main_window, item):
"""main_window: MainWindow instance item: CalculableObject instance"""
<|body_0|>
def _get_input_changed_func(self, main_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AttributesFrame:
"""Frame represents attributes of a single item. Contains form layouts - labels and inputs"""
def __init__(self, main_window, item):
"""main_window: MainWindow instance item: CalculableObject instance"""
super().__init__()
self.item = item
self.inputs = []... | the_stack_v2_python_sparse | Hospital-Helper-2-master/app/gui/attributes_frame.py | JoaoBueno/estudos-python | train | 2 |
6ddf1c9d92f4564a834801f60837679dfdfc4640 | [
"this_data = attr.asdict(self)\nother_data = attr.asdict(other)\nfor key, value in this_data.items():\n if isinstance(value, Sentinel):\n if key in other_data:\n setattr(self, key, other_data[key])",
"for key, value in self._default.items():\n if isinstance(getattr(self, key), Sentinel):\n... | <|body_start_0|>
this_data = attr.asdict(self)
other_data = attr.asdict(other)
for key, value in this_data.items():
if isinstance(value, Sentinel):
if key in other_data:
setattr(self, key, other_data[key])
<|end_body_0|>
<|body_start_1|>
f... | **中文文档** 一个特殊的用于指定配置的数据类型. 该基础类用于指定 Lambda Function, API Gateway Method 等配置. - 所有必要的属性都给予 ``REQUIRED`` 默认值 - 所有可选的属性都给予 ``NOTHING`` 默认值 - ``_default`` 中只定义那些 一定会有用到, 但是值不一定的值 | BaseConfig | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseConfig:
"""**中文文档** 一个特殊的用于指定配置的数据类型. 该基础类用于指定 Lambda Function, API Gateway Method 等配置. - 所有必要的属性都给予 ``REQUIRED`` 默认值 - 所有可选的属性都给予 ``NOTHING`` 默认值 - ``_default`` 中只定义那些 一定会有用到, 但是值不一定的值"""
def absorb(self, other):
"""inherit values from other config if the current one is a Sentin... | stack_v2_sparse_classes_75kplus_train_066502 | 21,127 | permissive | [
{
"docstring": "inherit values from other config if the current one is a Sentinel. :type other: FunctionConfig **中文文档** 从另一个 实例 当中吸取那些被数值化的数据.",
"name": "absorb",
"signature": "def absorb(self, other)"
},
{
"docstring": "Fill default value into current instance, if the field already has a value,... | 2 | stack_v2_sparse_classes_30k_train_050338 | Implement the Python class `BaseConfig` described below.
Class description:
**中文文档** 一个特殊的用于指定配置的数据类型. 该基础类用于指定 Lambda Function, API Gateway Method 等配置. - 所有必要的属性都给予 ``REQUIRED`` 默认值 - 所有可选的属性都给予 ``NOTHING`` 默认值 - ``_default`` 中只定义那些 一定会有用到, 但是值不一定的值
Method signatures and docstrings:
- def absorb(self, other): inheri... | Implement the Python class `BaseConfig` described below.
Class description:
**中文文档** 一个特殊的用于指定配置的数据类型. 该基础类用于指定 Lambda Function, API Gateway Method 等配置. - 所有必要的属性都给予 ``REQUIRED`` 默认值 - 所有可选的属性都给予 ``NOTHING`` 默认值 - ``_default`` 中只定义那些 一定会有用到, 但是值不一定的值
Method signatures and docstrings:
- def absorb(self, other): inheri... | 0bd6b47e88e65ad885cf702f956350b57080c41a | <|skeleton|>
class BaseConfig:
"""**中文文档** 一个特殊的用于指定配置的数据类型. 该基础类用于指定 Lambda Function, API Gateway Method 等配置. - 所有必要的属性都给予 ``REQUIRED`` 默认值 - 所有可选的属性都给予 ``NOTHING`` 默认值 - ``_default`` 中只定义那些 一定会有用到, 但是值不一定的值"""
def absorb(self, other):
"""inherit values from other config if the current one is a Sentin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseConfig:
"""**中文文档** 一个特殊的用于指定配置的数据类型. 该基础类用于指定 Lambda Function, API Gateway Method 等配置. - 所有必要的属性都给予 ``REQUIRED`` 默认值 - 所有可选的属性都给予 ``NOTHING`` 默认值 - ``_default`` 中只定义那些 一定会有用到, 但是值不一定的值"""
def absorb(self, other):
"""inherit values from other config if the current one is a Sentinel. :type oth... | the_stack_v2_python_sparse | rabbit_docker_cicd_pipeline/config.py | MacHu-GWU/rabbit_docker_cicd_pipeline-project | train | 0 |
9a1724ed1fba89e9562266e03a08ff0c7b704a49 | [
"self.number_of_archival_runs = number_of_archival_runs\nself.number_of_protection_runs = number_of_protection_runs\nself.number_of_replication_runs = number_of_replication_runs\nself.number_of_successful_archival_runs = number_of_successful_archival_runs\nself.number_of_successful_protection_runs = number_of_succe... | <|body_start_0|>
self.number_of_archival_runs = number_of_archival_runs
self.number_of_protection_runs = number_of_protection_runs
self.number_of_replication_runs = number_of_replication_runs
self.number_of_successful_archival_runs = number_of_successful_archival_runs
self.number... | Implementation of the 'ProtectionRunsSummary' model. ProtectionRunsSummary is the summary of the all the Protection Runs for the Protection Jobs using the Specified Protection Policy. Attributes: number_of_archival_runs (long|int): Specifies the total number of Archival Runs using the current Protection Policy. number_... | ProtectionRunsSummary | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProtectionRunsSummary:
"""Implementation of the 'ProtectionRunsSummary' model. ProtectionRunsSummary is the summary of the all the Protection Runs for the Protection Jobs using the Specified Protection Policy. Attributes: number_of_archival_runs (long|int): Specifies the total number of Archival ... | stack_v2_sparse_classes_75kplus_train_066503 | 4,115 | permissive | [
{
"docstring": "Constructor for the ProtectionRunsSummary class",
"name": "__init__",
"signature": "def __init__(self, number_of_archival_runs=None, number_of_protection_runs=None, number_of_replication_runs=None, number_of_successful_archival_runs=None, number_of_successful_protection_runs=None, number... | 2 | stack_v2_sparse_classes_30k_train_027529 | Implement the Python class `ProtectionRunsSummary` described below.
Class description:
Implementation of the 'ProtectionRunsSummary' model. ProtectionRunsSummary is the summary of the all the Protection Runs for the Protection Jobs using the Specified Protection Policy. Attributes: number_of_archival_runs (long|int): ... | Implement the Python class `ProtectionRunsSummary` described below.
Class description:
Implementation of the 'ProtectionRunsSummary' model. ProtectionRunsSummary is the summary of the all the Protection Runs for the Protection Jobs using the Specified Protection Policy. Attributes: number_of_archival_runs (long|int): ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ProtectionRunsSummary:
"""Implementation of the 'ProtectionRunsSummary' model. ProtectionRunsSummary is the summary of the all the Protection Runs for the Protection Jobs using the Specified Protection Policy. Attributes: number_of_archival_runs (long|int): Specifies the total number of Archival ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProtectionRunsSummary:
"""Implementation of the 'ProtectionRunsSummary' model. ProtectionRunsSummary is the summary of the all the Protection Runs for the Protection Jobs using the Specified Protection Policy. Attributes: number_of_archival_runs (long|int): Specifies the total number of Archival Runs using th... | the_stack_v2_python_sparse | cohesity_management_sdk/models/protection_runs_summary.py | cohesity/management-sdk-python | train | 24 |
2687f3033fe05cf24e0ee3c3b53fad5e401b1bd7 | [
"self.cmd = cmd\nself.args = args\nself.kwargs = kwargs",
"if type(self.cmd) is str:\n exec(self.cmd)\nelse:\n self.cmd(*self.args, **self.kwargs)"
] | <|body_start_0|>
self.cmd = cmd
self.args = args
self.kwargs = kwargs
<|end_body_0|>
<|body_start_1|>
if type(self.cmd) is str:
exec(self.cmd)
else:
self.cmd(*self.args, **self.kwargs)
<|end_body_1|>
| commande | f_cmd | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class f_cmd:
"""commande"""
def __init__(self, cmd, *args, **kwargs):
"""Initialisation cmd : code à executer (soit texte, soit fonction) + en option arguments (pour fonction)"""
<|body_0|>
def run(self):
"""Execute la commande"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_066504 | 7,191 | permissive | [
{
"docstring": "Initialisation cmd : code à executer (soit texte, soit fonction) + en option arguments (pour fonction)",
"name": "__init__",
"signature": "def __init__(self, cmd, *args, **kwargs)"
},
{
"docstring": "Execute la commande",
"name": "run",
"signature": "def run(self)"
}
] | 2 | null | Implement the Python class `f_cmd` described below.
Class description:
commande
Method signatures and docstrings:
- def __init__(self, cmd, *args, **kwargs): Initialisation cmd : code à executer (soit texte, soit fonction) + en option arguments (pour fonction)
- def run(self): Execute la commande | Implement the Python class `f_cmd` described below.
Class description:
commande
Method signatures and docstrings:
- def __init__(self, cmd, *args, **kwargs): Initialisation cmd : code à executer (soit texte, soit fonction) + en option arguments (pour fonction)
- def run(self): Execute la commande
<|skeleton|>
class ... | 46c4f9369964b2f9108f2776bf74f24ccdc71e7f | <|skeleton|>
class f_cmd:
"""commande"""
def __init__(self, cmd, *args, **kwargs):
"""Initialisation cmd : code à executer (soit texte, soit fonction) + en option arguments (pour fonction)"""
<|body_0|>
def run(self):
"""Execute la commande"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class f_cmd:
"""commande"""
def __init__(self, cmd, *args, **kwargs):
"""Initialisation cmd : code à executer (soit texte, soit fonction) + en option arguments (pour fonction)"""
self.cmd = cmd
self.args = args
self.kwargs = kwargs
def run(self):
"""Execute la comma... | the_stack_v2_python_sparse | build/lib/FGPIO/f_menu.py | FredThx/FGPIO | train | 0 |
22da4b02a550dfe725e5d5dfe30029c09932cfd4 | [
"self.data = dat\nself.cov = cov\nself.z = z\nself.prior = prior\nzc = z.cpu().numpy()\nzc = np.insert(zc, 0, 0)\nself.dz = torch.tensor(zc[1:] - zc[:-1], device=ddevice)\nself.LikeFunc = Likelihood(dat, cov)\nself.zdim = z.shape[0]",
"mod = modelo(theta, self.z, self.dz, self.zdim)\nself.u = -self.LikeFunc.get_l... | <|body_start_0|>
self.data = dat
self.cov = cov
self.z = z
self.prior = prior
zc = z.cpu().numpy()
zc = np.insert(zc, 0, 0)
self.dz = torch.tensor(zc[1:] - zc[:-1], device=ddevice)
self.LikeFunc = Likelihood(dat, cov)
self.zdim = z.shape[0]
<|end_b... | Potential | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Potential:
def __init__(self, dat, cov, z, prior):
"""Computes potential energy and its gradient. dat: array (ndata), data. sigma: array (ndata, ndata), data error z: array (ndata), redshift. prior: object, prior."""
<|body_0|>
def value(self, theta):
"""Returns pote... | stack_v2_sparse_classes_75kplus_train_066505 | 13,126 | no_license | [
{
"docstring": "Computes potential energy and its gradient. dat: array (ndata), data. sigma: array (ndata, ndata), data error z: array (ndata), redshift. prior: object, prior.",
"name": "__init__",
"signature": "def __init__(self, dat, cov, z, prior)"
},
{
"docstring": "Returns potential log val... | 3 | stack_v2_sparse_classes_30k_train_031228 | Implement the Python class `Potential` described below.
Class description:
Implement the Potential class.
Method signatures and docstrings:
- def __init__(self, dat, cov, z, prior): Computes potential energy and its gradient. dat: array (ndata), data. sigma: array (ndata, ndata), data error z: array (ndata), redshift... | Implement the Python class `Potential` described below.
Class description:
Implement the Potential class.
Method signatures and docstrings:
- def __init__(self, dat, cov, z, prior): Computes potential energy and its gradient. dat: array (ndata), data. sigma: array (ndata, ndata), data error z: array (ndata), redshift... | 8789f692d81c5435a5888b6b151ccf6187d5a064 | <|skeleton|>
class Potential:
def __init__(self, dat, cov, z, prior):
"""Computes potential energy and its gradient. dat: array (ndata), data. sigma: array (ndata, ndata), data error z: array (ndata), redshift. prior: object, prior."""
<|body_0|>
def value(self, theta):
"""Returns pote... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Potential:
def __init__(self, dat, cov, z, prior):
"""Computes potential energy and its gradient. dat: array (ndata), data. sigma: array (ndata, ndata), data error z: array (ndata), redshift. prior: object, prior."""
self.data = dat
self.cov = cov
self.z = z
self.prior ... | the_stack_v2_python_sparse | p18/mcmc.py | fluowhy/MCMC-methods | train | 1 | |
22e54d8ad209ada7bc64e0edeb0f52f93e49e31d | [
"json_dict = json.loads(request.body.decode())\nsku_id = json_dict.get('sku_id')\ntry:\n SKU.objects.get(id=sku_id)\nexcept SKU.DoesNotExist:\n return http.HttpResponseForbidden('商品sku_id错误')\nredis_conn = get_redis_connection('history')\nkey = 'history_%s' % request.user.id\npl = redis_conn.pipeline()\npl.lr... | <|body_start_0|>
json_dict = json.loads(request.body.decode())
sku_id = json_dict.get('sku_id')
try:
SKU.objects.get(id=sku_id)
except SKU.DoesNotExist:
return http.HttpResponseForbidden('商品sku_id错误')
redis_conn = get_redis_connection('history')
ke... | 用户历史浏览记录 | HistoryView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HistoryView:
"""用户历史浏览记录"""
def post(self, request):
"""保存用户浏览记录"""
<|body_0|>
def get(self, request):
"""获取用户浏览记录"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
json_dict = json.loads(request.body.decode())
sku_id = json_dict.get('sku_... | stack_v2_sparse_classes_75kplus_train_066506 | 16,550 | no_license | [
{
"docstring": "保存用户浏览记录",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "获取用户浏览记录",
"name": "get",
"signature": "def get(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_048705 | Implement the Python class `HistoryView` described below.
Class description:
用户历史浏览记录
Method signatures and docstrings:
- def post(self, request): 保存用户浏览记录
- def get(self, request): 获取用户浏览记录 | Implement the Python class `HistoryView` described below.
Class description:
用户历史浏览记录
Method signatures and docstrings:
- def post(self, request): 保存用户浏览记录
- def get(self, request): 获取用户浏览记录
<|skeleton|>
class HistoryView:
"""用户历史浏览记录"""
def post(self, request):
"""保存用户浏览记录"""
<|body_0|>
... | ce72dca3ec82ba97c27b543fb872cecb695710fc | <|skeleton|>
class HistoryView:
"""用户历史浏览记录"""
def post(self, request):
"""保存用户浏览记录"""
<|body_0|>
def get(self, request):
"""获取用户浏览记录"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HistoryView:
"""用户历史浏览记录"""
def post(self, request):
"""保存用户浏览记录"""
json_dict = json.loads(request.body.decode())
sku_id = json_dict.get('sku_id')
try:
SKU.objects.get(id=sku_id)
except SKU.DoesNotExist:
return http.HttpResponseForbidden('商品... | the_stack_v2_python_sparse | apps/user/views.py | cjwisme111/meiduo | train | 0 |
250b38eb74c55e0acc123e1ebccafbb1b722a1ee | [
"if page_url is None or html_cont is None:\n return\nsoup = BeautifulSoup(html_cont, 'lxml')\nnew_urls = self._get_new_urls(page_url, soup)\nnew_data = self._get_new_data(page_url, soup)\nreturn (new_urls, new_data)",
"new_urls = set()\nfor link in range(1, 100):\n new_url = 'http://www.runoob.com/w3cnote/p... | <|body_start_0|>
if page_url is None or html_cont is None:
return
soup = BeautifulSoup(html_cont, 'lxml')
new_urls = self._get_new_urls(page_url, soup)
new_data = self._get_new_data(page_url, soup)
return (new_urls, new_data)
<|end_body_0|>
<|body_start_1|>
n... | HTML解析器,就是将要爬取的数据从HTML源码中获取出来,同时也将新的URL链接发送给URL | HTMLParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HTMLParser:
"""HTML解析器,就是将要爬取的数据从HTML源码中获取出来,同时也将新的URL链接发送给URL"""
def parser(self, page_url, html_cont):
"""用于解析网页内容,抽取url和数据 :param page_url: 下载页面的url :param html_cont: 下载的网页内容 :return: 返回url和数据"""
<|body_0|>
def _get_new_urls(self, page_url, soup):
"""抽取新的url集合... | stack_v2_sparse_classes_75kplus_train_066507 | 1,846 | no_license | [
{
"docstring": "用于解析网页内容,抽取url和数据 :param page_url: 下载页面的url :param html_cont: 下载的网页内容 :return: 返回url和数据",
"name": "parser",
"signature": "def parser(self, page_url, html_cont)"
},
{
"docstring": "抽取新的url集合 :param page_url: 下载页面的url :param soup: soup 数据 :return: 返回新的url集合",
"name": "_get_new_... | 3 | stack_v2_sparse_classes_30k_train_047367 | Implement the Python class `HTMLParser` described below.
Class description:
HTML解析器,就是将要爬取的数据从HTML源码中获取出来,同时也将新的URL链接发送给URL
Method signatures and docstrings:
- def parser(self, page_url, html_cont): 用于解析网页内容,抽取url和数据 :param page_url: 下载页面的url :param html_cont: 下载的网页内容 :return: 返回url和数据
- def _get_new_urls(self, page_... | Implement the Python class `HTMLParser` described below.
Class description:
HTML解析器,就是将要爬取的数据从HTML源码中获取出来,同时也将新的URL链接发送给URL
Method signatures and docstrings:
- def parser(self, page_url, html_cont): 用于解析网页内容,抽取url和数据 :param page_url: 下载页面的url :param html_cont: 下载的网页内容 :return: 返回url和数据
- def _get_new_urls(self, page_... | 3a60fa1a8a13975c7c43262198f0c5e715caa97b | <|skeleton|>
class HTMLParser:
"""HTML解析器,就是将要爬取的数据从HTML源码中获取出来,同时也将新的URL链接发送给URL"""
def parser(self, page_url, html_cont):
"""用于解析网页内容,抽取url和数据 :param page_url: 下载页面的url :param html_cont: 下载的网页内容 :return: 返回url和数据"""
<|body_0|>
def _get_new_urls(self, page_url, soup):
"""抽取新的url集合... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HTMLParser:
"""HTML解析器,就是将要爬取的数据从HTML源码中获取出来,同时也将新的URL链接发送给URL"""
def parser(self, page_url, html_cont):
"""用于解析网页内容,抽取url和数据 :param page_url: 下载页面的url :param html_cont: 下载的网页内容 :return: 返回url和数据"""
if page_url is None or html_cont is None:
return
soup = BeautifulSoup(... | the_stack_v2_python_sparse | base_crawler/HTMLParser.py | ybsdegit/Interesting-WebCrawler | train | 15 |
0f84e8179613d47030241216090797ac9c97cac3 | [
"ping_instances, half_connection_instances = ([], [])\nresult = MonitorInstancesService.get_all_used_check_instances()\nfor instance in result:\n if '半连接' == instance['type']:\n half_connection_instances.append(instance)\n if 'ping' == instance['type']:\n ping_instances.append(instance)\nping_it... | <|body_start_0|>
ping_instances, half_connection_instances = ([], [])
result = MonitorInstancesService.get_all_used_check_instances()
for instance in result:
if '半连接' == instance['type']:
half_connection_instances.append(instance)
if 'ping' == instance['ty... | check instances class | CheckInstances | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckInstances:
"""check instances class"""
def get_check_instances():
"""get check instances :return:"""
<|body_0|>
def save_check_instances_to_redis(ping_instances, half_connection_instances):
"""save check instances to redis :param ping_instances: :param half_... | stack_v2_sparse_classes_75kplus_train_066508 | 4,953 | no_license | [
{
"docstring": "get check instances :return:",
"name": "get_check_instances",
"signature": "def get_check_instances()"
},
{
"docstring": "save check instances to redis :param ping_instances: :param half_connection_instances: :return:",
"name": "save_check_instances_to_redis",
"signature"... | 6 | stack_v2_sparse_classes_30k_train_047260 | Implement the Python class `CheckInstances` described below.
Class description:
check instances class
Method signatures and docstrings:
- def get_check_instances(): get check instances :return:
- def save_check_instances_to_redis(ping_instances, half_connection_instances): save check instances to redis :param ping_in... | Implement the Python class `CheckInstances` described below.
Class description:
check instances class
Method signatures and docstrings:
- def get_check_instances(): get check instances :return:
- def save_check_instances_to_redis(ping_instances, half_connection_instances): save check instances to redis :param ping_in... | 649d1a61ac15182b55c17e47c126d98d9b956b44 | <|skeleton|>
class CheckInstances:
"""check instances class"""
def get_check_instances():
"""get check instances :return:"""
<|body_0|>
def save_check_instances_to_redis(ping_instances, half_connection_instances):
"""save check instances to redis :param ping_instances: :param half_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CheckInstances:
"""check instances class"""
def get_check_instances():
"""get check instances :return:"""
ping_instances, half_connection_instances = ([], [])
result = MonitorInstancesService.get_all_used_check_instances()
for instance in result:
if '半连接' == in... | the_stack_v2_python_sparse | server/network_monitor_web_server/check_network/monitor/check_instances.py | JasonBourne-sxy/host-web | train | 1 |
4a7ab6a8c0d5cf6f6e18455e746edc7248a11f7b | [
"super(PacketTags, self).__init__()\nself.tag_methods = [PacketTags._tag_net_direction, PacketTags._tag_nxdomain]\nif add_tag_methods:\n self.tag_methods += add_tag_methods\nself.output_stream = self.tag_stuff()",
"for item in self.input_stream:\n if 'tags' not in item:\n item['tags'] = set()\n fo... | <|body_start_0|>
super(PacketTags, self).__init__()
self.tag_methods = [PacketTags._tag_net_direction, PacketTags._tag_nxdomain]
if add_tag_methods:
self.tag_methods += add_tag_methods
self.output_stream = self.tag_stuff()
<|end_body_0|>
<|body_start_1|>
for item in ... | Add tags to incoming packet data | PacketTags | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PacketTags:
"""Add tags to incoming packet data"""
def __init__(self, add_tag_methods=None):
"""Initialize PacketTags Class Args: add_tag_methods: a list of additional tag methods (optional, defaults to None)) Note: all methods must take the data dictionary as an argmument (e.g. tag_... | stack_v2_sparse_classes_75kplus_train_066509 | 3,568 | permissive | [
{
"docstring": "Initialize PacketTags Class Args: add_tag_methods: a list of additional tag methods (optional, defaults to None)) Note: all methods must take the data dictionary as an argmument (e.g. tag_method(data))",
"name": "__init__",
"signature": "def __init__(self, add_tag_methods=None)"
},
{... | 4 | null | Implement the Python class `PacketTags` described below.
Class description:
Add tags to incoming packet data
Method signatures and docstrings:
- def __init__(self, add_tag_methods=None): Initialize PacketTags Class Args: add_tag_methods: a list of additional tag methods (optional, defaults to None)) Note: all methods... | Implement the Python class `PacketTags` described below.
Class description:
Add tags to incoming packet data
Method signatures and docstrings:
- def __init__(self, add_tag_methods=None): Initialize PacketTags Class Args: add_tag_methods: a list of additional tag methods (optional, defaults to None)) Note: all methods... | e4f80f409e8852a5cddae8bc535b79aec397baa4 | <|skeleton|>
class PacketTags:
"""Add tags to incoming packet data"""
def __init__(self, add_tag_methods=None):
"""Initialize PacketTags Class Args: add_tag_methods: a list of additional tag methods (optional, defaults to None)) Note: all methods must take the data dictionary as an argmument (e.g. tag_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PacketTags:
"""Add tags to incoming packet data"""
def __init__(self, add_tag_methods=None):
"""Initialize PacketTags Class Args: add_tag_methods: a list of additional tag methods (optional, defaults to None)) Note: all methods must take the data dictionary as an argmument (e.g. tag_method(data))... | the_stack_v2_python_sparse | chains/links/packet_tags.py | SuperCowPowers/chains | train | 39 |
7b337ad813bdabf81194fb7c265dc47ec9ea5ad4 | [
"users_column_list = QueryHelper.get_columns_string(UserMapping, 'u')\nstmt = text('SELECT {cols} FROM \"{users_table}\" AS u WHERE u.google_id = :google_id'.format(cols=users_column_list, users_table=UserMapping.description))\nuser = db.session.query(User).from_statement(stmt).params(google_id=google_id).first()\n... | <|body_start_0|>
users_column_list = QueryHelper.get_columns_string(UserMapping, 'u')
stmt = text('SELECT {cols} FROM "{users_table}" AS u WHERE u.google_id = :google_id'.format(cols=users_column_list, users_table=UserMapping.description))
user = db.session.query(User).from_statement(stmt).param... | Repository class for Users | UsersRepository | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UsersRepository:
"""Repository class for Users"""
def get_user_by_google_id(cls, google_id: str) -> User:
"""Returns add_request by given id or none"""
<|body_0|>
def save_user(cls, user: User) -> User:
"""Saves given user and returns user with id"""
<|bo... | stack_v2_sparse_classes_75kplus_train_066510 | 2,010 | no_license | [
{
"docstring": "Returns add_request by given id or none",
"name": "get_user_by_google_id",
"signature": "def get_user_by_google_id(cls, google_id: str) -> User"
},
{
"docstring": "Saves given user and returns user with id",
"name": "save_user",
"signature": "def save_user(cls, user: User... | 3 | stack_v2_sparse_classes_30k_train_017079 | Implement the Python class `UsersRepository` described below.
Class description:
Repository class for Users
Method signatures and docstrings:
- def get_user_by_google_id(cls, google_id: str) -> User: Returns add_request by given id or none
- def save_user(cls, user: User) -> User: Saves given user and returns user wi... | Implement the Python class `UsersRepository` described below.
Class description:
Repository class for Users
Method signatures and docstrings:
- def get_user_by_google_id(cls, google_id: str) -> User: Returns add_request by given id or none
- def save_user(cls, user: User) -> User: Saves given user and returns user wi... | d5e383a3a703c973d038627f35d405e716cfd25c | <|skeleton|>
class UsersRepository:
"""Repository class for Users"""
def get_user_by_google_id(cls, google_id: str) -> User:
"""Returns add_request by given id or none"""
<|body_0|>
def save_user(cls, user: User) -> User:
"""Saves given user and returns user with id"""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UsersRepository:
"""Repository class for Users"""
def get_user_by_google_id(cls, google_id: str) -> User:
"""Returns add_request by given id or none"""
users_column_list = QueryHelper.get_columns_string(UserMapping, 'u')
stmt = text('SELECT {cols} FROM "{users_table}" AS u WHERE u... | the_stack_v2_python_sparse | app/users/repository.py | Innodogs/Innodogs | train | 0 |
08747748a4c5268ae195f91b7576f0a88fa76a08 | [
"current = self.head\nwhile current is not None:\n if current.value[0] == key:\n return current.value[1]\n current = current.next\nreturn None",
"if self.is_empty():\n print('Список пуст')\nelse:\n current = self.head\n ind = 0\n while current is not None:\n if current.value[0] == ... | <|body_start_0|>
current = self.head
while current is not None:
if current.value[0] == key:
return current.value[1]
current = current.next
return None
<|end_body_0|>
<|body_start_1|>
if self.is_empty():
print('Список пуст')
els... | This is the linked list class for the hash table | LinkedListHash | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkedListHash:
"""This is the linked list class for the hash table"""
def this_value(self, key):
"""Method for checking the existence of a node with a given value in the list"""
<|body_0|>
def delete_value(self, key):
"""Method for removing a node / nodes by a g... | stack_v2_sparse_classes_75kplus_train_066511 | 2,309 | no_license | [
{
"docstring": "Method for checking the existence of a node with a given value in the list",
"name": "this_value",
"signature": "def this_value(self, key)"
},
{
"docstring": "Method for removing a node / nodes by a given key from the list",
"name": "delete_value",
"signature": "def delet... | 2 | stack_v2_sparse_classes_30k_train_001790 | Implement the Python class `LinkedListHash` described below.
Class description:
This is the linked list class for the hash table
Method signatures and docstrings:
- def this_value(self, key): Method for checking the existence of a node with a given value in the list
- def delete_value(self, key): Method for removing ... | Implement the Python class `LinkedListHash` described below.
Class description:
This is the linked list class for the hash table
Method signatures and docstrings:
- def this_value(self, key): Method for checking the existence of a node with a given value in the list
- def delete_value(self, key): Method for removing ... | 44d27242789d670efa64dd72f9a112a80df8373c | <|skeleton|>
class LinkedListHash:
"""This is the linked list class for the hash table"""
def this_value(self, key):
"""Method for checking the existence of a node with a given value in the list"""
<|body_0|>
def delete_value(self, key):
"""Method for removing a node / nodes by a g... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LinkedListHash:
"""This is the linked list class for the hash table"""
def this_value(self, key):
"""Method for checking the existence of a node with a given value in the list"""
current = self.head
while current is not None:
if current.value[0] == key:
... | the_stack_v2_python_sparse | structures/hash_table.py | SvetlanaSumets11/python-education | train | 0 |
6939e5086cc553dbc3a9424838e867762e931308 | [
"self.logging = Logging()\nself.is_id = is_id\nself.file = file\nself.num = num\nself.country = country\nself.request = RequestClient(url)",
"data1 = {'orderSource': '1', 'ebayId': 'test', 'uid': 'ANONYMOUS', 'isId': self.is_id}\ndata2 = {'orderSource': 1, 'country': self.country, 'ebayId': 'test', 'importSum': s... | <|body_start_0|>
self.logging = Logging()
self.is_id = is_id
self.file = file
self.num = num
self.country = country
self.request = RequestClient(url)
<|end_body_0|>
<|body_start_1|>
data1 = {'orderSource': '1', 'ebayId': 'test', 'uid': 'ANONYMOUS', 'isId': self.i... | ImportOrder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImportOrder:
def __init__(self, url, is_id, file, num, country):
"""初始化订单导入所需要的的参数值 :param is_id: isid :param file: 导入订单文件 :param num: 导入数量 :param country: 导入国家"""
<|body_0|>
def import_order(self):
"""订单导入接口,分为两步:上传文件,提交请求 get_request参数如下:url, method, headers=None, ... | stack_v2_sparse_classes_75kplus_train_066512 | 3,137 | no_license | [
{
"docstring": "初始化订单导入所需要的的参数值 :param is_id: isid :param file: 导入订单文件 :param num: 导入数量 :param country: 导入国家",
"name": "__init__",
"signature": "def __init__(self, url, is_id, file, num, country)"
},
{
"docstring": "订单导入接口,分为两步:上传文件,提交请求 get_request参数如下:url, method, headers=None, data=None, para... | 2 | stack_v2_sparse_classes_30k_train_012699 | Implement the Python class `ImportOrder` described below.
Class description:
Implement the ImportOrder class.
Method signatures and docstrings:
- def __init__(self, url, is_id, file, num, country): 初始化订单导入所需要的的参数值 :param is_id: isid :param file: 导入订单文件 :param num: 导入数量 :param country: 导入国家
- def import_order(self): 订... | Implement the Python class `ImportOrder` described below.
Class description:
Implement the ImportOrder class.
Method signatures and docstrings:
- def __init__(self, url, is_id, file, num, country): 初始化订单导入所需要的的参数值 :param is_id: isid :param file: 导入订单文件 :param num: 导入数量 :param country: 导入国家
- def import_order(self): 订... | 931179680d2c0bf9187060711c9f6dab94119024 | <|skeleton|>
class ImportOrder:
def __init__(self, url, is_id, file, num, country):
"""初始化订单导入所需要的的参数值 :param is_id: isid :param file: 导入订单文件 :param num: 导入数量 :param country: 导入国家"""
<|body_0|>
def import_order(self):
"""订单导入接口,分为两步:上传文件,提交请求 get_request参数如下:url, method, headers=None, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImportOrder:
def __init__(self, url, is_id, file, num, country):
"""初始化订单导入所需要的的参数值 :param is_id: isid :param file: 导入订单文件 :param num: 导入数量 :param country: 导入国家"""
self.logging = Logging()
self.is_id = is_id
self.file = file
self.num = num
self.country = country... | the_stack_v2_python_sparse | case/import_order.py | zhoululululu/Automation | train | 0 | |
706e065d5a7f1fe0b5b92beff9432613340340a9 | [
"data = []\ndata.append(scheduler_id)\nres = requests.post(url=enable_scheduler_url, headers=get_headers(HOST_189), data=json.dumps(data))\nself.assertEqual(res.status_code, 204, msg='启用计划接口调用失败')",
"data = []\ndata.append(scheduler_id)\nres = requests.post(url=disable_scheduler_url, headers=get_headers(HOST_189)... | <|body_start_0|>
data = []
data.append(scheduler_id)
res = requests.post(url=enable_scheduler_url, headers=get_headers(HOST_189), data=json.dumps(data))
self.assertEqual(res.status_code, 204, msg='启用计划接口调用失败')
<|end_body_0|>
<|body_start_1|>
data = []
data.append(schedul... | 测试启用停用、批量删除schedulers接口 | EnableDisable | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnableDisable:
"""测试启用停用、批量删除schedulers接口"""
def test_case01(self):
"""启用计划"""
<|body_0|>
def test_case02(self):
"""停用计划"""
<|body_1|>
def test_case03(self):
"""批量删除计划"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
data = [... | stack_v2_sparse_classes_75kplus_train_066513 | 15,511 | no_license | [
{
"docstring": "启用计划",
"name": "test_case01",
"signature": "def test_case01(self)"
},
{
"docstring": "停用计划",
"name": "test_case02",
"signature": "def test_case02(self)"
},
{
"docstring": "批量删除计划",
"name": "test_case03",
"signature": "def test_case03(self)"
}
] | 3 | stack_v2_sparse_classes_30k_train_014618 | Implement the Python class `EnableDisable` described below.
Class description:
测试启用停用、批量删除schedulers接口
Method signatures and docstrings:
- def test_case01(self): 启用计划
- def test_case02(self): 停用计划
- def test_case03(self): 批量删除计划 | Implement the Python class `EnableDisable` described below.
Class description:
测试启用停用、批量删除schedulers接口
Method signatures and docstrings:
- def test_case01(self): 启用计划
- def test_case02(self): 停用计划
- def test_case03(self): 批量删除计划
<|skeleton|>
class EnableDisable:
"""测试启用停用、批量删除schedulers接口"""
def test_case01... | fc41513af3063169ff1b17d6f01f7074057ceb1f | <|skeleton|>
class EnableDisable:
"""测试启用停用、批量删除schedulers接口"""
def test_case01(self):
"""启用计划"""
<|body_0|>
def test_case02(self):
"""停用计划"""
<|body_1|>
def test_case03(self):
"""批量删除计划"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EnableDisable:
"""测试启用停用、批量删除schedulers接口"""
def test_case01(self):
"""启用计划"""
data = []
data.append(scheduler_id)
res = requests.post(url=enable_scheduler_url, headers=get_headers(HOST_189), data=json.dumps(data))
self.assertEqual(res.status_code, 204, msg='启用计划接口... | the_stack_v2_python_sparse | singl_api/api_test_cases/cases_for_schedulers_api.py | bingjiegu/For_API | train | 0 |
b734b5880b5e6e9e80af0074e18e3a3635bc202b | [
"image_id = self.kwargs.get('image_id', None)\ntag_id = self.kwargs.get('tag_id', None)\nif image_id is None:\n return get_object_or_404(Tag, pk=tag_id)\nimage = get_object_or_404(Image, pk=image_id)\nreturn get_object_or_404(image.tag_set.all(), pk=tag_id)",
"tag_id = self.kwargs.get('tag_id', None)\ntag = ge... | <|body_start_0|>
image_id = self.kwargs.get('image_id', None)
tag_id = self.kwargs.get('tag_id', None)
if image_id is None:
return get_object_or_404(Tag, pk=tag_id)
image = get_object_or_404(Image, pk=image_id)
return get_object_or_404(image.tag_set.all(), pk=tag_id)
... | Класа која се користи за приказ, ажурирање и брисање инстанце класе Ознака; Репрезентује податке у JSON формату | TagDetailAPIView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TagDetailAPIView:
"""Класа која се користи за приказ, ажурирање и брисање инстанце класе Ознака; Репрезентује податке у JSON формату"""
def get_object(self):
"""Метода помоћу које се врши добављање појединачне инстанце; Окида се на HTTP GET метод :return: Tag|Http404"""
<|bod... | stack_v2_sparse_classes_75kplus_train_066514 | 4,818 | no_license | [
{
"docstring": "Метода помоћу које се врши добављање појединачне инстанце; Окида се на HTTP GET метод :return: Tag|Http404",
"name": "get_object",
"signature": "def get_object(self)"
},
{
"docstring": "Метода помоћу које се врши ажурирање инстанце; Окида се на HTTP PUT метод; :param request: use... | 3 | stack_v2_sparse_classes_30k_train_039892 | Implement the Python class `TagDetailAPIView` described below.
Class description:
Класа која се користи за приказ, ажурирање и брисање инстанце класе Ознака; Репрезентује податке у JSON формату
Method signatures and docstrings:
- def get_object(self): Метода помоћу које се врши добављање појединачне инстанце; Окида с... | Implement the Python class `TagDetailAPIView` described below.
Class description:
Класа која се користи за приказ, ажурирање и брисање инстанце класе Ознака; Репрезентује податке у JSON формату
Method signatures and docstrings:
- def get_object(self): Метода помоћу које се врши добављање појединачне инстанце; Окида с... | 9b49cdfdcfbbc911cec23ed30ded30f6c4042522 | <|skeleton|>
class TagDetailAPIView:
"""Класа која се користи за приказ, ажурирање и брисање инстанце класе Ознака; Репрезентује податке у JSON формату"""
def get_object(self):
"""Метода помоћу које се врши добављање појединачне инстанце; Окида се на HTTP GET метод :return: Tag|Http404"""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TagDetailAPIView:
"""Класа која се користи за приказ, ажурирање и брисање инстанце класе Ознака; Репрезентује податке у JSON формату"""
def get_object(self):
"""Метода помоћу које се врши добављање појединачне инстанце; Окида се на HTTP GET метод :return: Tag|Http404"""
image_id = self.kw... | the_stack_v2_python_sparse | src/tags/api/views.py | milosb793/django-gallery-api | train | 0 |
2f5976adc2d2cd587e2cf47c3b4837da73d64745 | [
"self.run_root = run_root\nself.node_ids = node_ids\nself.antenna_mask = antenna_mask\nself.nb_antennas = self.mask_to_number[antenna_mask]\nself.RSSI = {(sender, receiver): Averager(self.nb_antennas + 1) for sender in node_ids for receiver in node_ids}",
"for sender in self.node_ids:\n result_name = self.run_... | <|body_start_0|>
self.run_root = run_root
self.node_ids = node_ids
self.antenna_mask = antenna_mask
self.nb_antennas = self.mask_to_number[antenna_mask]
self.RSSI = {(sender, receiver): Averager(self.nb_antennas + 1) for sender in node_ids for receiver in node_ids}
<|end_body_0|>... | one instance of this class for each call to one_run will do the aggregation into RSSI.txt | Aggregator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Aggregator:
"""one instance of this class for each call to one_run will do the aggregation into RSSI.txt"""
def __init__(self, run_root, node_ids, antenna_mask):
"""run_root should be a pathlib Path"""
<|body_0|>
def run(self):
"""call at the end of one_run"""
... | stack_v2_sparse_classes_75kplus_train_066515 | 3,309 | no_license | [
{
"docstring": "run_root should be a pathlib Path",
"name": "__init__",
"signature": "def __init__(self, run_root, node_ids, antenna_mask)"
},
{
"docstring": "call at the end of one_run",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_043815 | Implement the Python class `Aggregator` described below.
Class description:
one instance of this class for each call to one_run will do the aggregation into RSSI.txt
Method signatures and docstrings:
- def __init__(self, run_root, node_ids, antenna_mask): run_root should be a pathlib Path
- def run(self): call at the... | Implement the Python class `Aggregator` described below.
Class description:
one instance of this class for each call to one_run will do the aggregation into RSSI.txt
Method signatures and docstrings:
- def __init__(self, run_root, node_ids, antenna_mask): run_root should be a pathlib Path
- def run(self): call at the... | 7f2854678c52b2ef26bcd33596d2f1ca53a9a1a4 | <|skeleton|>
class Aggregator:
"""one instance of this class for each call to one_run will do the aggregation into RSSI.txt"""
def __init__(self, run_root, node_ids, antenna_mask):
"""run_root should be a pathlib Path"""
<|body_0|>
def run(self):
"""call at the end of one_run"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Aggregator:
"""one instance of this class for each call to one_run will do the aggregation into RSSI.txt"""
def __init__(self, run_root, node_ids, antenna_mask):
"""run_root should be a pathlib Path"""
self.run_root = run_root
self.node_ids = node_ids
self.antenna_mask = a... | the_stack_v2_python_sparse | batman-vs-olsr/processmap.py | fit-r2lab/r2lab-demos | train | 4 |
81f363368eb9da41b4414fd7151288444367e500 | [
"def dfs(i):\n if visited[i]:\n return 0\n visited[i] = True\n count = 1\n for j in range(len(M[i])):\n if M[i][j] == 1 and i != j:\n count += dfs(j)\n return count\ncount = 0\nvisited = [False] * len(M)\nfor i in range(len(M)):\n if dfs(i) > 0:\n count += 1\nreturn... | <|body_start_0|>
def dfs(i):
if visited[i]:
return 0
visited[i] = True
count = 1
for j in range(len(M[i])):
if M[i][j] == 1 and i != j:
count += dfs(j)
return count
count = 0
visited =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findCircleNum(self, M):
""":type M: List[List[int]] :rtype: int"""
<|body_0|>
def findCircleNum_unionfind(self, M):
""":type M: List[List[int]] :rtype: int"""
<|body_1|>
def findCircleNum_wrong(self, M):
""":type M: List[List[int]] ... | stack_v2_sparse_classes_75kplus_train_066516 | 24,866 | no_license | [
{
"docstring": ":type M: List[List[int]] :rtype: int",
"name": "findCircleNum",
"signature": "def findCircleNum(self, M)"
},
{
"docstring": ":type M: List[List[int]] :rtype: int",
"name": "findCircleNum_unionfind",
"signature": "def findCircleNum_unionfind(self, M)"
},
{
"docstri... | 4 | stack_v2_sparse_classes_30k_train_047655 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findCircleNum(self, M): :type M: List[List[int]] :rtype: int
- def findCircleNum_unionfind(self, M): :type M: List[List[int]] :rtype: int
- def findCircleNum_wrong(self, M): ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findCircleNum(self, M): :type M: List[List[int]] :rtype: int
- def findCircleNum_unionfind(self, M): :type M: List[List[int]] :rtype: int
- def findCircleNum_wrong(self, M): ... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def findCircleNum(self, M):
""":type M: List[List[int]] :rtype: int"""
<|body_0|>
def findCircleNum_unionfind(self, M):
""":type M: List[List[int]] :rtype: int"""
<|body_1|>
def findCircleNum_wrong(self, M):
""":type M: List[List[int]] ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findCircleNum(self, M):
""":type M: List[List[int]] :rtype: int"""
def dfs(i):
if visited[i]:
return 0
visited[i] = True
count = 1
for j in range(len(M[i])):
if M[i][j] == 1 and i != j:
... | the_stack_v2_python_sparse | src/lt_547.py | oxhead/CodingYourWay | train | 0 | |
f0adc7309c4c602961cdcfacbd630dfe0648585c | [
"self.fast_rayshooting = MultiplaneFast(x_image, y_image, z_lens, z_source, lens_model_list, redshift_list, astropy_instance, parameter_class, foreground_rays, tol_source, numerical_alpha_class)\nself._tol_source = tol_source\nself._pso_convergence_mean = pso_convergence_mean\nself._param_class = parameter_class\ns... | <|body_start_0|>
self.fast_rayshooting = MultiplaneFast(x_image, y_image, z_lens, z_source, lens_model_list, redshift_list, astropy_instance, parameter_class, foreground_rays, tol_source, numerical_alpha_class)
self._tol_source = tol_source
self._pso_convergence_mean = pso_convergence_mean
... | class which executes the optimization routines. Currently implemented as a particle swarm optimization followed by a downhill simplex routine. Particle swarm optimizer is modified from the CosmoHammer particle swarm routine with different convergence criteria implemented. | Optimizer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Optimizer:
"""class which executes the optimization routines. Currently implemented as a particle swarm optimization followed by a downhill simplex routine. Particle swarm optimizer is modified from the CosmoHammer particle swarm routine with different convergence criteria implemented."""
de... | stack_v2_sparse_classes_75kplus_train_066517 | 6,114 | permissive | [
{
"docstring": ":param x_image: x_image to fit (should be length 4) :param y_image: y_image to fit (should be length 4) :param lens_model_list: list of lens models for the system :param redshift_list: list of lens redshifts for the system :param z_lens: the main deflector redshift, the lens models being optimiz... | 4 | null | Implement the Python class `Optimizer` described below.
Class description:
class which executes the optimization routines. Currently implemented as a particle swarm optimization followed by a downhill simplex routine. Particle swarm optimizer is modified from the CosmoHammer particle swarm routine with different conve... | Implement the Python class `Optimizer` described below.
Class description:
class which executes the optimization routines. Currently implemented as a particle swarm optimization followed by a downhill simplex routine. Particle swarm optimizer is modified from the CosmoHammer particle swarm routine with different conve... | 73c9645f26f6983fe7961104075ebe8bf7a4b54c | <|skeleton|>
class Optimizer:
"""class which executes the optimization routines. Currently implemented as a particle swarm optimization followed by a downhill simplex routine. Particle swarm optimizer is modified from the CosmoHammer particle swarm routine with different convergence criteria implemented."""
de... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Optimizer:
"""class which executes the optimization routines. Currently implemented as a particle swarm optimization followed by a downhill simplex routine. Particle swarm optimizer is modified from the CosmoHammer particle swarm routine with different convergence criteria implemented."""
def __init__(se... | the_stack_v2_python_sparse | lenstronomy/LensModel/QuadOptimizer/optimizer.py | lenstronomy/lenstronomy | train | 41 |
73cb954133495750fac60a75244893fddb761961 | [
"handler.ContentHandler.__init__(self)\nself.collection = collection\nself.mname = None\nself.option_list = None\nself.oname = None\nself.o = None\nself.an_o = None\nself.list_class = OptionList",
"if tag in ('report', 'module'):\n self.mname = attrs['name']\n self.option_list = self.list_class()\n self.... | <|body_start_0|>
handler.ContentHandler.__init__(self)
self.collection = collection
self.mname = None
self.option_list = None
self.oname = None
self.o = None
self.an_o = None
self.list_class = OptionList
<|end_body_0|>
<|body_start_1|>
if tag in (... | SAX parsing class for the OptionListCollection XML file. | OptionParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptionParser:
"""SAX parsing class for the OptionListCollection XML file."""
def __init__(self, collection):
"""Create a OptionParser class that populates the passed collection. collection: OptionListCollection to be loaded from the file."""
<|body_0|>
def startElement(s... | stack_v2_sparse_classes_75kplus_train_066518 | 19,905 | no_license | [
{
"docstring": "Create a OptionParser class that populates the passed collection. collection: OptionListCollection to be loaded from the file.",
"name": "__init__",
"signature": "def __init__(self, collection)"
},
{
"docstring": "Overridden class that handles the start of a XML element",
"na... | 3 | stack_v2_sparse_classes_30k_train_033064 | Implement the Python class `OptionParser` described below.
Class description:
SAX parsing class for the OptionListCollection XML file.
Method signatures and docstrings:
- def __init__(self, collection): Create a OptionParser class that populates the passed collection. collection: OptionListCollection to be loaded fro... | Implement the Python class `OptionParser` described below.
Class description:
SAX parsing class for the OptionListCollection XML file.
Method signatures and docstrings:
- def __init__(self, collection): Create a OptionParser class that populates the passed collection. collection: OptionListCollection to be loaded fro... | 0c79561bed7ff42c88714edbc85197fa9235e188 | <|skeleton|>
class OptionParser:
"""SAX parsing class for the OptionListCollection XML file."""
def __init__(self, collection):
"""Create a OptionParser class that populates the passed collection. collection: OptionListCollection to be loaded from the file."""
<|body_0|>
def startElement(s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OptionParser:
"""SAX parsing class for the OptionListCollection XML file."""
def __init__(self, collection):
"""Create a OptionParser class that populates the passed collection. collection: OptionListCollection to be loaded from the file."""
handler.ContentHandler.__init__(self)
s... | the_stack_v2_python_sparse | gen/plug/_options.py | balrok/gramps_addon | train | 2 |
f2ab0baafcf21bf6dc1e3bfda234c637c301cbf3 | [
"try:\n try:\n return Product.objects.get(ProductId=int(id))\n except ValueError as e:\n return Product.objects.get(ProductSlug=id)\nexcept Product.DoesNotExist:\n self.NOT_FOUND_RESP = Response({id: 'Product Not Found'}, status=status.HTTP_404_NOT_FOUND)\n return None",
"product = self.... | <|body_start_0|>
try:
try:
return Product.objects.get(ProductId=int(id))
except ValueError as e:
return Product.objects.get(ProductSlug=id)
except Product.DoesNotExist:
self.NOT_FOUND_RESP = Response({id: 'Product Not Found'}, status=st... | Inhereits APIView class to encapsulate Read(GET), Update(PUT) and Delete(DELETE) operations on the model/table Product given a specific product id (unique). | ProductViewForIdAndSlug | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductViewForIdAndSlug:
"""Inhereits APIView class to encapsulate Read(GET), Update(PUT) and Delete(DELETE) operations on the model/table Product given a specific product id (unique)."""
def get_object(self, id):
"""Fetch an instance based on its primary key ie id. If no id is found... | stack_v2_sparse_classes_75kplus_train_066519 | 20,756 | no_license | [
{
"docstring": "Fetch an instance based on its primary key ie id. If no id is found return None :param id: Id of the instance which needs to be fetched :return: product instance with given id. If not found returns None",
"name": "get_object",
"signature": "def get_object(self, id)"
},
{
"docstri... | 4 | null | Implement the Python class `ProductViewForIdAndSlug` described below.
Class description:
Inhereits APIView class to encapsulate Read(GET), Update(PUT) and Delete(DELETE) operations on the model/table Product given a specific product id (unique).
Method signatures and docstrings:
- def get_object(self, id): Fetch an i... | Implement the Python class `ProductViewForIdAndSlug` described below.
Class description:
Inhereits APIView class to encapsulate Read(GET), Update(PUT) and Delete(DELETE) operations on the model/table Product given a specific product id (unique).
Method signatures and docstrings:
- def get_object(self, id): Fetch an i... | 83d4abe6966f0ed51b288b3910b4dc28e564af0a | <|skeleton|>
class ProductViewForIdAndSlug:
"""Inhereits APIView class to encapsulate Read(GET), Update(PUT) and Delete(DELETE) operations on the model/table Product given a specific product id (unique)."""
def get_object(self, id):
"""Fetch an instance based on its primary key ie id. If no id is found... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProductViewForIdAndSlug:
"""Inhereits APIView class to encapsulate Read(GET), Update(PUT) and Delete(DELETE) operations on the model/table Product given a specific product id (unique)."""
def get_object(self, id):
"""Fetch an instance based on its primary key ie id. If no id is found return None ... | the_stack_v2_python_sparse | NGKARTAPI/product/views.py | SmrutiRanjan-Ai/django | train | 0 |
23afee10ed2cfa32517253525d55cb05133fbed8 | [
"self.fxdata = fxdata\nself.lookahead = lookahead\ntimestamps = self.fxdata.timestamp()\nself.start = timestamps.index(timestamp)",
"values = self.fxdata.fxlow()\nresult = self._classify(values, kessler=kessler)\nreturn result",
"values = self.fxdata.fxhigh()\nresult = self._classify(values, kessler=kessler)\nr... | <|body_start_0|>
self.fxdata = fxdata
self.lookahead = lookahead
timestamps = self.fxdata.timestamp()
self.start = timestamps.index(timestamp)
<|end_body_0|>
<|body_start_1|>
values = self.fxdata.fxlow()
result = self._classify(values, kessler=kessler)
return res... | Class to classify database data. Args: None Returns: None Methods: | Classify | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Classify:
"""Class to classify database data. Args: None Returns: None Methods:"""
def __init__(self, fxdata, timestamp, lookahead):
"""Method for intializing the class. Args: fxdata: Object of fxdata table timestamp: Ending timestamp of data subset to be analyzed lookahead: Number o... | stack_v2_sparse_classes_75kplus_train_066520 | 22,478 | no_license | [
{
"docstring": "Method for intializing the class. Args: fxdata: Object of fxdata table timestamp: Ending timestamp of data subset to be analyzed lookahead: Number of periods before timestamp to analyze Returns: None",
"name": "__init__",
"signature": "def __init__(self, fxdata, timestamp, lookahead)"
... | 4 | stack_v2_sparse_classes_30k_val_001715 | Implement the Python class `Classify` described below.
Class description:
Class to classify database data. Args: None Returns: None Methods:
Method signatures and docstrings:
- def __init__(self, fxdata, timestamp, lookahead): Method for intializing the class. Args: fxdata: Object of fxdata table timestamp: Ending ti... | Implement the Python class `Classify` described below.
Class description:
Class to classify database data. Args: None Returns: None Methods:
Method signatures and docstrings:
- def __init__(self, fxdata, timestamp, lookahead): Method for intializing the class. Args: fxdata: Object of fxdata table timestamp: Ending ti... | 608fc1822fb859e69bb2fcb5a1abad5a87dcd714 | <|skeleton|>
class Classify:
"""Class to classify database data. Args: None Returns: None Methods:"""
def __init__(self, fxdata, timestamp, lookahead):
"""Method for intializing the class. Args: fxdata: Object of fxdata table timestamp: Ending timestamp of data subset to be analyzed lookahead: Number o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Classify:
"""Class to classify database data. Args: None Returns: None Methods:"""
def __init__(self, fxdata, timestamp, lookahead):
"""Method for intializing the class. Args: fxdata: Object of fxdata table timestamp: Ending timestamp of data subset to be analyzed lookahead: Number of periods bef... | the_stack_v2_python_sparse | crawsiz/main/feature.py | palisadoes/crawsiz | train | 0 |
f679013dca7ebe4e045e170d7da1030a02c2331a | [
"self.voluntaryOnly = voluntaryOnly\nself.DGindex = 0\nself.DGnodes = {}",
"self.DGnodes[label] = self.DGindex\nself.DGindex += 1\nreturn self.DGindex - 1",
"elementi = line.decode('UTF-8').split('\\t')\nassert len(elementi) == 9\norigin, destination, date, cited_by, country = (elementi[1], elementi[2], element... | <|body_start_0|>
self.voluntaryOnly = voluntaryOnly
self.DGindex = 0
self.DGnodes = {}
<|end_body_0|>
<|body_start_1|>
self.DGnodes[label] = self.DGindex
self.DGindex += 1
return self.DGindex - 1
<|end_body_1|>
<|body_start_2|>
elementi = line.decode('UTF-8').sp... | ReducedCitationSpace | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReducedCitationSpace:
def __init__(self, voluntaryOnly=False):
"""Constructor method. Prepares variables. Arguments: voluntaryOnly - bool - should only citations put by the applicant be considered or all citations, Returns: Instance of object."""
<|body_0|>
def record_node(s... | stack_v2_sparse_classes_75kplus_train_066521 | 5,151 | no_license | [
{
"docstring": "Constructor method. Prepares variables. Arguments: voluntaryOnly - bool - should only citations put by the applicant be considered or all citations, Returns: Instance of object.",
"name": "__init__",
"signature": "def __init__(self, voluntaryOnly=False)"
},
{
"docstring": "Method... | 5 | stack_v2_sparse_classes_30k_train_013207 | Implement the Python class `ReducedCitationSpace` described below.
Class description:
Implement the ReducedCitationSpace class.
Method signatures and docstrings:
- def __init__(self, voluntaryOnly=False): Constructor method. Prepares variables. Arguments: voluntaryOnly - bool - should only citations put by the applic... | Implement the Python class `ReducedCitationSpace` described below.
Class description:
Implement the ReducedCitationSpace class.
Method signatures and docstrings:
- def __init__(self, voluntaryOnly=False): Constructor method. Prepares variables. Arguments: voluntaryOnly - bool - should only citations put by the applic... | 922e33ea921ac2d90ef239439f240a97861de0ef | <|skeleton|>
class ReducedCitationSpace:
def __init__(self, voluntaryOnly=False):
"""Constructor method. Prepares variables. Arguments: voluntaryOnly - bool - should only citations put by the applicant be considered or all citations, Returns: Instance of object."""
<|body_0|>
def record_node(s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReducedCitationSpace:
def __init__(self, voluntaryOnly=False):
"""Constructor method. Prepares variables. Arguments: voluntaryOnly - bool - should only citations put by the applicant be considered or all citations, Returns: Instance of object."""
self.voluntaryOnly = voluntaryOnly
self... | the_stack_v2_python_sparse | citation_network/citation_parse_full_node_list.py | x0range/greenpatents | train | 0 | |
caf0cefc987a3c08109cf8ff88999f5e1878a698 | [
"if len(s) < 1:\n return 0\ni, max_len = (0, 0)\nc = 0\nfor i in range(len(s)):\n j = 0\n while i - j >= 0 and i + j < len(s):\n if s[i - j] != s[i + j]:\n break\n c = 2 * j + 1\n j += 1\n max_len = max(max_len, c)\n j = 0\n while i - j >= 0 and i + j + 1 < len(s):\... | <|body_start_0|>
if len(s) < 1:
return 0
i, max_len = (0, 0)
c = 0
for i in range(len(s)):
j = 0
while i - j >= 0 and i + j < len(s):
if s[i - j] != s[i + j]:
break
c = 2 * j + 1
j += ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def LPS_basic(self, s):
"""枚举中心位置,然后再在该位置上用扩展法,记录并更新得到的最长的回文长度 :param s: :return:"""
<|body_0|>
def manacher(self, s):
"""manacher算法 step 1: 令RL[i]=min(RL[2*pos-i], MaxRight-i) step 2: 以i为中心扩展回文串,直到左右两边字符不同,或者到达边界。 step 3: 更新MaxRight和pos reference:https://s... | stack_v2_sparse_classes_75kplus_train_066522 | 2,050 | no_license | [
{
"docstring": "枚举中心位置,然后再在该位置上用扩展法,记录并更新得到的最长的回文长度 :param s: :return:",
"name": "LPS_basic",
"signature": "def LPS_basic(self, s)"
},
{
"docstring": "manacher算法 step 1: 令RL[i]=min(RL[2*pos-i], MaxRight-i) step 2: 以i为中心扩展回文串,直到左右两边字符不同,或者到达边界。 step 3: 更新MaxRight和pos reference:https://segmentfaul... | 2 | stack_v2_sparse_classes_30k_train_036721 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def LPS_basic(self, s): 枚举中心位置,然后再在该位置上用扩展法,记录并更新得到的最长的回文长度 :param s: :return:
- def manacher(self, s): manacher算法 step 1: 令RL[i]=min(RL[2*pos-i], MaxRight-i) step 2: 以i为中心扩展回文串,... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def LPS_basic(self, s): 枚举中心位置,然后再在该位置上用扩展法,记录并更新得到的最长的回文长度 :param s: :return:
- def manacher(self, s): manacher算法 step 1: 令RL[i]=min(RL[2*pos-i], MaxRight-i) step 2: 以i为中心扩展回文串,... | 215d513b3564a7a76db3d2b29e4acc341a68e8ee | <|skeleton|>
class Solution:
def LPS_basic(self, s):
"""枚举中心位置,然后再在该位置上用扩展法,记录并更新得到的最长的回文长度 :param s: :return:"""
<|body_0|>
def manacher(self, s):
"""manacher算法 step 1: 令RL[i]=min(RL[2*pos-i], MaxRight-i) step 2: 以i为中心扩展回文串,直到左右两边字符不同,或者到达边界。 step 3: 更新MaxRight和pos reference:https://s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def LPS_basic(self, s):
"""枚举中心位置,然后再在该位置上用扩展法,记录并更新得到的最长的回文长度 :param s: :return:"""
if len(s) < 1:
return 0
i, max_len = (0, 0)
c = 0
for i in range(len(s)):
j = 0
while i - j >= 0 and i + j < len(s):
if s[i... | the_stack_v2_python_sparse | python/dp/longest-palindrome-substring.py | euxuoh/leetcode | train | 0 | |
a53f6fa02e707cb99cd45f0f7696d00683a57b05 | [
"super().__init__(title, parent)\nif icon_provider is None:\n self.icon_provider = widgets.FileIconProvider()\nelse:\n self.icon_provider = icon_provider\nself.clear_icon = clear_icon\nself.manager = recent_files_manager\nself.recent_files_actions: list[gui.Action] = []\nself.update_actions()",
"self.clear(... | <|body_start_0|>
super().__init__(title, parent)
if icon_provider is None:
self.icon_provider = widgets.FileIconProvider()
else:
self.icon_provider = icon_provider
self.clear_icon = clear_icon
self.manager = recent_files_manager
self.recent_files_a... | Menu that manage the list of recent files. To use the menu, simply connect to the open_requested signal. | MenuRecentFiles | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MenuRecentFiles:
"""Menu that manage the list of recent files. To use the menu, simply connect to the open_requested signal."""
def __init__(self, parent, recent_files_manager=None, title: str='Recent files', icon_provider=None, clear_icon=None):
"""Init. :param parent: parent object... | stack_v2_sparse_classes_75kplus_train_066523 | 6,653 | permissive | [
{
"docstring": "Init. :param parent: parent object :param icon_provider: Object that provides icon based on the file path. :type icon_provider: QtWidgets.QFileIconProvider :param clear_icon: Clear action icon. This parameter is a tuple made up of the icon theme name and the fallback icon path (from your resourc... | 4 | null | Implement the Python class `MenuRecentFiles` described below.
Class description:
Menu that manage the list of recent files. To use the menu, simply connect to the open_requested signal.
Method signatures and docstrings:
- def __init__(self, parent, recent_files_manager=None, title: str='Recent files', icon_provider=N... | Implement the Python class `MenuRecentFiles` described below.
Class description:
Menu that manage the list of recent files. To use the menu, simply connect to the open_requested signal.
Method signatures and docstrings:
- def __init__(self, parent, recent_files_manager=None, title: str='Recent files', icon_provider=N... | f00500d992d1befb0f2c2ae62fd2a8aafba7fd45 | <|skeleton|>
class MenuRecentFiles:
"""Menu that manage the list of recent files. To use the menu, simply connect to the open_requested signal."""
def __init__(self, parent, recent_files_manager=None, title: str='Recent files', icon_provider=None, clear_icon=None):
"""Init. :param parent: parent object... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MenuRecentFiles:
"""Menu that manage the list of recent files. To use the menu, simply connect to the open_requested signal."""
def __init__(self, parent, recent_files_manager=None, title: str='Recent files', icon_provider=None, clear_icon=None):
"""Init. :param parent: parent object :param icon_... | the_stack_v2_python_sparse | prettyqt/utils/menurecentfiles.py | phil65/PrettyQt | train | 17 |
ad02cdc019016d48d77336ada50b490c2d6bbb87 | [
"super().__init__(**kwargs)\nself.create_model(**kwargs)\nself.initialize_tensorkeys_for_functions()",
"config = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nconfig.intra_op_parallelism_threads = 112\nconfig.inter_op_parallelism_threads = 1\nself.sess = tf.Session(config=config)\nself.X = tf.placehol... | <|body_start_0|>
super().__init__(**kwargs)
self.create_model(**kwargs)
self.initialize_tensorkeys_for_functions()
<|end_body_0|>
<|body_start_1|>
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.intra_op_parallelism_threads = 112
config.in... | Initialize. Args: **kwargs: Additional parameters to pass to the function | TensorFlow2DUNet | [
"LicenseRef-scancode-protobuf",
"MPL-2.0",
"MIT",
"BSD-3-Clause",
"Apache-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TensorFlow2DUNet:
"""Initialize. Args: **kwargs: Additional parameters to pass to the function"""
def __init__(self, **kwargs):
"""Initialize. Args: **kwargs: Additional parameters to pass to the function"""
<|body_0|>
def create_model(self, training_smoothing=32.0, vali... | stack_v2_sparse_classes_75kplus_train_066524 | 8,194 | permissive | [
{
"docstring": "Initialize. Args: **kwargs: Additional parameters to pass to the function",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Create the TensorFlow 2D U-Net model. Args: training_smoothing (float): (Default=32.0) validation_smoothing (float): (Def... | 2 | stack_v2_sparse_classes_30k_train_037397 | Implement the Python class `TensorFlow2DUNet` described below.
Class description:
Initialize. Args: **kwargs: Additional parameters to pass to the function
Method signatures and docstrings:
- def __init__(self, **kwargs): Initialize. Args: **kwargs: Additional parameters to pass to the function
- def create_model(sel... | Implement the Python class `TensorFlow2DUNet` described below.
Class description:
Initialize. Args: **kwargs: Additional parameters to pass to the function
Method signatures and docstrings:
- def __init__(self, **kwargs): Initialize. Args: **kwargs: Additional parameters to pass to the function
- def create_model(sel... | bd73b749a9ea1b92dbcdd07e639752101d769fc0 | <|skeleton|>
class TensorFlow2DUNet:
"""Initialize. Args: **kwargs: Additional parameters to pass to the function"""
def __init__(self, **kwargs):
"""Initialize. Args: **kwargs: Additional parameters to pass to the function"""
<|body_0|>
def create_model(self, training_smoothing=32.0, vali... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TensorFlow2DUNet:
"""Initialize. Args: **kwargs: Additional parameters to pass to the function"""
def __init__(self, **kwargs):
"""Initialize. Args: **kwargs: Additional parameters to pass to the function"""
super().__init__(**kwargs)
self.create_model(**kwargs)
self.initi... | the_stack_v2_python_sparse | openfl-workspace/tf_2dunet/src/tf_2dunet.py | PDuckworth/openfl | train | 0 |
13fef981994748acc329abb9ef3c097089d18230 | [
"result = [0 for _ in range(n)]\nfor i, j, k in bookings:\n for m in range(i, j + 1):\n result[m - 1] += k\nreturn result",
"result = [0 for _ in range(n)]\nhashmap = dict()\nfor i, j, k in bookings:\n if (i, j) not in hashmap:\n hashmap[i, j] = k\n else:\n hashmap[i, j] += k\nfor i,... | <|body_start_0|>
result = [0 for _ in range(n)]
for i, j, k in bookings:
for m in range(i, j + 1):
result[m - 1] += k
return result
<|end_body_0|>
<|body_start_1|>
result = [0 for _ in range(n)]
hashmap = dict()
for i, j, k in bookings:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def corpFlightBookings(self, bookings, n: int):
"""超时 :param list[list[int]] bookings: :param n: :return: list[int]"""
<|body_0|>
def corpFlightBookings2(self, bookings, n: int):
"""超时 :param list[list[int]] bookings: :param n: :return: list[int]"""
... | stack_v2_sparse_classes_75kplus_train_066525 | 2,401 | no_license | [
{
"docstring": "超时 :param list[list[int]] bookings: :param n: :return: list[int]",
"name": "corpFlightBookings",
"signature": "def corpFlightBookings(self, bookings, n: int)"
},
{
"docstring": "超时 :param list[list[int]] bookings: :param n: :return: list[int]",
"name": "corpFlightBookings2",
... | 3 | stack_v2_sparse_classes_30k_train_027784 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def corpFlightBookings(self, bookings, n: int): 超时 :param list[list[int]] bookings: :param n: :return: list[int]
- def corpFlightBookings2(self, bookings, n: int): 超时 :param list... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def corpFlightBookings(self, bookings, n: int): 超时 :param list[list[int]] bookings: :param n: :return: list[int]
- def corpFlightBookings2(self, bookings, n: int): 超时 :param list... | 837957ea22aa07ce28a6c23ea0419bd2011e1f88 | <|skeleton|>
class Solution:
def corpFlightBookings(self, bookings, n: int):
"""超时 :param list[list[int]] bookings: :param n: :return: list[int]"""
<|body_0|>
def corpFlightBookings2(self, bookings, n: int):
"""超时 :param list[list[int]] bookings: :param n: :return: list[int]"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def corpFlightBookings(self, bookings, n: int):
"""超时 :param list[list[int]] bookings: :param n: :return: list[int]"""
result = [0 for _ in range(n)]
for i, j, k in bookings:
for m in range(i, j + 1):
result[m - 1] += k
return result
d... | the_stack_v2_python_sparse | 华为题库/航班预定统计.py | 2226171237/Algorithmpractice | train | 0 | |
488b88a79697f6bf259cb6758bf011916fefe794 | [
"BaseMeta.__init__(cls, name, bases, attrs)\nfor t in cls._control_types:\n AtspiMeta.control_type_to_cls[t] = cls",
"try:\n wrapper_match = AtspiMeta.control_type_to_cls[element.control_type]\nexcept KeyError:\n wrapper_match = AtspiWrapper\nreturn wrapper_match"
] | <|body_start_0|>
BaseMeta.__init__(cls, name, bases, attrs)
for t in cls._control_types:
AtspiMeta.control_type_to_cls[t] = cls
<|end_body_0|>
<|body_start_1|>
try:
wrapper_match = AtspiMeta.control_type_to_cls[element.control_type]
except KeyError:
w... | Metaclass for AtspiWrapper objects | AtspiMeta | [
"BSD-3-Clause",
"LGPL-2.1-or-later",
"LGPL-2.1-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AtspiMeta:
"""Metaclass for AtspiWrapper objects"""
def __init__(cls, name, bases, attrs):
"""Register the control types"""
<|body_0|>
def find_wrapper(element):
"""Find the correct wrapper for this Atspi element"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_75kplus_train_066526 | 7,489 | permissive | [
{
"docstring": "Register the control types",
"name": "__init__",
"signature": "def __init__(cls, name, bases, attrs)"
},
{
"docstring": "Find the correct wrapper for this Atspi element",
"name": "find_wrapper",
"signature": "def find_wrapper(element)"
}
] | 2 | null | Implement the Python class `AtspiMeta` described below.
Class description:
Metaclass for AtspiWrapper objects
Method signatures and docstrings:
- def __init__(cls, name, bases, attrs): Register the control types
- def find_wrapper(element): Find the correct wrapper for this Atspi element | Implement the Python class `AtspiMeta` described below.
Class description:
Metaclass for AtspiWrapper objects
Method signatures and docstrings:
- def __init__(cls, name, bases, attrs): Register the control types
- def find_wrapper(element): Find the correct wrapper for this Atspi element
<|skeleton|>
class AtspiMeta... | bf7f789d01b7c66ccd0c213db0a029da7e588c9e | <|skeleton|>
class AtspiMeta:
"""Metaclass for AtspiWrapper objects"""
def __init__(cls, name, bases, attrs):
"""Register the control types"""
<|body_0|>
def find_wrapper(element):
"""Find the correct wrapper for this Atspi element"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AtspiMeta:
"""Metaclass for AtspiWrapper objects"""
def __init__(cls, name, bases, attrs):
"""Register the control types"""
BaseMeta.__init__(cls, name, bases, attrs)
for t in cls._control_types:
AtspiMeta.control_type_to_cls[t] = cls
def find_wrapper(element):
... | the_stack_v2_python_sparse | pywinauto/controls/atspiwrapper.py | pywinauto/pywinauto | train | 4,466 |
0c4024cbc3d1cd98b46e76df64f00a2db946348d | [
"if std:\n self.std = True\n self.standardizer = InputStandardizer(stats_dir)\nelse:\n self.std = False\n self.standardizer = None",
"buyerJoints = tf.cast(tf.io.parse_tensor(example['br'], out_type=tf.double), tf.float32)\nleftSellerJoints = tf.cast(tf.io.parse_tensor(example['ls'], out_type=tf.doubl... | <|body_start_0|>
if std:
self.std = True
self.standardizer = InputStandardizer(stats_dir)
else:
self.std = False
self.standardizer = None
<|end_body_0|>
<|body_start_1|>
buyerJoints = tf.cast(tf.io.parse_tensor(example['br'], out_type=tf.double), ... | creates the TF dataset object with batching | DataGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataGenerator:
"""creates the TF dataset object with batching"""
def __init__(self, std, stats_dir):
"""Initializes the DataGenerator Object :param std: standardize data ( bool ) :param stats_dir: Directory to data stats if standardization is enabled"""
<|body_0|>
def de... | stack_v2_sparse_classes_75kplus_train_066527 | 3,659 | no_license | [
{
"docstring": "Initializes the DataGenerator Object :param std: standardize data ( bool ) :param stats_dir: Directory to data stats if standardization is enabled",
"name": "__init__",
"signature": "def __init__(self, std, stats_dir)"
},
{
"docstring": "Deserializes the tensors in parsed example... | 3 | stack_v2_sparse_classes_30k_train_006832 | Implement the Python class `DataGenerator` described below.
Class description:
creates the TF dataset object with batching
Method signatures and docstrings:
- def __init__(self, std, stats_dir): Initializes the DataGenerator Object :param std: standardize data ( bool ) :param stats_dir: Directory to data stats if sta... | Implement the Python class `DataGenerator` described below.
Class description:
creates the TF dataset object with batching
Method signatures and docstrings:
- def __init__(self, std, stats_dir): Initializes the DataGenerator Object :param std: standardize data ( bool ) :param stats_dir: Directory to data stats if sta... | 4ccfa0376f4ff0e6372fccfd695f9ffa71661e11 | <|skeleton|>
class DataGenerator:
"""creates the TF dataset object with batching"""
def __init__(self, std, stats_dir):
"""Initializes the DataGenerator Object :param std: standardize data ( bool ) :param stats_dir: Directory to data stats if standardization is enabled"""
<|body_0|>
def de... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataGenerator:
"""creates the TF dataset object with batching"""
def __init__(self, std, stats_dir):
"""Initializes the DataGenerator Object :param std: standardize data ( bool ) :param stats_dir: Directory to data stats if standardization is enabled"""
if std:
self.std = True... | the_stack_v2_python_sparse | DataUtils/DataGenerator.py | peacekurella/DeepSignal | train | 0 |
0ff5024261af037006235a72cc02bc4e6e1c8a84 | [
"result_set = np.array([])\ndistinct_documents = list(set([(x['year'], x['document_name']) for x in dataset]))\nfor year, document in distinct_documents:\n items = [x['data'] for x in dataset if x['year'] == year and x['document_name'] == document]\n topic_ids = [x['topic_id'] for x in items[0]]\n weights ... | <|body_start_0|>
result_set = np.array([])
distinct_documents = list(set([(x['year'], x['document_name']) for x in dataset]))
for year, document in distinct_documents:
items = [x['data'] for x in dataset if x['year'] == year and x['document_name'] == document]
topic_ids =... | Reduces a composition file by adding all items, i.e. splitted documents or rows in the file, that belongs to the same document into a single items. | CompositionDocumentReducer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompositionDocumentReducer:
"""Reduces a composition file by adding all items, i.e. splitted documents or rows in the file, that belongs to the same document into a single items."""
def compute(self, dataset, threshold=0.0):
"""Compute a new composition data set by an addative reduce... | stack_v2_sparse_classes_75kplus_train_066528 | 13,916 | no_license | [
{
"docstring": "Compute a new composition data set by an addative reduce of all items that belongs to the same document",
"name": "compute",
"signature": "def compute(self, dataset, threshold=0.0)"
},
{
"docstring": "Writes dataset into a semicolon separated UTF-8 encoded text file using regiona... | 2 | stack_v2_sparse_classes_30k_train_000070 | Implement the Python class `CompositionDocumentReducer` described below.
Class description:
Reduces a composition file by adding all items, i.e. splitted documents or rows in the file, that belongs to the same document into a single items.
Method signatures and docstrings:
- def compute(self, dataset, threshold=0.0):... | Implement the Python class `CompositionDocumentReducer` described below.
Class description:
Reduces a composition file by adding all items, i.e. splitted documents or rows in the file, that belongs to the same document into a single items.
Method signatures and docstrings:
- def compute(self, dataset, threshold=0.0):... | 32fc444ed11649a948a7bf59653ec792396f06e3 | <|skeleton|>
class CompositionDocumentReducer:
"""Reduces a composition file by adding all items, i.e. splitted documents or rows in the file, that belongs to the same document into a single items."""
def compute(self, dataset, threshold=0.0):
"""Compute a new composition data set by an addative reduce... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CompositionDocumentReducer:
"""Reduces a composition file by adding all items, i.e. splitted documents or rows in the file, that belongs to the same document into a single items."""
def compute(self, dataset, threshold=0.0):
"""Compute a new composition data set by an addative reduce of all items... | the_stack_v2_python_sparse | pending_deletes/topic_modelling/topic_co_occurrence.py | humlab/text_analytic_tools | train | 2 |
a296af8d86e3b6aa7db445f024db106877d88344 | [
"instance_type = renamed_kwargs('train_instance_type', 'instance_type', kwargs.get('instance_type'), kwargs)\nsuper(XGBoost, self).__init__(entry_point, source_dir, hyperparameters, image_uri=image_uri, **kwargs)\nself.py_version = py_version\nself.framework_version = framework_version\nvalidate_py_version(py_versi... | <|body_start_0|>
instance_type = renamed_kwargs('train_instance_type', 'instance_type', kwargs.get('instance_type'), kwargs)
super(XGBoost, self).__init__(entry_point, source_dir, hyperparameters, image_uri=image_uri, **kwargs)
self.py_version = py_version
self.framework_version = framew... | Handle end-to-end training and deployment of XGBoost booster training. It can also handle training using customer provided XGBoost entry point script. | XGBoost | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XGBoost:
"""Handle end-to-end training and deployment of XGBoost booster training. It can also handle training using customer provided XGBoost entry point script."""
def __init__(self, entry_point: Union[str, PipelineVariable], framework_version: str, source_dir: Optional[Union[str, Pipeline... | stack_v2_sparse_classes_75kplus_train_066529 | 13,656 | permissive | [
{
"docstring": "An estimator that executes an XGBoost-based SageMaker Training Job. The managed XGBoost environment is an Amazon-built Docker container thatexecutes functions defined in the supplied ``entry_point`` Python script. Training is started by calling :meth:`~sagemaker.amazon.estimator.Framework.fit` o... | 4 | stack_v2_sparse_classes_30k_train_005359 | Implement the Python class `XGBoost` described below.
Class description:
Handle end-to-end training and deployment of XGBoost booster training. It can also handle training using customer provided XGBoost entry point script.
Method signatures and docstrings:
- def __init__(self, entry_point: Union[str, PipelineVariabl... | Implement the Python class `XGBoost` described below.
Class description:
Handle end-to-end training and deployment of XGBoost booster training. It can also handle training using customer provided XGBoost entry point script.
Method signatures and docstrings:
- def __init__(self, entry_point: Union[str, PipelineVariabl... | 8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85 | <|skeleton|>
class XGBoost:
"""Handle end-to-end training and deployment of XGBoost booster training. It can also handle training using customer provided XGBoost entry point script."""
def __init__(self, entry_point: Union[str, PipelineVariable], framework_version: str, source_dir: Optional[Union[str, Pipeline... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XGBoost:
"""Handle end-to-end training and deployment of XGBoost booster training. It can also handle training using customer provided XGBoost entry point script."""
def __init__(self, entry_point: Union[str, PipelineVariable], framework_version: str, source_dir: Optional[Union[str, PipelineVariable]]=No... | the_stack_v2_python_sparse | src/sagemaker/xgboost/estimator.py | aws/sagemaker-python-sdk | train | 2,050 |
f7a96f641af5eb425a199375af3eba313aa49914 | [
"res = ['']\nfor c in S:\n if c.isdigit():\n for i in range(len(res)):\n res[i] += c\n else:\n copy = res.copy()\n for i in range(len(res)):\n res[i] += c.lower()\n for i in range(len(copy)):\n copy[i] += c.upper()\n res.extend(copy)\nreturn ... | <|body_start_0|>
res = ['']
for c in S:
if c.isdigit():
for i in range(len(res)):
res[i] += c
else:
copy = res.copy()
for i in range(len(res)):
res[i] += c.lower()
for i in ran... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def letterCasePermutation_best(self, S):
""":type S: str :rtype: List[str]"""
<|body_0|>
def letterCasePermutation_dfs(self, S):
""":type S: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = ['']
for c in ... | stack_v2_sparse_classes_75kplus_train_066530 | 1,585 | no_license | [
{
"docstring": ":type S: str :rtype: List[str]",
"name": "letterCasePermutation_best",
"signature": "def letterCasePermutation_best(self, S)"
},
{
"docstring": ":type S: str :rtype: List[str]",
"name": "letterCasePermutation_dfs",
"signature": "def letterCasePermutation_dfs(self, S)"
}... | 2 | stack_v2_sparse_classes_30k_train_023822 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCasePermutation_best(self, S): :type S: str :rtype: List[str]
- def letterCasePermutation_dfs(self, S): :type S: str :rtype: List[str] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCasePermutation_best(self, S): :type S: str :rtype: List[str]
- def letterCasePermutation_dfs(self, S): :type S: str :rtype: List[str]
<|skeleton|>
class Solution:
... | b925bb22d1daa4a56c5a238a5758a926905559b4 | <|skeleton|>
class Solution:
def letterCasePermutation_best(self, S):
""":type S: str :rtype: List[str]"""
<|body_0|>
def letterCasePermutation_dfs(self, S):
""":type S: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def letterCasePermutation_best(self, S):
""":type S: str :rtype: List[str]"""
res = ['']
for c in S:
if c.isdigit():
for i in range(len(res)):
res[i] += c
else:
copy = res.copy()
for i... | the_stack_v2_python_sparse | String/784. Letter Case Permutation.py | beninghton/notGivenUpToG | train | 0 | |
5ab2a666d8f8fe77825ac78661aeb01c55643553 | [
"assert len(input_domain) != 0\nself.lbs = input_domain[0]\nself.ubs = input_domain[1]\nself.set_type = set_type\nself.construct_input()\nself.unsafe_domains = unsafe_output_domains\nself.input_ranges = input_ranges",
"if self.set_type == 'FVIM':\n box = CubeDomain(self.lbs, self.ubs)\n self.input_set = box... | <|body_start_0|>
assert len(input_domain) != 0
self.lbs = input_domain[0]
self.ubs = input_domain[1]
self.set_type = set_type
self.construct_input()
self.unsafe_domains = unsafe_output_domains
self.input_ranges = input_ranges
<|end_body_0|>
<|body_start_1|>
... | A class for the safety property of a neural network Attributes: lbs (list): Lower bound of the input domain ubs (list): Upper bound of the input domain set_type (str): Name of the set representation input_set (FVIM or Flattice): Input set constructed by a set representation unsafe_domains (list): A set of unsafe output... | Property | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Property:
"""A class for the safety property of a neural network Attributes: lbs (list): Lower bound of the input domain ubs (list): Upper bound of the input domain set_type (str): Name of the set representation input_set (FVIM or Flattice): Input set constructed by a set representation unsafe_do... | stack_v2_sparse_classes_75kplus_train_066531 | 2,398 | permissive | [
{
"docstring": "Construct the attributes for a Property object Parameters: input_domain (list): Lower and Upper bounds of the input domain unsafe_output_domains (list): Unsafe output domains using sets of linear inequalities input_ranges (list): Entire input range to the network set_type (str): Name of the set ... | 2 | stack_v2_sparse_classes_30k_train_006233 | Implement the Python class `Property` described below.
Class description:
A class for the safety property of a neural network Attributes: lbs (list): Lower bound of the input domain ubs (list): Upper bound of the input domain set_type (str): Name of the set representation input_set (FVIM or Flattice): Input set constr... | Implement the Python class `Property` described below.
Class description:
A class for the safety property of a neural network Attributes: lbs (list): Lower bound of the input domain ubs (list): Upper bound of the input domain set_type (str): Name of the set representation input_set (FVIM or Flattice): Input set constr... | 38a25dba5941afb1ec2557c671e9bca362831274 | <|skeleton|>
class Property:
"""A class for the safety property of a neural network Attributes: lbs (list): Lower bound of the input domain ubs (list): Upper bound of the input domain set_type (str): Name of the set representation input_set (FVIM or Flattice): Input set constructed by a set representation unsafe_do... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Property:
"""A class for the safety property of a neural network Attributes: lbs (list): Lower bound of the input domain ubs (list): Upper bound of the input domain set_type (str): Name of the set representation input_set (FVIM or Flattice): Input set constructed by a set representation unsafe_domains (list):... | the_stack_v2_python_sparse | veritex/utils/sfproperty.py | Shaddadi/veritex | train | 10 |
b5834add7209c23a7d40e73a769ef0ec463deeca | [
"with open(certfile, 'rb') as fp:\n certificates = load_pem_x509_certificates(fp.read())\nself.certificate = certificates[0]\nself.certificate_chain = certificates[1:]\nif keyfile is not None:\n with open(keyfile, 'rb') as fp:\n self.private_key = load_pem_private_key(fp.read(), password=password.encod... | <|body_start_0|>
with open(certfile, 'rb') as fp:
certificates = load_pem_x509_certificates(fp.read())
self.certificate = certificates[0]
self.certificate_chain = certificates[1:]
if keyfile is not None:
with open(keyfile, 'rb') as fp:
self.private... | A QUIC configuration. | QuicConfiguration | [
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuicConfiguration:
"""A QUIC configuration."""
def load_cert_chain(self, certfile: PathLike, keyfile: Optional[PathLike]=None, password: Optional[Union[bytes, str]]=None) -> None:
"""Load a private key and the corresponding certificate."""
<|body_0|>
def load_verify_loca... | stack_v2_sparse_classes_75kplus_train_066532 | 3,388 | permissive | [
{
"docstring": "Load a private key and the corresponding certificate.",
"name": "load_cert_chain",
"signature": "def load_cert_chain(self, certfile: PathLike, keyfile: Optional[PathLike]=None, password: Optional[Union[bytes, str]]=None) -> None"
},
{
"docstring": "Load a set of \"certification a... | 2 | stack_v2_sparse_classes_30k_train_041922 | Implement the Python class `QuicConfiguration` described below.
Class description:
A QUIC configuration.
Method signatures and docstrings:
- def load_cert_chain(self, certfile: PathLike, keyfile: Optional[PathLike]=None, password: Optional[Union[bytes, str]]=None) -> None: Load a private key and the corresponding cer... | Implement the Python class `QuicConfiguration` described below.
Class description:
A QUIC configuration.
Method signatures and docstrings:
- def load_cert_chain(self, certfile: PathLike, keyfile: Optional[PathLike]=None, password: Optional[Union[bytes, str]]=None) -> None: Load a private key and the corresponding cer... | 64bee65c921db7e78e25d08f1e98da2668b57be5 | <|skeleton|>
class QuicConfiguration:
"""A QUIC configuration."""
def load_cert_chain(self, certfile: PathLike, keyfile: Optional[PathLike]=None, password: Optional[Union[bytes, str]]=None) -> None:
"""Load a private key and the corresponding certificate."""
<|body_0|>
def load_verify_loca... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QuicConfiguration:
"""A QUIC configuration."""
def load_cert_chain(self, certfile: PathLike, keyfile: Optional[PathLike]=None, password: Optional[Union[bytes, str]]=None) -> None:
"""Load a private key and the corresponding certificate."""
with open(certfile, 'rb') as fp:
cert... | the_stack_v2_python_sparse | third_party/blink/web_tests/external/wpt/tools/third_party/aioquic/src/aioquic/quic/configuration.py | otcshare/chromium-src | train | 18 |
9c5ef105875d8ad12fa8b01fd1b8fd98c6422413 | [
"self.parameters = ['solution', 'n_total', 'levels', 'n_level', 'mean_level', 'var_level', 'cost_per_sample', 'alpha', 'beta', 'gamma']\nself.stopping_crit = stopping_crit\nself.integrand = integrand\nself.true_measure = true_measure\nself.discrete_distrib = discrete_distrib\nself.levels = int(levels_init)\nself.n_... | <|body_start_0|>
self.parameters = ['solution', 'n_total', 'levels', 'n_level', 'mean_level', 'var_level', 'cost_per_sample', 'alpha', 'beta', 'gamma']
self.stopping_crit = stopping_crit
self.integrand = integrand
self.true_measure = true_measure
self.discrete_distrib = discrete_... | Accumulated data for IIDDistribution calculations, and store multi-level mean, variance, and cost values. See the stopping criterion that utilize this object for references. | MLMCData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLMCData:
"""Accumulated data for IIDDistribution calculations, and store multi-level mean, variance, and cost values. See the stopping criterion that utilize this object for references."""
def __init__(self, stopping_crit, integrand, true_measure, discrete_distrib, levels_init, n_init, alph... | stack_v2_sparse_classes_75kplus_train_066533 | 5,331 | permissive | [
{
"docstring": "Initialize data instance Args: stopping_crit (StoppingCriterion): a StoppingCriterion instance integrand (Integrand): an Integrand instance true_measure (TrueMeasure): A TrueMeasure instance discrete_distrib (DiscreteDistribution): a DiscreteDistribution instance levels_init (int): initial numbe... | 3 | stack_v2_sparse_classes_30k_train_032370 | Implement the Python class `MLMCData` described below.
Class description:
Accumulated data for IIDDistribution calculations, and store multi-level mean, variance, and cost values. See the stopping criterion that utilize this object for references.
Method signatures and docstrings:
- def __init__(self, stopping_crit, ... | Implement the Python class `MLMCData` described below.
Class description:
Accumulated data for IIDDistribution calculations, and store multi-level mean, variance, and cost values. See the stopping criterion that utilize this object for references.
Method signatures and docstrings:
- def __init__(self, stopping_crit, ... | 96af0449bafe027191f9d976ceef47557b0127d4 | <|skeleton|>
class MLMCData:
"""Accumulated data for IIDDistribution calculations, and store multi-level mean, variance, and cost values. See the stopping criterion that utilize this object for references."""
def __init__(self, stopping_crit, integrand, true_measure, discrete_distrib, levels_init, n_init, alph... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MLMCData:
"""Accumulated data for IIDDistribution calculations, and store multi-level mean, variance, and cost values. See the stopping criterion that utilize this object for references."""
def __init__(self, stopping_crit, integrand, true_measure, discrete_distrib, levels_init, n_init, alpha0, beta0, ga... | the_stack_v2_python_sparse | qmcpy/accumulate_data/mlmc_data.py | QMCSoftware/QMCSoftware | train | 54 |
a64e7210b5ff743d9436c637ae933bc1ca56e0eb | [
"super().__init__(raster_mode, dwell_time, total_time, dwell_time_live)\nself.step_count_x = step_count_x\nself.step_count_y = step_count_y\nself.step_size_x = step_size_x\nself.step_size_y = step_size_y\nself.frame_count = frame_count\nself.position = position",
"try:\n location = next(iter(self.positions.key... | <|body_start_0|>
super().__init__(raster_mode, dwell_time, total_time, dwell_time_live)
self.step_count_x = step_count_x
self.step_count_y = step_count_y
self.step_size_x = step_size_x
self.step_size_y = step_size_y
self.frame_count = frame_count
self.position = p... | AcquisitionRasterXY | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AcquisitionRasterXY:
def __init__(self, step_count_x, step_count_y, step_size_x=None, step_size_y=None, frame_count=None, position=None, raster_mode=None, dwell_time=None, total_time=None, dwell_time_live=None):
"""Defines the position and duration of a two-dimensional X/Y raster over th... | stack_v2_sparse_classes_75kplus_train_066534 | 15,189 | permissive | [
{
"docstring": "Defines the position and duration of a two-dimensional X/Y raster over the specimen. :arg step_count_x: number of steps in x direction (required) :arg step_count_y: number of steps in y direction (required) :arg step_size_x: dimension of each step in x direction (optional) :arg step_size_y: dime... | 3 | stack_v2_sparse_classes_30k_val_000033 | Implement the Python class `AcquisitionRasterXY` described below.
Class description:
Implement the AcquisitionRasterXY class.
Method signatures and docstrings:
- def __init__(self, step_count_x, step_count_y, step_size_x=None, step_size_y=None, frame_count=None, position=None, raster_mode=None, dwell_time=None, total... | Implement the Python class `AcquisitionRasterXY` described below.
Class description:
Implement the AcquisitionRasterXY class.
Method signatures and docstrings:
- def __init__(self, step_count_x, step_count_y, step_size_x=None, step_size_y=None, frame_count=None, position=None, raster_mode=None, dwell_time=None, total... | 0081ea29127c72e8a0511a9f8fc58d0fe098b801 | <|skeleton|>
class AcquisitionRasterXY:
def __init__(self, step_count_x, step_count_y, step_size_x=None, step_size_y=None, frame_count=None, position=None, raster_mode=None, dwell_time=None, total_time=None, dwell_time_live=None):
"""Defines the position and duration of a two-dimensional X/Y raster over th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AcquisitionRasterXY:
def __init__(self, step_count_x, step_count_y, step_size_x=None, step_size_y=None, frame_count=None, position=None, raster_mode=None, dwell_time=None, total_time=None, dwell_time_live=None):
"""Defines the position and duration of a two-dimensional X/Y raster over the specimen. :a... | the_stack_v2_python_sparse | pyhmsa/spec/condition/acquisition.py | pyhmsa/pyhmsa | train | 2 | |
fd6a25be8769a87cba91ef545ca2d0b044f5070c | [
"all_user_plans = WorkoutPlan.objects.filter(owner=user)\nplan_names = []\nplan_ids = []\nfor plan in all_user_plans:\n plan_ids.append(plan.id)\n plan_names.append(plan.name)\nresult = tuple(zip(plan_ids, plan_names))\nreturn result",
"plans = SelectActivePlanView.get_user_plans(request.user)\nform = self.... | <|body_start_0|>
all_user_plans = WorkoutPlan.objects.filter(owner=user)
plan_names = []
plan_ids = []
for plan in all_user_plans:
plan_ids.append(plan.id)
plan_names.append(plan.name)
result = tuple(zip(plan_ids, plan_names))
return result
<|end_b... | The class view for selecting an active workout plan | SelectActivePlanView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelectActivePlanView:
"""The class view for selecting an active workout plan"""
def get_user_plans(user):
"""Get all training plans belonging to the current user. :param user: current user :return: a tuple of paired workout plan ids with workout plan names :rtype: tuple[tuple[int, st... | stack_v2_sparse_classes_75kplus_train_066535 | 34,014 | no_license | [
{
"docstring": "Get all training plans belonging to the current user. :param user: current user :return: a tuple of paired workout plan ids with workout plan names :rtype: tuple[tuple[int, str]]",
"name": "get_user_plans",
"signature": "def get_user_plans(user)"
},
{
"docstring": "Display the fo... | 3 | null | Implement the Python class `SelectActivePlanView` described below.
Class description:
The class view for selecting an active workout plan
Method signatures and docstrings:
- def get_user_plans(user): Get all training plans belonging to the current user. :param user: current user :return: a tuple of paired workout pla... | Implement the Python class `SelectActivePlanView` described below.
Class description:
The class view for selecting an active workout plan
Method signatures and docstrings:
- def get_user_plans(user): Get all training plans belonging to the current user. :param user: current user :return: a tuple of paired workout pla... | b6100d4082c197bc7b40bac27a9b8f07f8efcd84 | <|skeleton|>
class SelectActivePlanView:
"""The class view for selecting an active workout plan"""
def get_user_plans(user):
"""Get all training plans belonging to the current user. :param user: current user :return: a tuple of paired workout plan ids with workout plan names :rtype: tuple[tuple[int, st... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SelectActivePlanView:
"""The class view for selecting an active workout plan"""
def get_user_plans(user):
"""Get all training plans belonging to the current user. :param user: current user :return: a tuple of paired workout plan ids with workout plan names :rtype: tuple[tuple[int, str]]"""
... | the_stack_v2_python_sparse | RunScheduleApp/views.py | Gribek/RunSchedules | train | 0 |
be3b9577c8b40430fbdfcedbf79d3b2de7aa95af | [
"if not isinstance(parser, SAMLMetadataParser):\n raise ValueError(\"Argument 'parser' must be an instance of {0} class\".format(SAMLMetadataParser))\nself._parser = parser",
"if not issubclass(configuration_grouping_class, SAMLConfiguration):\n raise ValueError(\"Argument 'configuration_grouping_class' mus... | <|body_start_0|>
if not isinstance(parser, SAMLMetadataParser):
raise ValueError("Argument 'parser' must be an instance of {0} class".format(SAMLMetadataParser))
self._parser = parser
<|end_body_0|>
<|body_start_1|>
if not issubclass(configuration_grouping_class, SAMLConfiguration):... | Factory creating new instances of SAMLConfiguration class. | SAMLConfigurationFactory | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SAMLConfigurationFactory:
"""Factory creating new instances of SAMLConfiguration class."""
def __init__(self, parser):
"""Initialize a new instance of SAMLConfigurationFactory class. :param parser: SAMLMetadataParser object :type parser: api.saml.metadata.parser.SAMLMetadataParser"""... | stack_v2_sparse_classes_75kplus_train_066536 | 26,438 | permissive | [
{
"docstring": "Initialize a new instance of SAMLConfigurationFactory class. :param parser: SAMLMetadataParser object :type parser: api.saml.metadata.parser.SAMLMetadataParser",
"name": "__init__",
"signature": "def __init__(self, parser)"
},
{
"docstring": "Create a new instance of SAMLConfigur... | 2 | stack_v2_sparse_classes_30k_train_036773 | Implement the Python class `SAMLConfigurationFactory` described below.
Class description:
Factory creating new instances of SAMLConfiguration class.
Method signatures and docstrings:
- def __init__(self, parser): Initialize a new instance of SAMLConfigurationFactory class. :param parser: SAMLMetadataParser object :ty... | Implement the Python class `SAMLConfigurationFactory` described below.
Class description:
Factory creating new instances of SAMLConfiguration class.
Method signatures and docstrings:
- def __init__(self, parser): Initialize a new instance of SAMLConfigurationFactory class. :param parser: SAMLMetadataParser object :ty... | 662cc7e0721d0153857c8c17a37e2a6df86f8ce6 | <|skeleton|>
class SAMLConfigurationFactory:
"""Factory creating new instances of SAMLConfiguration class."""
def __init__(self, parser):
"""Initialize a new instance of SAMLConfigurationFactory class. :param parser: SAMLMetadataParser object :type parser: api.saml.metadata.parser.SAMLMetadataParser"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SAMLConfigurationFactory:
"""Factory creating new instances of SAMLConfiguration class."""
def __init__(self, parser):
"""Initialize a new instance of SAMLConfigurationFactory class. :param parser: SAMLMetadataParser object :type parser: api.saml.metadata.parser.SAMLMetadataParser"""
if n... | the_stack_v2_python_sparse | api/saml/configuration/model.py | NYPL-Simplified/circulation | train | 20 |
3812ef8d9bd325f3be38b14ec3e217f09829d8ae | [
"self._server = server\nself._usr = bind_dn\nself._pwd = bind_password",
"self._server = Server(app.config['LDAP_HOST'], use_ssl=True)\nself._base_search = app.config['LDAP_BASE_SEARCH']\nself._usr = app.config['LDAP_BIND_DN']\nself._pwd = app.config['LDAP_BIND_PASSWD']",
"u = 'uid=%s,ou=People,' % username + s... | <|body_start_0|>
self._server = server
self._usr = bind_dn
self._pwd = bind_password
<|end_body_0|>
<|body_start_1|>
self._server = Server(app.config['LDAP_HOST'], use_ssl=True)
self._base_search = app.config['LDAP_BASE_SEARCH']
self._usr = app.config['LDAP_BIND_DN']
... | simple ldap client for dce ldap server. assumes that anonymous connection is _never_ done! assumes that init_app() is called before any search or other call to ldap server. | LdapClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LdapClient:
"""simple ldap client for dce ldap server. assumes that anonymous connection is _never_ done! assumes that init_app() is called before any search or other call to ldap server."""
def __init__(self, server=None, bind_dn=None, bind_password=None):
"""create instance."""
... | stack_v2_sparse_classes_75kplus_train_066537 | 2,134 | permissive | [
{
"docstring": "create instance.",
"name": "__init__",
"signature": "def __init__(self, server=None, bind_dn=None, bind_password=None)"
},
{
"docstring": "init ldap client instance, with configs from app.",
"name": "init_app",
"signature": "def init_app(self, app)"
},
{
"docstrin... | 4 | stack_v2_sparse_classes_30k_train_047654 | Implement the Python class `LdapClient` described below.
Class description:
simple ldap client for dce ldap server. assumes that anonymous connection is _never_ done! assumes that init_app() is called before any search or other call to ldap server.
Method signatures and docstrings:
- def __init__(self, server=None, b... | Implement the Python class `LdapClient` described below.
Class description:
simple ldap client for dce ldap server. assumes that anonymous connection is _never_ done! assumes that init_app() is called before any search or other call to ldap server.
Method signatures and docstrings:
- def __init__(self, server=None, b... | 10300ca4ce097d8a633612554d257b939633eeae | <|skeleton|>
class LdapClient:
"""simple ldap client for dce ldap server. assumes that anonymous connection is _never_ done! assumes that init_app() is called before any search or other call to ldap server."""
def __init__(self, server=None, bind_dn=None, bind_password=None):
"""create instance."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LdapClient:
"""simple ldap client for dce ldap server. assumes that anonymous connection is _never_ done! assumes that init_app() is called before any search or other call to ldap server."""
def __init__(self, server=None, bind_dn=None, bind_password=None):
"""create instance."""
self._se... | the_stack_v2_python_sparse | cadash/ldap.py | harvard-dce/cadash | train | 0 |
6bfc3df9cd85238f9349ba18a40c13e69d9dd18e | [
"self._verbose = verbose\nself._reader = codecs.getreader('utf-8')\nself._dirstack = list()\nself._dirstack.append(('root', root_path if root_path else ''))",
"_, parent = self._dirstack[-1]\neffective_url = urljoin(parent, json_resource) if parent else json_resource\ntry:\n if effective_url.startswith('file:/... | <|body_start_0|>
self._verbose = verbose
self._reader = codecs.getreader('utf-8')
self._dirstack = list()
self._dirstack.append(('root', root_path if root_path else ''))
<|end_body_0|>
<|body_start_1|>
_, parent = self._dirstack[-1]
effective_url = urljoin(parent, json_r... | This loader can be used to load a JSON resource identified by URL and file path. It also maintains a directory stack so that nested templates can be loaded by relative paths. | DefaultJsonLoader | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefaultJsonLoader:
"""This loader can be used to load a JSON resource identified by URL and file path. It also maintains a directory stack so that nested templates can be loaded by relative paths."""
def __init__(self, root_path=None, verbose=False):
"""Construct a default loader. :p... | stack_v2_sparse_classes_75kplus_train_066538 | 3,772 | permissive | [
{
"docstring": "Construct a default loader. :param root_path: The root port of a URL or file path. :type root_path: 'str' :param verbose: Print more info if true. :type verbose: 'bool'",
"name": "__init__",
"signature": "def __init__(self, root_path=None, verbose=False)"
},
{
"docstring": "Load ... | 3 | stack_v2_sparse_classes_30k_train_035290 | Implement the Python class `DefaultJsonLoader` described below.
Class description:
This loader can be used to load a JSON resource identified by URL and file path. It also maintains a directory stack so that nested templates can be loaded by relative paths.
Method signatures and docstrings:
- def __init__(self, root_... | Implement the Python class `DefaultJsonLoader` described below.
Class description:
This loader can be used to load a JSON resource identified by URL and file path. It also maintains a directory stack so that nested templates can be loaded by relative paths.
Method signatures and docstrings:
- def __init__(self, root_... | 29c12c90edb0801d2319d4b85f445b2e08e580fa | <|skeleton|>
class DefaultJsonLoader:
"""This loader can be used to load a JSON resource identified by URL and file path. It also maintains a directory stack so that nested templates can be loaded by relative paths."""
def __init__(self, root_path=None, verbose=False):
"""Construct a default loader. :p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DefaultJsonLoader:
"""This loader can be used to load a JSON resource identified by URL and file path. It also maintains a directory stack so that nested templates can be loaded by relative paths."""
def __init__(self, root_path=None, verbose=False):
"""Construct a default loader. :param root_pat... | the_stack_v2_python_sparse | templating/core/src/main/python/jsonteng/json_loader.py | vmware/json-template-engine | train | 35 |
863777be6a8136dd8144abda04eea8a9265533b8 | [
"if not data:\n return b'\\x00' * size if size else b'\\x00'\nif size and len(data) < size:\n data.extend(['' for _ in range(size - len(data))])\nif size and len(data) > size:\n data = data[:size]\nreturn b'\\x00'.join([d.replace('\\x00', '').encode('utf-8') for d in data]) + b'\\x00'",
"if size:\n tm... | <|body_start_0|>
if not data:
return b'\x00' * size if size else b'\x00'
if size and len(data) < size:
data.extend(['' for _ in range(size - len(data))])
if size and len(data) > size:
data = data[:size]
return b'\x00'.join([d.replace('\x00', '').encode... | List of null terminated string | SMPayloadTypeNTLIST | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SMPayloadTypeNTLIST:
"""List of null terminated string"""
def encode(data, size=None):
"""Encode list of unicode string into null terminated strings. :param data: the list to encode :param size: Size of the list :Example: >>> SMPayloadTypeNTLIST.encode(["string1", "string2"], 2) b'st... | stack_v2_sparse_classes_75kplus_train_066539 | 14,049 | permissive | [
{
"docstring": "Encode list of unicode string into null terminated strings. :param data: the list to encode :param size: Size of the list :Example: >>> SMPayloadTypeNTLIST.encode([\"string1\", \"string2\"], 2) b'string1\\\\x00string2\\\\x00' >>> # zero padding >>> SMPayloadTypeNTLIST.encode([\"string1\", \"stri... | 2 | stack_v2_sparse_classes_30k_train_014425 | Implement the Python class `SMPayloadTypeNTLIST` described below.
Class description:
List of null terminated string
Method signatures and docstrings:
- def encode(data, size=None): Encode list of unicode string into null terminated strings. :param data: the list to encode :param size: Size of the list :Example: >>> S... | Implement the Python class `SMPayloadTypeNTLIST` described below.
Class description:
List of null terminated string
Method signatures and docstrings:
- def encode(data, size=None): Encode list of unicode string into null terminated strings. :param data: the list to encode :param size: Size of the list :Example: >>> S... | cf20b363ed3d7bcb75101b17870e876a857ecd66 | <|skeleton|>
class SMPayloadTypeNTLIST:
"""List of null terminated string"""
def encode(data, size=None):
"""Encode list of unicode string into null terminated strings. :param data: the list to encode :param size: Size of the list :Example: >>> SMPayloadTypeNTLIST.encode(["string1", "string2"], 2) b'st... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SMPayloadTypeNTLIST:
"""List of null terminated string"""
def encode(data, size=None):
"""Encode list of unicode string into null terminated strings. :param data: the list to encode :param size: Size of the list :Example: >>> SMPayloadTypeNTLIST.encode(["string1", "string2"], 2) b'string1\\x00str... | the_stack_v2_python_sparse | smserver/smutils/smpacket/smencoder.py | Moutix/stepmania-server | train | 4 |
e27b225477ead1c2cd6dc3007e994ce554e743c2 | [
"super(MultiHeadAttention, self).__init__()\nassert d_model % n_head == 0, 'Should always have d_model % n_head = 0.'\nassert d_k == d_v, 'Should always have d_k == d_v.'\nself.n_head = n_head\nself.d_k = d_k\nself.d_v = d_v\nself.w_qs = nn.Linear(d_model, n_head * d_k)\nself.w_ks = nn.Linear(d_model, n_head * d_k)... | <|body_start_0|>
super(MultiHeadAttention, self).__init__()
assert d_model % n_head == 0, 'Should always have d_model % n_head = 0.'
assert d_k == d_v, 'Should always have d_k == d_v.'
self.n_head = n_head
self.d_k = d_k
self.d_v = d_v
self.w_qs = nn.Linear(d_mode... | Implements multi-head attention. Allows the model to jointly attend to information from different representation subspaces at different positions. The implementation is: .. math:: MultiHead(Q, K, V) = Concat(head_1, \\ldots, head_h) \\cdot W^O Where:\\ head_i = Attention(Q \\cdot W^Q_i, K \\cdot W^K_i, V \\cdot W^V_i) ... | MultiHeadAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadAttention:
"""Implements multi-head attention. Allows the model to jointly attend to information from different representation subspaces at different positions. The implementation is: .. math:: MultiHead(Q, K, V) = Concat(head_1, \\ldots, head_h) \\cdot W^O Where:\\ head_i = Attention(Q ... | stack_v2_sparse_classes_75kplus_train_066540 | 7,565 | no_license | [
{
"docstring": "Constructor for the ``MultiHeadAttention`` class. :param n_head: number of heads to use (recommended: 8). :param d_model: dimension of the output vectors (should be 512). :param d_k: Dimensionality of each key / query (Should correspond to d_model / n_head). :param d_v: Dimensionality of each va... | 2 | stack_v2_sparse_classes_30k_train_039883 | Implement the Python class `MultiHeadAttention` described below.
Class description:
Implements multi-head attention. Allows the model to jointly attend to information from different representation subspaces at different positions. The implementation is: .. math:: MultiHead(Q, K, V) = Concat(head_1, \\ldots, head_h) \\... | Implement the Python class `MultiHeadAttention` described below.
Class description:
Implements multi-head attention. Allows the model to jointly attend to information from different representation subspaces at different positions. The implementation is: .. math:: MultiHead(Q, K, V) = Concat(head_1, \\ldots, head_h) \\... | 6be6d8d181457a9306b751de4c92b9ae844cdda0 | <|skeleton|>
class MultiHeadAttention:
"""Implements multi-head attention. Allows the model to jointly attend to information from different representation subspaces at different positions. The implementation is: .. math:: MultiHead(Q, K, V) = Concat(head_1, \\ldots, head_h) \\cdot W^O Where:\\ head_i = Attention(Q ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiHeadAttention:
"""Implements multi-head attention. Allows the model to jointly attend to information from different representation subspaces at different positions. The implementation is: .. math:: MultiHead(Q, K, V) = Concat(head_1, \\ldots, head_h) \\cdot W^O Where:\\ head_i = Attention(Q \\cdot W^Q_i,... | the_stack_v2_python_sparse | transformer/attention.py | AlexisDrch/Transformer | train | 2 |
d4a4cf91e3256e2f1ea95f56e356310efcd19c50 | [
"re = cloudparking_service().mockCarInOut(send_data['carNum'], 0, send_data['inClientID'])\nresult = re\nAssertions().assert_in_text(result, expect['mockCarInMsg'])",
"re = CarInOutHandle(sentryLogin).carInOutHandle(send_data['carNum'], send_data['carInHandleType'], send_data['carIn_jobId'])\nresult = re\nAsserti... | <|body_start_0|>
re = cloudparking_service().mockCarInOut(send_data['carNum'], 0, send_data['inClientID'])
result = re
Assertions().assert_in_text(result, expect['mockCarInMsg'])
<|end_body_0|>
<|body_start_1|>
re = CarInOutHandle(sentryLogin).carInOutHandle(send_data['carNum'], send_da... | 岗亭收费处查看历史消息 | TestCheckHistoryMsg | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCheckHistoryMsg:
"""岗亭收费处查看历史消息"""
def test_mockCarIn(self, sentryLogin, send_data, expect):
"""模拟车辆进场"""
<|body_0|>
def test_checkCarIn(self, sentryLogin, send_data, expect):
"""岗亭端登记放入"""
<|body_1|>
def test_checkHandleInHistoryMsg(self, sentry... | stack_v2_sparse_classes_75kplus_train_066541 | 2,987 | no_license | [
{
"docstring": "模拟车辆进场",
"name": "test_mockCarIn",
"signature": "def test_mockCarIn(self, sentryLogin, send_data, expect)"
},
{
"docstring": "岗亭端登记放入",
"name": "test_checkCarIn",
"signature": "def test_checkCarIn(self, sentryLogin, send_data, expect)"
},
{
"docstring": "岗亭端查看单条记录... | 6 | stack_v2_sparse_classes_30k_train_006770 | Implement the Python class `TestCheckHistoryMsg` described below.
Class description:
岗亭收费处查看历史消息
Method signatures and docstrings:
- def test_mockCarIn(self, sentryLogin, send_data, expect): 模拟车辆进场
- def test_checkCarIn(self, sentryLogin, send_data, expect): 岗亭端登记放入
- def test_checkHandleInHistoryMsg(self, sentryLogi... | Implement the Python class `TestCheckHistoryMsg` described below.
Class description:
岗亭收费处查看历史消息
Method signatures and docstrings:
- def test_mockCarIn(self, sentryLogin, send_data, expect): 模拟车辆进场
- def test_checkCarIn(self, sentryLogin, send_data, expect): 岗亭端登记放入
- def test_checkHandleInHistoryMsg(self, sentryLogi... | 34c368c109867da26d9256bca85f872b0fac2ea7 | <|skeleton|>
class TestCheckHistoryMsg:
"""岗亭收费处查看历史消息"""
def test_mockCarIn(self, sentryLogin, send_data, expect):
"""模拟车辆进场"""
<|body_0|>
def test_checkCarIn(self, sentryLogin, send_data, expect):
"""岗亭端登记放入"""
<|body_1|>
def test_checkHandleInHistoryMsg(self, sentry... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestCheckHistoryMsg:
"""岗亭收费处查看历史消息"""
def test_mockCarIn(self, sentryLogin, send_data, expect):
"""模拟车辆进场"""
re = cloudparking_service().mockCarInOut(send_data['carNum'], 0, send_data['inClientID'])
result = re
Assertions().assert_in_text(result, expect['mockCarInMsg'])
... | the_stack_v2_python_sparse | test_suite/sentryDutyRoom/carInOutHandle/test_checkHistoryMsg.py | oyebino/pomp_api | train | 1 |
e231cf88bfa77f919e2a3ddec66f84a23fb318af | [
"if self.accepted or self.revoked:\n raise ShareContractCannotBeAccepted()\nself.accepted = True\nself.save()\nshare_contract_accepted.send(sender=self.__class__, share_contract=self)",
"if self.accepted or self.revoked:\n raise ShareContractCannotBeDeclined()\nself.delete()",
"if not self.accepted:\n ... | <|body_start_0|>
if self.accepted or self.revoked:
raise ShareContractCannotBeAccepted()
self.accepted = True
self.save()
share_contract_accepted.send(sender=self.__class__, share_contract=self)
<|end_body_0|>
<|body_start_1|>
if self.accepted or self.revoked:
... | ShareContract Workflow: -> Create self.accepted = False self.revoked = False -> Accept self.accepted = True self.revoked = False -> Revoke self.accepted = True self.revoked = True -> Delete -> Decline -> Delete | ShareContract | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShareContract:
"""ShareContract Workflow: -> Create self.accepted = False self.revoked = False -> Accept self.accepted = True self.revoked = False -> Revoke self.accepted = True self.revoked = True -> Delete -> Decline -> Delete"""
def accept(self):
"""Accept this share contract"""
... | stack_v2_sparse_classes_75kplus_train_066542 | 5,221 | permissive | [
{
"docstring": "Accept this share contract",
"name": "accept",
"signature": "def accept(self)"
},
{
"docstring": "Decline this share contract",
"name": "decline",
"signature": "def decline(self)"
},
{
"docstring": "Revoke this share contract",
"name": "revoke",
"signature... | 3 | null | Implement the Python class `ShareContract` described below.
Class description:
ShareContract Workflow: -> Create self.accepted = False self.revoked = False -> Accept self.accepted = True self.revoked = False -> Revoke self.accepted = True self.revoked = True -> Delete -> Decline -> Delete
Method signatures and docstr... | Implement the Python class `ShareContract` described below.
Class description:
ShareContract Workflow: -> Create self.accepted = False self.revoked = False -> Accept self.accepted = True self.revoked = False -> Revoke self.accepted = True self.revoked = True -> Delete -> Decline -> Delete
Method signatures and docstr... | e448729b6050f67f64606497a14236b282d25fda | <|skeleton|>
class ShareContract:
"""ShareContract Workflow: -> Create self.accepted = False self.revoked = False -> Accept self.accepted = True self.revoked = False -> Revoke self.accepted = True self.revoked = True -> Delete -> Decline -> Delete"""
def accept(self):
"""Accept this share contract"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ShareContract:
"""ShareContract Workflow: -> Create self.accepted = False self.revoked = False -> Accept self.accepted = True self.revoked = False -> Revoke self.accepted = True self.revoked = True -> Delete -> Decline -> Delete"""
def accept(self):
"""Accept this share contract"""
if sel... | the_stack_v2_python_sparse | categories/models.py | joeig/memodrop | train | 19 |
41f8c7ff6393be932c3033fddd821c8b11a77842 | [
"course_run = CourseRunFactory.create(course__program__financial_aid_availability=True, course__program__live=True)\ncourse = course_run.course\nProgramEnrollment.objects.create(program=course.program, user=user)\ncoupon1_auto = CouponFactory.create(coupon_type=Coupon.DISCOUNTED_PREVIOUS_COURSE, content_object=cour... | <|body_start_0|>
course_run = CourseRunFactory.create(course__program__financial_aid_availability=True, course__program__live=True)
course = course_run.course
ProgramEnrollment.objects.create(program=course.program, user=user)
coupon1_auto = CouponFactory.create(coupon_type=Coupon.DISCOU... | Tests for pick_coupon | PickCouponTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PickCouponTests:
"""Tests for pick_coupon"""
def _create_coupons(cls, user):
"""Create some coupons"""
<|body_0|>
def setUpTestData(cls):
"""Set up some coupons"""
<|body_1|>
def test_pick_coupon(self):
"""Tests for happy case"""
<|bo... | stack_v2_sparse_classes_75kplus_train_066543 | 41,111 | permissive | [
{
"docstring": "Create some coupons",
"name": "_create_coupons",
"signature": "def _create_coupons(cls, user)"
},
{
"docstring": "Set up some coupons",
"name": "setUpTestData",
"signature": "def setUpTestData(cls)"
},
{
"docstring": "Tests for happy case",
"name": "test_pick_... | 5 | stack_v2_sparse_classes_30k_train_008041 | Implement the Python class `PickCouponTests` described below.
Class description:
Tests for pick_coupon
Method signatures and docstrings:
- def _create_coupons(cls, user): Create some coupons
- def setUpTestData(cls): Set up some coupons
- def test_pick_coupon(self): Tests for happy case
- def test_attached_to_other_u... | Implement the Python class `PickCouponTests` described below.
Class description:
Tests for pick_coupon
Method signatures and docstrings:
- def _create_coupons(cls, user): Create some coupons
- def setUpTestData(cls): Set up some coupons
- def test_pick_coupon(self): Tests for happy case
- def test_attached_to_other_u... | d6564caca0b7bbfd31e67a751564107fd17d6eb0 | <|skeleton|>
class PickCouponTests:
"""Tests for pick_coupon"""
def _create_coupons(cls, user):
"""Create some coupons"""
<|body_0|>
def setUpTestData(cls):
"""Set up some coupons"""
<|body_1|>
def test_pick_coupon(self):
"""Tests for happy case"""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PickCouponTests:
"""Tests for pick_coupon"""
def _create_coupons(cls, user):
"""Create some coupons"""
course_run = CourseRunFactory.create(course__program__financial_aid_availability=True, course__program__live=True)
course = course_run.course
ProgramEnrollment.objects.cr... | the_stack_v2_python_sparse | ecommerce/api_test.py | mitodl/micromasters | train | 35 |
2e8e06c4bcf0217a85bfd3e68bd997bcdff813ec | [
"assert DoomsDay.get_offset_from_year(2019) == 5\nassert DoomsDay.get_offset_from_year(1987) == 4\nassert DoomsDay.get_offset_from_year(1843) == 2\nassert DoomsDay.get_offset_from_year(1773) == 0\nprint('test_offset: pass')",
"ret = DoomsDay.is_leap_year(y)\nif ret is ans:\n print(f'correct: {y}')\nelse:\n ... | <|body_start_0|>
assert DoomsDay.get_offset_from_year(2019) == 5
assert DoomsDay.get_offset_from_year(1987) == 4
assert DoomsDay.get_offset_from_year(1843) == 2
assert DoomsDay.get_offset_from_year(1773) == 0
print('test_offset: pass')
<|end_body_0|>
<|body_start_1|>
ret... | class to test DoomsDay | TestDoomsDay | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDoomsDay:
"""class to test DoomsDay"""
def test_offset():
"""test offset"""
<|body_0|>
def test_leap(y, ans):
"""test leap year"""
<|body_1|>
def test_tmm(y, m, d):
"""test_tmm"""
<|body_2|>
def test_dow(y, m, d):
"""... | stack_v2_sparse_classes_75kplus_train_066544 | 2,373 | no_license | [
{
"docstring": "test offset",
"name": "test_offset",
"signature": "def test_offset()"
},
{
"docstring": "test leap year",
"name": "test_leap",
"signature": "def test_leap(y, ans)"
},
{
"docstring": "test_tmm",
"name": "test_tmm",
"signature": "def test_tmm(y, m, d)"
},
... | 5 | null | Implement the Python class `TestDoomsDay` described below.
Class description:
class to test DoomsDay
Method signatures and docstrings:
- def test_offset(): test offset
- def test_leap(y, ans): test leap year
- def test_tmm(y, m, d): test_tmm
- def test_dow(y, m, d): test dow vs module datetime
- def full_test(): chec... | Implement the Python class `TestDoomsDay` described below.
Class description:
class to test DoomsDay
Method signatures and docstrings:
- def test_offset(): test offset
- def test_leap(y, ans): test leap year
- def test_tmm(y, m, d): test_tmm
- def test_dow(y, m, d): test dow vs module datetime
- def full_test(): chec... | 0309eeb614612f9a35843e2f45f4080ae03eaa81 | <|skeleton|>
class TestDoomsDay:
"""class to test DoomsDay"""
def test_offset():
"""test offset"""
<|body_0|>
def test_leap(y, ans):
"""test leap year"""
<|body_1|>
def test_tmm(y, m, d):
"""test_tmm"""
<|body_2|>
def test_dow(y, m, d):
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestDoomsDay:
"""class to test DoomsDay"""
def test_offset():
"""test offset"""
assert DoomsDay.get_offset_from_year(2019) == 5
assert DoomsDay.get_offset_from_year(1987) == 4
assert DoomsDay.get_offset_from_year(1843) == 2
assert DoomsDay.get_offset_from_year(1773... | the_stack_v2_python_sparse | python3/datetime/dooms_day_test.py | ericosur/ericosur-snippet | train | 2 |
270dea63223b6183f478b68fc7c0ee025f88043f | [
"needs = {}.fromkeys(nums, 0)\nwindows = {}.fromkeys(nums, 0)\nfor num in nums:\n needs[num] += 1\nmax_freq = max(needs.values())\nn = len(nums)\nleft, right, res = (0, 0, n)\nwhile right < n:\n c = nums[right]\n right += 1\n windows[c] += 1\n while max(windows.values()) == max_freq:\n res = m... | <|body_start_0|>
needs = {}.fromkeys(nums, 0)
windows = {}.fromkeys(nums, 0)
for num in nums:
needs[num] += 1
max_freq = max(needs.values())
n = len(nums)
left, right, res = (0, 0, n)
while right < n:
c = nums[right]
right += 1
... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findShortestSubArray(self, nums: List[int]) -> int:
"""标准滑动窗口解法"""
<|body_0|>
def findShortestSubArray2(self, nums: List[int]) -> int:
"""数组遍历法,记录每个数字出现的频次,第一次出现的位置和最后一次出现的位置"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
needs = {}.f... | stack_v2_sparse_classes_75kplus_train_066545 | 1,631 | permissive | [
{
"docstring": "标准滑动窗口解法",
"name": "findShortestSubArray",
"signature": "def findShortestSubArray(self, nums: List[int]) -> int"
},
{
"docstring": "数组遍历法,记录每个数字出现的频次,第一次出现的位置和最后一次出现的位置",
"name": "findShortestSubArray2",
"signature": "def findShortestSubArray2(self, nums: List[int]) -> in... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findShortestSubArray(self, nums: List[int]) -> int: 标准滑动窗口解法
- def findShortestSubArray2(self, nums: List[int]) -> int: 数组遍历法,记录每个数字出现的频次,第一次出现的位置和最后一次出现的位置 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findShortestSubArray(self, nums: List[int]) -> int: 标准滑动窗口解法
- def findShortestSubArray2(self, nums: List[int]) -> int: 数组遍历法,记录每个数字出现的频次,第一次出现的位置和最后一次出现的位置
<|skeleton|>
cla... | 27185d382a891f4667f67701a60c796fa3a6c1ac | <|skeleton|>
class Solution:
def findShortestSubArray(self, nums: List[int]) -> int:
"""标准滑动窗口解法"""
<|body_0|>
def findShortestSubArray2(self, nums: List[int]) -> int:
"""数组遍历法,记录每个数字出现的频次,第一次出现的位置和最后一次出现的位置"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findShortestSubArray(self, nums: List[int]) -> int:
"""标准滑动窗口解法"""
needs = {}.fromkeys(nums, 0)
windows = {}.fromkeys(nums, 0)
for num in nums:
needs[num] += 1
max_freq = max(needs.values())
n = len(nums)
left, right, res = (0, ... | the_stack_v2_python_sparse | Leetcode/滑动窗口/697-数组的度-e.py | JackeyGuo/Algorithms | train | 1 | |
d942d8a860b72a0c684d604f0509f65a991360cf | [
"res = ['']\nfor i in range(len(s)):\n tmp_s = s[i:]\n for j in range(len(tmp_s)):\n res.append(tmp_s[j:])\nreturn sorted(list(set(res)), key=len, reverse=True)",
"a_list = self.genSubsequence(a)\nb_list = self.genSubsequence(b)\na_res = -1\nb_res = -1\nfor w in a_list:\n if w not in b_list:\n ... | <|body_start_0|>
res = ['']
for i in range(len(s)):
tmp_s = s[i:]
for j in range(len(tmp_s)):
res.append(tmp_s[j:])
return sorted(list(set(res)), key=len, reverse=True)
<|end_body_0|>
<|body_start_1|>
a_list = self.genSubsequence(a)
b_list... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def genSubsequence(self, s):
"""generate the subsequence list of the string :type s: str :rtype sorted<list>"""
<|body_0|>
def findLUSlength(self, a, b):
""":type a: str :type b: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_066546 | 2,097 | no_license | [
{
"docstring": "generate the subsequence list of the string :type s: str :rtype sorted<list>",
"name": "genSubsequence",
"signature": "def genSubsequence(self, s)"
},
{
"docstring": ":type a: str :type b: str :rtype: int",
"name": "findLUSlength",
"signature": "def findLUSlength(self, a,... | 2 | stack_v2_sparse_classes_30k_train_044063 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def genSubsequence(self, s): generate the subsequence list of the string :type s: str :rtype sorted<list>
- def findLUSlength(self, a, b): :type a: str :type b: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def genSubsequence(self, s): generate the subsequence list of the string :type s: str :rtype sorted<list>
- def findLUSlength(self, a, b): :type a: str :type b: str :rtype: int
... | 9a58a519b2b0da6bd781ae0b389503798ac8191b | <|skeleton|>
class Solution:
def genSubsequence(self, s):
"""generate the subsequence list of the string :type s: str :rtype sorted<list>"""
<|body_0|>
def findLUSlength(self, a, b):
""":type a: str :type b: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def genSubsequence(self, s):
"""generate the subsequence list of the string :type s: str :rtype sorted<list>"""
res = ['']
for i in range(len(s)):
tmp_s = s[i:]
for j in range(len(tmp_s)):
res.append(tmp_s[j:])
return sorted(lis... | the_stack_v2_python_sparse | src/521.py | ovwane/leetcode-1 | train | 0 | |
2b9bf61ba51d53f6bae6a4e05b50edbaf29e6585 | [
"if not record.references_to:\n raise ReferenceToNoneException()\nreturn '{} IN A {}'.format(record.domain_name, record.references_to)",
"last_address = record.references_to\nrecord.references_to = [last_address, new_references]\nrecord.change_state(BalancedHostDnsRecordState())"
] | <|body_start_0|>
if not record.references_to:
raise ReferenceToNoneException()
return '{} IN A {}'.format(record.domain_name, record.references_to)
<|end_body_0|>
<|body_start_1|>
last_address = record.references_to
record.references_to = [last_address, new_references]
... | HostDnsRecordState it is state of DnsRecord. | HostDnsRecordState | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HostDnsRecordState:
"""HostDnsRecordState it is state of DnsRecord."""
def get_string(record):
"""Get string representation."""
<|body_0|>
def add_references(record, new_references):
"""Add new reference to, switch state."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_066547 | 2,743 | no_license | [
{
"docstring": "Get string representation.",
"name": "get_string",
"signature": "def get_string(record)"
},
{
"docstring": "Add new reference to, switch state.",
"name": "add_references",
"signature": "def add_references(record, new_references)"
}
] | 2 | stack_v2_sparse_classes_30k_train_029068 | Implement the Python class `HostDnsRecordState` described below.
Class description:
HostDnsRecordState it is state of DnsRecord.
Method signatures and docstrings:
- def get_string(record): Get string representation.
- def add_references(record, new_references): Add new reference to, switch state. | Implement the Python class `HostDnsRecordState` described below.
Class description:
HostDnsRecordState it is state of DnsRecord.
Method signatures and docstrings:
- def get_string(record): Get string representation.
- def add_references(record, new_references): Add new reference to, switch state.
<|skeleton|>
class ... | e221fdc23cdb8e6db0a07c50e18a52f7a41ff87c | <|skeleton|>
class HostDnsRecordState:
"""HostDnsRecordState it is state of DnsRecord."""
def get_string(record):
"""Get string representation."""
<|body_0|>
def add_references(record, new_references):
"""Add new reference to, switch state."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HostDnsRecordState:
"""HostDnsRecordState it is state of DnsRecord."""
def get_string(record):
"""Get string representation."""
if not record.references_to:
raise ReferenceToNoneException()
return '{} IN A {}'.format(record.domain_name, record.references_to)
def a... | the_stack_v2_python_sparse | dbtobindzone/builders/dns_state.py | proggga/dbtobindzone | train | 0 |
7139f30dd8dca193b6982574c28e271f75294db1 | [
"self.pid_type = pid_type\nself.object_type = object_type\nself.object_getter = getter",
"pid = PersistentIdentifier.get(self.pid_type, pid_value)\nif pid.is_new() or pid.is_reserved():\n raise PIDUnregistered(pid)\nif pid.is_deleted():\n obj_id = pid.get_assigned_object(object_type=self.object_type)\n t... | <|body_start_0|>
self.pid_type = pid_type
self.object_type = object_type
self.object_getter = getter
<|end_body_0|>
<|body_start_1|>
pid = PersistentIdentifier.get(self.pid_type, pid_value)
if pid.is_new() or pid.is_reserved():
raise PIDUnregistered(pid)
if p... | Persistent identifier resolver. Helper class for retrieving an internal object for a given persistent identifier. | Resolver | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Resolver:
"""Persistent identifier resolver. Helper class for retrieving an internal object for a given persistent identifier."""
def __init__(self, pid_type=None, object_type=None, getter=None):
"""Initialize resolver. :param pid_type: Persistent identifier type. :param object_type:... | stack_v2_sparse_classes_75kplus_train_066548 | 2,856 | no_license | [
{
"docstring": "Initialize resolver. :param pid_type: Persistent identifier type. :param object_type: Object type. :param getter: Callable that will take an object id for the given object type and retrieve the internal object.",
"name": "__init__",
"signature": "def __init__(self, pid_type=None, object_... | 2 | stack_v2_sparse_classes_30k_train_030333 | Implement the Python class `Resolver` described below.
Class description:
Persistent identifier resolver. Helper class for retrieving an internal object for a given persistent identifier.
Method signatures and docstrings:
- def __init__(self, pid_type=None, object_type=None, getter=None): Initialize resolver. :param ... | Implement the Python class `Resolver` described below.
Class description:
Persistent identifier resolver. Helper class for retrieving an internal object for a given persistent identifier.
Method signatures and docstrings:
- def __init__(self, pid_type=None, object_type=None, getter=None): Initialize resolver. :param ... | 54eb34c7e1594cc50a5347ba93e12a991ba8b7f3 | <|skeleton|>
class Resolver:
"""Persistent identifier resolver. Helper class for retrieving an internal object for a given persistent identifier."""
def __init__(self, pid_type=None, object_type=None, getter=None):
"""Initialize resolver. :param pid_type: Persistent identifier type. :param object_type:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Resolver:
"""Persistent identifier resolver. Helper class for retrieving an internal object for a given persistent identifier."""
def __init__(self, pid_type=None, object_type=None, getter=None):
"""Initialize resolver. :param pid_type: Persistent identifier type. :param object_type: Object type.... | the_stack_v2_python_sparse | .virtualenvs/invenio/lib/python2.7/site-packages/invenio_pidstore/resolver.py | N03/invenio | train | 0 |
e39f560cd7b2eeb958a2678376aefe5ea8f14256 | [
"if not matrix:\n return\nself.row = len(matrix)\nself.col = len(matrix[0])\nself.matrix = [[0] * self.col for _ in range(self.row)]\nfor i in xrange(self.row):\n for j in xrange(self.col):\n self.matrix[i][j] = self.matrix[max(0, i - 1)][j] + matrix[i][j]",
"origin = self.matrix[0][col] if not row e... | <|body_start_0|>
if not matrix:
return
self.row = len(matrix)
self.col = len(matrix[0])
self.matrix = [[0] * self.col for _ in range(self.row)]
for i in xrange(self.row):
for j in xrange(self.col):
self.matrix[i][j] = self.matrix[max(0, i -... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def update(self, row, col, val):
""":type row: int :type col: int :type val: int :rtype: void"""
<|body_1|>
def sumRegion(self, row1, col1, row2, col2):
""":typ... | stack_v2_sparse_classes_75kplus_train_066549 | 1,350 | no_license | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row: int :type col: int :type val: int :rtype: void",
"name": "update",
"signature": "def update(self, row, col, val)"
},
{
"docstring": ":type r... | 3 | stack_v2_sparse_classes_30k_train_040166 | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def update(self, row, col, val): :type row: int :type col: int :type val: int :rtype: void
- def sumRegion(self, row... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def update(self, row, col, val): :type row: int :type col: int :type val: int :rtype: void
- def sumRegion(self, row... | ed15eb27936b39980d4cb5fb61cd937ec7ddcb6a | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def update(self, row, col, val):
""":type row: int :type col: int :type val: int :rtype: void"""
<|body_1|>
def sumRegion(self, row1, col1, row2, col2):
""":typ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
if not matrix:
return
self.row = len(matrix)
self.col = len(matrix[0])
self.matrix = [[0] * self.col for _ in range(self.row)]
for i in xrange(self.row):
for j in ... | the_stack_v2_python_sparse | alice/LC308.py | AliceTTXu/LeetCode | train | 0 | |
9668f59486c5655bf6bf79013689d3acb1440d60 | [
"print('=' * 40)\nprint('check_status_by_job_id', job_id)\nprint('=' * 40)\ntry:\n job = PreprocessJob.objects.get(job_id)\nexcept PreprocessJob.DoesNotExist:\n user_msg = 'PreprocessJob not found: %s (check_status_by_job_id)' % job_id\n return err_resp(user_msg)\nit_worked = JobStatusCheck.check_status(jo... | <|body_start_0|>
print('=' * 40)
print('check_status_by_job_id', job_id)
print('=' * 40)
try:
job = PreprocessJob.objects.get(job_id)
except PreprocessJob.DoesNotExist:
user_msg = 'PreprocessJob not found: %s (check_status_by_job_id)' % job_id
... | Check celery and update status for a PreprocessJob | JobStatusCheck | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JobStatusCheck:
"""Check celery and update status for a PreprocessJob"""
def check_status_by_job_id(job_id):
"""Check/update the job status by job_id"""
<|body_0|>
def xcheck_status(job):
"""Check/update the job status"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_75kplus_train_066550 | 2,681 | permissive | [
{
"docstring": "Check/update the job status by job_id",
"name": "check_status_by_job_id",
"signature": "def check_status_by_job_id(job_id)"
},
{
"docstring": "Check/update the job status",
"name": "xcheck_status",
"signature": "def xcheck_status(job)"
}
] | 2 | stack_v2_sparse_classes_30k_train_053385 | Implement the Python class `JobStatusCheck` described below.
Class description:
Check celery and update status for a PreprocessJob
Method signatures and docstrings:
- def check_status_by_job_id(job_id): Check/update the job status by job_id
- def xcheck_status(job): Check/update the job status | Implement the Python class `JobStatusCheck` described below.
Class description:
Check celery and update status for a PreprocessJob
Method signatures and docstrings:
- def check_status_by_job_id(job_id): Check/update the job status by job_id
- def xcheck_status(job): Check/update the job status
<|skeleton|>
class Job... | 9461522219f5ef0f4877f24c8f5923e462bd9557 | <|skeleton|>
class JobStatusCheck:
"""Check celery and update status for a PreprocessJob"""
def check_status_by_job_id(job_id):
"""Check/update the job status by job_id"""
<|body_0|>
def xcheck_status(job):
"""Check/update the job status"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JobStatusCheck:
"""Check celery and update status for a PreprocessJob"""
def check_status_by_job_id(job_id):
"""Check/update the job status by job_id"""
print('=' * 40)
print('check_status_by_job_id', job_id)
print('=' * 40)
try:
job = PreprocessJob.obj... | the_stack_v2_python_sparse | preprocess_web/code/ravens_metadata_apps/preprocess_jobs/job_status_check.py | TwoRavens/raven-metadata-service | train | 0 |
afbeb7216f984d5977c15a8fa1789f16048282c3 | [
"result = [[r0, c0]]\nk = 1\nwhile len(result) < R * C:\n if 0 <= r0 < R:\n for j in range(max(0, c0 + 1), min(c0 + 1 + k, C)):\n result.append([r0, j])\n c0 = c0 + k\n print('1', r0, c0, k)\n if 0 <= c0 < C:\n for i in range(max(r0 + 1, 0), min(r0 + 1 + k, R)):\n res... | <|body_start_0|>
result = [[r0, c0]]
k = 1
while len(result) < R * C:
if 0 <= r0 < R:
for j in range(max(0, c0 + 1), min(c0 + 1 + k, C)):
result.append([r0, j])
c0 = c0 + k
print('1', r0, c0, k)
if 0 <= c0 < C:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def spiralMatrixIII(self, R, C, r0, c0):
""":type R: int :type C: int :type r0: int :type c0: int :rtype: List[List[int]] 176MS"""
<|body_0|>
def spiralMatrixIII_1(self, R, C, r0, c0):
"""180ms :param R: :param C: :param r0: :param c0: :return:"""
<... | stack_v2_sparse_classes_75kplus_train_066551 | 3,291 | no_license | [
{
"docstring": ":type R: int :type C: int :type r0: int :type c0: int :rtype: List[List[int]] 176MS",
"name": "spiralMatrixIII",
"signature": "def spiralMatrixIII(self, R, C, r0, c0)"
},
{
"docstring": "180ms :param R: :param C: :param r0: :param c0: :return:",
"name": "spiralMatrixIII_1",
... | 2 | stack_v2_sparse_classes_30k_train_049853 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def spiralMatrixIII(self, R, C, r0, c0): :type R: int :type C: int :type r0: int :type c0: int :rtype: List[List[int]] 176MS
- def spiralMatrixIII_1(self, R, C, r0, c0): 180ms :p... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def spiralMatrixIII(self, R, C, r0, c0): :type R: int :type C: int :type r0: int :type c0: int :rtype: List[List[int]] 176MS
- def spiralMatrixIII_1(self, R, C, r0, c0): 180ms :p... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def spiralMatrixIII(self, R, C, r0, c0):
""":type R: int :type C: int :type r0: int :type c0: int :rtype: List[List[int]] 176MS"""
<|body_0|>
def spiralMatrixIII_1(self, R, C, r0, c0):
"""180ms :param R: :param C: :param r0: :param c0: :return:"""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def spiralMatrixIII(self, R, C, r0, c0):
""":type R: int :type C: int :type r0: int :type c0: int :rtype: List[List[int]] 176MS"""
result = [[r0, c0]]
k = 1
while len(result) < R * C:
if 0 <= r0 < R:
for j in range(max(0, c0 + 1), min(c0 + ... | the_stack_v2_python_sparse | SpiralMatrixIII_MID_889.py | 953250587/leetcode-python | train | 2 | |
0da50b1cc82c6ee04bb83c2d2a3a14999b679593 | [
"self.n_estimator = n_estimator\nself.trees = []\nself.max_sample = max_sample\nself.criterion = criterion\nself.max_depth = max_depth\nself.min_leaf_size = min_leaf_size",
"m, n_feature = X_train.shape\nsample = self.max_sample if isinstance(self.max_sample, int) else int(self.max_sample * m)\nfor _ in range(sel... | <|body_start_0|>
self.n_estimator = n_estimator
self.trees = []
self.max_sample = max_sample
self.criterion = criterion
self.max_depth = max_depth
self.min_leaf_size = min_leaf_size
<|end_body_0|>
<|body_start_1|>
m, n_feature = X_train.shape
sample = sel... | RandomForest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomForest:
def __init__(self, n_estimator=100, criterion='gini', max_depth=3, min_leaf_size=4, max_sample=0.5):
"""Random forest is a supervised learning algorithm. Some week estimator works together to build a strong estimator. :param n_estimator: Total number of tree that will be cr... | stack_v2_sparse_classes_75kplus_train_066552 | 5,246 | no_license | [
{
"docstring": "Random forest is a supervised learning algorithm. Some week estimator works together to build a strong estimator. :param n_estimator: Total number of tree that will be created :param criterion: The loss function that will be used. gini/entropy :param max_depth: Maximum depth of each tree. :param... | 3 | stack_v2_sparse_classes_30k_train_006678 | Implement the Python class `RandomForest` described below.
Class description:
Implement the RandomForest class.
Method signatures and docstrings:
- def __init__(self, n_estimator=100, criterion='gini', max_depth=3, min_leaf_size=4, max_sample=0.5): Random forest is a supervised learning algorithm. Some week estimator... | Implement the Python class `RandomForest` described below.
Class description:
Implement the RandomForest class.
Method signatures and docstrings:
- def __init__(self, n_estimator=100, criterion='gini', max_depth=3, min_leaf_size=4, max_sample=0.5): Random forest is a supervised learning algorithm. Some week estimator... | d8ed73d9c319135bd2fd8440d8610846c31f6c5d | <|skeleton|>
class RandomForest:
def __init__(self, n_estimator=100, criterion='gini', max_depth=3, min_leaf_size=4, max_sample=0.5):
"""Random forest is a supervised learning algorithm. Some week estimator works together to build a strong estimator. :param n_estimator: Total number of tree that will be cr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomForest:
def __init__(self, n_estimator=100, criterion='gini', max_depth=3, min_leaf_size=4, max_sample=0.5):
"""Random forest is a supervised learning algorithm. Some week estimator works together to build a strong estimator. :param n_estimator: Total number of tree that will be created :param c... | the_stack_v2_python_sparse | machine_learning/ensemble/bagging/random_forest/random_forest.py | Jayem-11/machine-learning-scratch | train | 0 | |
24b9a2e20a2592c136dafcaa92b3047aed694019 | [
"projects = []\nfor project_tuple in project_tuples:\n project = Project(project_tuple[1])\n project.id = project_tuple[0]\n project.houdini_build = project_tuple[2]\n project.width = project_tuple[3]\n project.height = project_tuple[4]\n project.description = project_tuple[5]\n projects.append... | <|body_start_0|>
projects = []
for project_tuple in project_tuples:
project = Project(project_tuple[1])
project.id = project_tuple[0]
project.houdini_build = project_tuple[2]
project.width = project_tuple[3]
project.height = project_tuple[4]
... | Convert data from DB to Athena objects | Converter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Converter:
"""Convert data from DB to Athena objects"""
def convert_to_project(project_tuples):
"""Convert list of projects tuples to list of Eve Project objects :param project_tuples: list of tuples, project data: [(id, name, houdini_build, width, height, description)] :return:"""
... | stack_v2_sparse_classes_75kplus_train_066553 | 6,625 | no_license | [
{
"docstring": "Convert list of projects tuples to list of Eve Project objects :param project_tuples: list of tuples, project data: [(id, name, houdini_build, width, height, description)] :return:",
"name": "convert_to_project",
"signature": "def convert_to_project(project_tuples)"
},
{
"docstri... | 5 | null | Implement the Python class `Converter` described below.
Class description:
Convert data from DB to Athena objects
Method signatures and docstrings:
- def convert_to_project(project_tuples): Convert list of projects tuples to list of Eve Project objects :param project_tuples: list of tuples, project data: [(id, name, ... | Implement the Python class `Converter` described below.
Class description:
Convert data from DB to Athena objects
Method signatures and docstrings:
- def convert_to_project(project_tuples): Convert list of projects tuples to list of Eve Project objects :param project_tuples: list of tuples, project data: [(id, name, ... | 4e58b79e5992dc4fb4e73e44cd2a7e0522420d15 | <|skeleton|>
class Converter:
"""Convert data from DB to Athena objects"""
def convert_to_project(project_tuples):
"""Convert list of projects tuples to list of Eve Project objects :param project_tuples: list of tuples, project data: [(id, name, houdini_build, width, height, description)] :return:"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Converter:
"""Convert data from DB to Athena objects"""
def convert_to_project(project_tuples):
"""Convert list of projects tuples to list of Eve Project objects :param project_tuples: list of tuples, project data: [(id, name, houdini_build, width, height, description)] :return:"""
projec... | the_stack_v2_python_sparse | Eve/tools/core/database/entities.py | kiryha/Houdini | train | 668 |
000e2c88420274258fd7b6dd7e7767eeca8e51ea | [
"logging.FileHandler.__init__(self, filename, mode, encoding, delay)\nself.mode = mode\nself.encoding = encoding\nself.namer = None\nself.rotator = None",
"try:\n if self.shouldRollover(record):\n self.doRollover()\n logging.FileHandler.emit(self, record)\nexcept Exception:\n self.handleError(reco... | <|body_start_0|>
logging.FileHandler.__init__(self, filename, mode, encoding, delay)
self.mode = mode
self.encoding = encoding
self.namer = None
self.rotator = None
<|end_body_0|>
<|body_start_1|>
try:
if self.shouldRollover(record):
self.doRo... | Base class for handlers that rotate log files at a certain point. Not meant to be instantiated directly. Instead, use RotatingFileHandler or TimedRotatingFileHandler. | BaseRotatingHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseRotatingHandler:
"""Base class for handlers that rotate log files at a certain point. Not meant to be instantiated directly. Instead, use RotatingFileHandler or TimedRotatingFileHandler."""
def __init__(self, filename, mode, encoding=None, delay=False):
"""Use the specified filen... | stack_v2_sparse_classes_75kplus_train_066554 | 21,205 | no_license | [
{
"docstring": "Use the specified filename for streamed logging",
"name": "__init__",
"signature": "def __init__(self, filename, mode, encoding=None, delay=False)"
},
{
"docstring": "Emit a record. Output the record to the file, catering for rollover as described in doRollover().",
"name": "... | 4 | stack_v2_sparse_classes_30k_train_026167 | Implement the Python class `BaseRotatingHandler` described below.
Class description:
Base class for handlers that rotate log files at a certain point. Not meant to be instantiated directly. Instead, use RotatingFileHandler or TimedRotatingFileHandler.
Method signatures and docstrings:
- def __init__(self, filename, m... | Implement the Python class `BaseRotatingHandler` described below.
Class description:
Base class for handlers that rotate log files at a certain point. Not meant to be instantiated directly. Instead, use RotatingFileHandler or TimedRotatingFileHandler.
Method signatures and docstrings:
- def __init__(self, filename, m... | 641727294039a9441c35ba1a1d22de403664b710 | <|skeleton|>
class BaseRotatingHandler:
"""Base class for handlers that rotate log files at a certain point. Not meant to be instantiated directly. Instead, use RotatingFileHandler or TimedRotatingFileHandler."""
def __init__(self, filename, mode, encoding=None, delay=False):
"""Use the specified filen... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseRotatingHandler:
"""Base class for handlers that rotate log files at a certain point. Not meant to be instantiated directly. Instead, use RotatingFileHandler or TimedRotatingFileHandler."""
def __init__(self, filename, mode, encoding=None, delay=False):
"""Use the specified filename for strea... | the_stack_v2_python_sparse | stripped/logging/handlers.py | notro/tmp_CircuitPython_stdlib | train | 1 |
6407300850f5080adbd1515ad35b9574d189190e | [
"JudgmentVerification.__init__(self, config, basename)\nself.bi = center_name()\npass",
"functionName = inspect.stack()[0][3]\ntabs = t_c\nif tabs in case_value:\n self.ct = CustomTabs(self.driver, self.financial[tabs])\n self.ct.into_the_city(self.vac, case_value[tabs])\n pass\nelse:\n self.log.info(... | <|body_start_0|>
JudgmentVerification.__init__(self, config, basename)
self.bi = center_name()
pass
<|end_body_0|>
<|body_start_1|>
functionName = inspect.stack()[0][3]
tabs = t_c
if tabs in case_value:
self.ct = CustomTabs(self.driver, self.financial[tabs])
... | InviteOperateJude | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InviteOperateJude:
def __init__(self, config, basename, center_name):
"""定义模块数据信息 :param module: 元素模块 :param sheet: 用例标签名 :param basename: 执行程序的文件名"""
<|body_0|>
def switchover_tabs_city(self, case_value, t_c):
"""进入指定的tabs或者city :param t_c: :return:"""
<|bod... | stack_v2_sparse_classes_75kplus_train_066555 | 5,076 | no_license | [
{
"docstring": "定义模块数据信息 :param module: 元素模块 :param sheet: 用例标签名 :param basename: 执行程序的文件名",
"name": "__init__",
"signature": "def __init__(self, config, basename, center_name)"
},
{
"docstring": "进入指定的tabs或者city :param t_c: :return:",
"name": "switchover_tabs_city",
"signature": "def sw... | 4 | stack_v2_sparse_classes_30k_train_002314 | Implement the Python class `InviteOperateJude` described below.
Class description:
Implement the InviteOperateJude class.
Method signatures and docstrings:
- def __init__(self, config, basename, center_name): 定义模块数据信息 :param module: 元素模块 :param sheet: 用例标签名 :param basename: 执行程序的文件名
- def switchover_tabs_city(self, c... | Implement the Python class `InviteOperateJude` described below.
Class description:
Implement the InviteOperateJude class.
Method signatures and docstrings:
- def __init__(self, config, basename, center_name): 定义模块数据信息 :param module: 元素模块 :param sheet: 用例标签名 :param basename: 执行程序的文件名
- def switchover_tabs_city(self, c... | 4df8ce960721407a20d89de47faad0df0de063a1 | <|skeleton|>
class InviteOperateJude:
def __init__(self, config, basename, center_name):
"""定义模块数据信息 :param module: 元素模块 :param sheet: 用例标签名 :param basename: 执行程序的文件名"""
<|body_0|>
def switchover_tabs_city(self, case_value, t_c):
"""进入指定的tabs或者city :param t_c: :return:"""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InviteOperateJude:
def __init__(self, config, basename, center_name):
"""定义模块数据信息 :param module: 元素模块 :param sheet: 用例标签名 :param basename: 执行程序的文件名"""
JudgmentVerification.__init__(self, config, basename)
self.bi = center_name()
pass
def switchover_tabs_city(self, case_val... | the_stack_v2_python_sparse | CenterBackground/GeneralizeAssist/Invite/inviteoperatejude.py | namexiaohuihui/operating | train | 0 | |
41ebe2c39e122ba9238714b9aba42a29c97942a5 | [
"self.orgnr_field = orgnr_field\nself.dunsnr_field = dunsnr_field\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\norgnr_field = dictionary.get('orgnrField')\ndunsnr_field = dictionary.get('dunsnrField')\nfor key in cls._names.values():\n if key in dictionary:\n ... | <|body_start_0|>
self.orgnr_field = orgnr_field
self.dunsnr_field = dunsnr_field
self.additional_properties = additional_properties
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
orgnr_field = dictionary.get('orgnrField')
dunsnr_field = di... | Implementation of the 'Identifikasjon' model. TODO: type model description here. Attributes: orgnr_field (int): TODO: type description here. dunsnr_field (int): TODO: type description here. | Identifikasjon | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Identifikasjon:
"""Implementation of the 'Identifikasjon' model. TODO: type model description here. Attributes: orgnr_field (int): TODO: type description here. dunsnr_field (int): TODO: type description here."""
def __init__(self, orgnr_field=None, dunsnr_field=None, additional_properties={}... | stack_v2_sparse_classes_75kplus_train_066556 | 2,101 | permissive | [
{
"docstring": "Constructor for the Identifikasjon class",
"name": "__init__",
"signature": "def __init__(self, orgnr_field=None, dunsnr_field=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary repre... | 2 | stack_v2_sparse_classes_30k_val_001112 | Implement the Python class `Identifikasjon` described below.
Class description:
Implementation of the 'Identifikasjon' model. TODO: type model description here. Attributes: orgnr_field (int): TODO: type description here. dunsnr_field (int): TODO: type description here.
Method signatures and docstrings:
- def __init__... | Implement the Python class `Identifikasjon` described below.
Class description:
Implementation of the 'Identifikasjon' model. TODO: type model description here. Attributes: orgnr_field (int): TODO: type description here. dunsnr_field (int): TODO: type description here.
Method signatures and docstrings:
- def __init__... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class Identifikasjon:
"""Implementation of the 'Identifikasjon' model. TODO: type model description here. Attributes: orgnr_field (int): TODO: type description here. dunsnr_field (int): TODO: type description here."""
def __init__(self, orgnr_field=None, dunsnr_field=None, additional_properties={}... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Identifikasjon:
"""Implementation of the 'Identifikasjon' model. TODO: type model description here. Attributes: orgnr_field (int): TODO: type description here. dunsnr_field (int): TODO: type description here."""
def __init__(self, orgnr_field=None, dunsnr_field=None, additional_properties={}):
""... | the_stack_v2_python_sparse | idfy_rest_client/models/identifikasjon.py | dealflowteam/Idfy | train | 0 |
5cdf4f096f3d83c2a7fc7243e48c06cf07fd4358 | [
"super().setupUI(Form)\nself.label_4 = QtWidgets.QLabel(self.verticalLayoutWidget)\nself.label_4.setToolTip('')\nself.label_4.setAlignment(QtCore.Qt.AlignCenter)\nself.label_4.setObjectName('label_4')\nself.verticalLayout_2.addWidget(self.label_4)\nself.label_8 = QtWidgets.QLabel(self.verticalLayoutWidget)\nself.la... | <|body_start_0|>
super().setupUI(Form)
self.label_4 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_4.setToolTip('')
self.label_4.setAlignment(QtCore.Qt.AlignCenter)
self.label_4.setObjectName('label_4')
self.verticalLayout_2.addWidget(self.label_4)
self.... | TMTWindowWidget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TMTWindowWidget:
def setupUi(self, Form):
"""Método empleado para especificar el contenido de la Interfáz gráfica, es generado por pyuic5. Args: Form: Ventana en la que se deplegará la interfáz gráfica (es un tipo de dato QtWidget.QWidget)"""
<|body_0|>
def retranslateUi(sel... | stack_v2_sparse_classes_75kplus_train_066557 | 2,685 | no_license | [
{
"docstring": "Método empleado para especificar el contenido de la Interfáz gráfica, es generado por pyuic5. Args: Form: Ventana en la que se deplegará la interfáz gráfica (es un tipo de dato QtWidget.QWidget)",
"name": "setupUi",
"signature": "def setupUi(self, Form)"
},
{
"docstring": "Método... | 2 | stack_v2_sparse_classes_30k_train_019163 | Implement the Python class `TMTWindowWidget` described below.
Class description:
Implement the TMTWindowWidget class.
Method signatures and docstrings:
- def setupUi(self, Form): Método empleado para especificar el contenido de la Interfáz gráfica, es generado por pyuic5. Args: Form: Ventana en la que se deplegará la... | Implement the Python class `TMTWindowWidget` described below.
Class description:
Implement the TMTWindowWidget class.
Method signatures and docstrings:
- def setupUi(self, Form): Método empleado para especificar el contenido de la Interfáz gráfica, es generado por pyuic5. Args: Form: Ventana en la que se deplegará la... | 5d1d68fc4476ed866ecfc305112854d9a49c3876 | <|skeleton|>
class TMTWindowWidget:
def setupUi(self, Form):
"""Método empleado para especificar el contenido de la Interfáz gráfica, es generado por pyuic5. Args: Form: Ventana en la que se deplegará la interfáz gráfica (es un tipo de dato QtWidget.QWidget)"""
<|body_0|>
def retranslateUi(sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TMTWindowWidget:
def setupUi(self, Form):
"""Método empleado para especificar el contenido de la Interfáz gráfica, es generado por pyuic5. Args: Form: Ventana en la que se deplegará la interfáz gráfica (es un tipo de dato QtWidget.QWidget)"""
super().setupUI(Form)
self.label_4 = QtWidg... | the_stack_v2_python_sparse | src/main/python/vistas/TMTWindowWidget.py | ProyectoIntegrador2018/reportes-neurociencias | train | 1 | |
5e4198dcc9da98e7c4922d426edff324a07f9969 | [
"@self.router.get('/info', response_model=Info, response_model_exclude={'minzoom', 'maxzoom', 'center'}, response_model_exclude_none=True, responses={200: {'description': \"Return dataset's basic info or the list of available bands.\"}})\ndef info(src_path=Depends(self.path_dependency), bands_params=Depends(BandsPa... | <|body_start_0|>
@self.router.get('/info', response_model=Info, response_model_exclude={'minzoom', 'maxzoom', 'center'}, response_model_exclude_none=True, responses={200: {'description': "Return dataset's basic info or the list of available bands."}})
def info(src_path=Depends(self.path_dependency), ban... | Custom Tiler Factory for MultiBandReader classes. Note: To be able to use the rio_tiler.io.MultiBandReader we need to be able to pass a `bands` argument to most of its methods. By using the `BandsExprParams` for the `layer_dependency`, the .tile(), .point(), .preview() and the .part() methods will receive bands or expr... | MultiBandTilerFactory | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiBandTilerFactory:
"""Custom Tiler Factory for MultiBandReader classes. Note: To be able to use the rio_tiler.io.MultiBandReader we need to be able to pass a `bands` argument to most of its methods. By using the `BandsExprParams` for the `layer_dependency`, the .tile(), .point(), .preview() a... | stack_v2_sparse_classes_75kplus_train_066558 | 48,399 | permissive | [
{
"docstring": "Register /info endpoint.",
"name": "info",
"signature": "def info(self)"
},
{
"docstring": "Register /metadata endpoint.",
"name": "metadata",
"signature": "def metadata(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_025189 | Implement the Python class `MultiBandTilerFactory` described below.
Class description:
Custom Tiler Factory for MultiBandReader classes. Note: To be able to use the rio_tiler.io.MultiBandReader we need to be able to pass a `bands` argument to most of its methods. By using the `BandsExprParams` for the `layer_dependenc... | Implement the Python class `MultiBandTilerFactory` described below.
Class description:
Custom Tiler Factory for MultiBandReader classes. Note: To be able to use the rio_tiler.io.MultiBandReader we need to be able to pass a `bands` argument to most of its methods. By using the `BandsExprParams` for the `layer_dependenc... | 2168c9284b39a46c4d1a095542c77addc690a738 | <|skeleton|>
class MultiBandTilerFactory:
"""Custom Tiler Factory for MultiBandReader classes. Note: To be able to use the rio_tiler.io.MultiBandReader we need to be able to pass a `bands` argument to most of its methods. By using the `BandsExprParams` for the `layer_dependency`, the .tile(), .point(), .preview() a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiBandTilerFactory:
"""Custom Tiler Factory for MultiBandReader classes. Note: To be able to use the rio_tiler.io.MultiBandReader we need to be able to pass a `bands` argument to most of its methods. By using the `BandsExprParams` for the `layer_dependency`, the .tile(), .point(), .preview() and the .part(... | the_stack_v2_python_sparse | src/titiler/core/titiler/core/factory.py | kylebarron/titiler | train | 0 |
6315e87ad725948c6e3299ee34916634276d9e83 | [
"curs.execute('DROP TABLE IF EXISTS jotd')\nconn.commit()\ncurs.execute(TBLDEF)\nconn.commit()\nself.starttime = datetime.datetime.today()\nday = self.starttime\nself.daycount = 50\nself.jokeDB = []\nself.datelist = []\nself.recipients = (('bill', 'bill@ourcompany.com'), ('teresa', 'teresa@ourcompany.com'))\nfor j ... | <|body_start_0|>
curs.execute('DROP TABLE IF EXISTS jotd')
conn.commit()
curs.execute(TBLDEF)
conn.commit()
self.starttime = datetime.datetime.today()
day = self.starttime
self.daycount = 50
self.jokeDB = []
self.datelist = []
self.recipien... | testEmailJoker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class testEmailJoker:
def setUp(self):
"""This method sets up a jotd table for each test; it uses only 2 mail recipients and a DAYCOUNT of 50. Also, the jokes are a single word with a numeric suffix for easy comparison"""
<|body_0|>
def test_numOfDates(self):
"""This metho... | stack_v2_sparse_classes_75kplus_train_066559 | 4,301 | no_license | [
{
"docstring": "This method sets up a jotd table for each test; it uses only 2 mail recipients and a DAYCOUNT of 50. Also, the jokes are a single word with a numeric suffix for easy comparison",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "This method tests the number of un... | 5 | stack_v2_sparse_classes_30k_train_035895 | Implement the Python class `testEmailJoker` described below.
Class description:
Implement the testEmailJoker class.
Method signatures and docstrings:
- def setUp(self): This method sets up a jotd table for each test; it uses only 2 mail recipients and a DAYCOUNT of 50. Also, the jokes are a single word with a numeric... | Implement the Python class `testEmailJoker` described below.
Class description:
Implement the testEmailJoker class.
Method signatures and docstrings:
- def setUp(self): This method sets up a jotd table for each test; it uses only 2 mail recipients and a DAYCOUNT of 50. Also, the jokes are a single word with a numeric... | b32f83aa1b705a5ad384b73c618f04f7d2622753 | <|skeleton|>
class testEmailJoker:
def setUp(self):
"""This method sets up a jotd table for each test; it uses only 2 mail recipients and a DAYCOUNT of 50. Also, the jokes are a single word with a numeric suffix for easy comparison"""
<|body_0|>
def test_numOfDates(self):
"""This metho... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class testEmailJoker:
def setUp(self):
"""This method sets up a jotd table for each test; it uses only 2 mail recipients and a DAYCOUNT of 50. Also, the jokes are a single word with a numeric suffix for easy comparison"""
curs.execute('DROP TABLE IF EXISTS jotd')
conn.commit()
curs.e... | the_stack_v2_python_sparse | ostPython2/testEmailJoker.py | deepbsd/OST_Python | train | 1 | |
e60bdf2928f121a623e928237f8ce8e684856c0d | [
"for x in range(30):\n for y in range(30):\n self.play_agent(x, y)\nfor x in range(30):\n for y in range(30):\n agent = self.board.at(x, y)\n agent.last_against = agent.curr_against\n agent.curr_against = {}\nfor x in range(30):\n for y in range(30):\n self.find_best_neig... | <|body_start_0|>
for x in range(30):
for y in range(30):
self.play_agent(x, y)
for x in range(30):
for y in range(30):
agent = self.board.at(x, y)
agent.last_against = agent.curr_against
agent.curr_against = {}
... | Runs a game using the imitation dynamics | ImitationGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImitationGame:
"""Runs a game using the imitation dynamics"""
def update(self):
"""Updates a single round of the game. The phases of the round are as follows: 1. Each agent first plays against all of its neighbors. Payoffs are calculated as the average of payoffs against all neighbor... | stack_v2_sparse_classes_75kplus_train_066560 | 3,767 | no_license | [
{
"docstring": "Updates a single round of the game. The phases of the round are as follows: 1. Each agent first plays against all of its neighbors. Payoffs are calculated as the average of payoffs against all neighbors played (thus border agents are roughly equal to inner agents). 2. Update agent states. 3. Eac... | 4 | stack_v2_sparse_classes_30k_train_005028 | Implement the Python class `ImitationGame` described below.
Class description:
Runs a game using the imitation dynamics
Method signatures and docstrings:
- def update(self): Updates a single round of the game. The phases of the round are as follows: 1. Each agent first plays against all of its neighbors. Payoffs are ... | Implement the Python class `ImitationGame` described below.
Class description:
Runs a game using the imitation dynamics
Method signatures and docstrings:
- def update(self): Updates a single round of the game. The phases of the round are as follows: 1. Each agent first plays against all of its neighbors. Payoffs are ... | 52b27e36474afef3d8d24a7c39d0cbb879e0184d | <|skeleton|>
class ImitationGame:
"""Runs a game using the imitation dynamics"""
def update(self):
"""Updates a single round of the game. The phases of the round are as follows: 1. Each agent first plays against all of its neighbors. Payoffs are calculated as the average of payoffs against all neighbor... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImitationGame:
"""Runs a game using the imitation dynamics"""
def update(self):
"""Updates a single round of the game. The phases of the round are as follows: 1. Each agent first plays against all of its neighbors. Payoffs are calculated as the average of payoffs against all neighbors played (thu... | the_stack_v2_python_sparse | pyevo/imitation_game.py | nwoodbury/pyevo | train | 0 |
21fc6e841f7199644b0aa303dd09016408662a62 | [
"thread_name = thread_name + '-checker'\nsuper(Checker, self).__init__(name=thread_name)\nself.q = q\nself.q_new_item = q_new_item\nself.device_details = device_details\nself.experimental_details = experimental_details",
"log = localdb.Database()\ndevice_type = self.device_details['device_type']\nhw_class = getat... | <|body_start_0|>
thread_name = thread_name + '-checker'
super(Checker, self).__init__(name=thread_name)
self.q = q
self.q_new_item = q_new_item
self.device_details = device_details
self.experimental_details = experimental_details
<|end_body_0|>
<|body_start_1|>
l... | Checks the shared queue for commands and forwards them to its actual device. | Checker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Checker:
"""Checks the shared queue for commands and forwards them to its actual device."""
def __init__(self, q, q_new_item, device_details, thread_name, experimental_details):
""":param q: queue.Queue() object, commands are put in it :param q_new_item: queue.Event() object, is set ... | stack_v2_sparse_classes_75kplus_train_066561 | 3,014 | no_license | [
{
"docstring": ":param q: queue.Queue() object, commands are put in it :param q_new_item: queue.Event() object, is set when new commands are added to it, which triggers the checker :param device_details: dict, check documentation.txt :param thread_name: name of the thread, used to identify and keep in tact acti... | 2 | stack_v2_sparse_classes_30k_train_052596 | Implement the Python class `Checker` described below.
Class description:
Checks the shared queue for commands and forwards them to its actual device.
Method signatures and docstrings:
- def __init__(self, q, q_new_item, device_details, thread_name, experimental_details): :param q: queue.Queue() object, commands are p... | Implement the Python class `Checker` described below.
Class description:
Checks the shared queue for commands and forwards them to its actual device.
Method signatures and docstrings:
- def __init__(self, q, q_new_item, device_details, thread_name, experimental_details): :param q: queue.Queue() object, commands are p... | 3370746338fc1d94cee7fd26a78fe1695917b677 | <|skeleton|>
class Checker:
"""Checks the shared queue for commands and forwards them to its actual device."""
def __init__(self, q, q_new_item, device_details, thread_name, experimental_details):
""":param q: queue.Queue() object, commands are put in it :param q_new_item: queue.Event() object, is set ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Checker:
"""Checks the shared queue for commands and forwards them to its actual device."""
def __init__(self, q, q_new_item, device_details, thread_name, experimental_details):
""":param q: queue.Queue() object, commands are put in it :param q_new_item: queue.Event() object, is set when new comm... | the_stack_v2_python_sparse | DataManager/executioner.py | SmartBioTech/PBRcontrol | train | 2 |
1809d94b541997f992d2882fa9785f17d444c534 | [
"client_fdfs = FDFS_Client_Meiduo()\nimage = validated_data.get('image')\nres = client_fdfs.upload(image)\nif res == 'Failed!':\n return serializers.ValidationError({'error': '图片上传失败'})\nsku_img = SKUImage.objects.create(sku=validated_data['sku'], image=res)\ngenerate_static_sku_detail_html.delay(sku_img.sku.id)... | <|body_start_0|>
client_fdfs = FDFS_Client_Meiduo()
image = validated_data.get('image')
res = client_fdfs.upload(image)
if res == 'Failed!':
return serializers.ValidationError({'error': '图片上传失败'})
sku_img = SKUImage.objects.create(sku=validated_data['sku'], image=res)... | SKUImages序列化器 | ImagesSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImagesSerializer:
"""SKUImages序列化器"""
def create(self, validated_data):
"""上传图片"""
<|body_0|>
def update(self, instance, validated_data):
"""更新图片"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
client_fdfs = FDFS_Client_Meiduo()
image = ... | stack_v2_sparse_classes_75kplus_train_066562 | 1,999 | no_license | [
{
"docstring": "上传图片",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "更新图片",
"name": "update",
"signature": "def update(self, instance, validated_data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017340 | Implement the Python class `ImagesSerializer` described below.
Class description:
SKUImages序列化器
Method signatures and docstrings:
- def create(self, validated_data): 上传图片
- def update(self, instance, validated_data): 更新图片 | Implement the Python class `ImagesSerializer` described below.
Class description:
SKUImages序列化器
Method signatures and docstrings:
- def create(self, validated_data): 上传图片
- def update(self, instance, validated_data): 更新图片
<|skeleton|>
class ImagesSerializer:
"""SKUImages序列化器"""
def create(self, validated_da... | e3976cbb9e96a1558f4e00abed1c61d887f915b1 | <|skeleton|>
class ImagesSerializer:
"""SKUImages序列化器"""
def create(self, validated_data):
"""上传图片"""
<|body_0|>
def update(self, instance, validated_data):
"""更新图片"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImagesSerializer:
"""SKUImages序列化器"""
def create(self, validated_data):
"""上传图片"""
client_fdfs = FDFS_Client_Meiduo()
image = validated_data.get('image')
res = client_fdfs.upload(image)
if res == 'Failed!':
return serializers.ValidationError({'error': '... | the_stack_v2_python_sparse | meiduo_mall/meiduo_mall/apps/meiduo_admin/serializers/images.py | yi0506/meiduo | train | 0 |
ad163d3a8e61fddc80a5e27edff15e7305566f16 | [
"if save_format.startswith(PTExportFormat.ONNX):\n split_format = save_format.split('_')\n opset = None\n if len(split_format) == 1:\n opset = PTExporter._ONNX_DEFAULT_OPSET\n elif len(split_format) == 2:\n opset = int(split_format[1])\n if opset is not None and opset <= 0:\n rai... | <|body_start_0|>
if save_format.startswith(PTExportFormat.ONNX):
split_format = save_format.split('_')
opset = None
if len(split_format) == 1:
opset = PTExporter._ONNX_DEFAULT_OPSET
elif len(split_format) == 2:
opset = int(split_for... | This class provides export of the compressed model to the ONNX format. | PTExporter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PTExporter:
"""This class provides export of the compressed model to the ONNX format."""
def parse_format(save_format: str) -> Tuple[str, dict]:
"""Parse saving format to a short form and additional arguments. :param save_format: Saving format. :return str: short form of the save_for... | stack_v2_sparse_classes_75kplus_train_066563 | 7,785 | permissive | [
{
"docstring": "Parse saving format to a short form and additional arguments. :param save_format: Saving format. :return str: short form of the save_format dict: additional arguments for exporter",
"name": "parse_format",
"signature": "def parse_format(save_format: str) -> Tuple[str, dict]"
},
{
... | 4 | stack_v2_sparse_classes_30k_train_015789 | Implement the Python class `PTExporter` described below.
Class description:
This class provides export of the compressed model to the ONNX format.
Method signatures and docstrings:
- def parse_format(save_format: str) -> Tuple[str, dict]: Parse saving format to a short form and additional arguments. :param save_forma... | Implement the Python class `PTExporter` described below.
Class description:
This class provides export of the compressed model to the ONNX format.
Method signatures and docstrings:
- def parse_format(save_format: str) -> Tuple[str, dict]: Parse saving format to a short form and additional arguments. :param save_forma... | c027c8b43c4865d46b8de01d8350dd338ec5a874 | <|skeleton|>
class PTExporter:
"""This class provides export of the compressed model to the ONNX format."""
def parse_format(save_format: str) -> Tuple[str, dict]:
"""Parse saving format to a short form and additional arguments. :param save_format: Saving format. :return str: short form of the save_for... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PTExporter:
"""This class provides export of the compressed model to the ONNX format."""
def parse_format(save_format: str) -> Tuple[str, dict]:
"""Parse saving format to a short form and additional arguments. :param save_format: Saving format. :return str: short form of the save_format dict: add... | the_stack_v2_python_sparse | nncf/torch/exporter.py | openvinotoolkit/nncf | train | 558 |
69dd5729fbef3f612bfe695aaabb5586cedbfc02 | [
"assert isinstance(attr_key, str)\nassert isinstance(attr_value, list)\nreturn attr_key + ' = []'",
"assert isinstance(attr_value, list)\nif isinstance(attr_value[0], dict):\n return attr_value[0]\nBaseCodeGenerator.get_dict_rep(self, attr_key, attr_value)"
] | <|body_start_0|>
assert isinstance(attr_key, str)
assert isinstance(attr_value, list)
return attr_key + ' = []'
<|end_body_0|>
<|body_start_1|>
assert isinstance(attr_value, list)
if isinstance(attr_value[0], dict):
return attr_value[0]
BaseCodeGenerator.get_... | CodeGenerator for List data. :params: Same as :class:`BaseCodeGenerator`. | ListCodeGenerator | [
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-1.0-or-later",
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"LicenseRef-scancode-unknown-license-reference",
"HPND",
"GPL-2.0-onl... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListCodeGenerator:
"""CodeGenerator for List data. :params: Same as :class:`BaseCodeGenerator`."""
def generate_code(self, attr_key, attr_value):
"""See :meth:`.Data_Handler.BaseCodeGenerator.generate_code`"""
<|body_0|>
def get_dict_rep(self, attr_key, attr_value):
... | stack_v2_sparse_classes_75kplus_train_066564 | 5,117 | permissive | [
{
"docstring": "See :meth:`.Data_Handler.BaseCodeGenerator.generate_code`",
"name": "generate_code",
"signature": "def generate_code(self, attr_key, attr_value)"
},
{
"docstring": "See :meth:`.Data_Handler.BaseCodeGenerator.get_dict_rep`",
"name": "get_dict_rep",
"signature": "def get_di... | 2 | stack_v2_sparse_classes_30k_train_030065 | Implement the Python class `ListCodeGenerator` described below.
Class description:
CodeGenerator for List data. :params: Same as :class:`BaseCodeGenerator`.
Method signatures and docstrings:
- def generate_code(self, attr_key, attr_value): See :meth:`.Data_Handler.BaseCodeGenerator.generate_code`
- def get_dict_rep(s... | Implement the Python class `ListCodeGenerator` described below.
Class description:
CodeGenerator for List data. :params: Same as :class:`BaseCodeGenerator`.
Method signatures and docstrings:
- def generate_code(self, attr_key, attr_value): See :meth:`.Data_Handler.BaseCodeGenerator.generate_code`
- def get_dict_rep(s... | 78c02e5fbb129b1bc4147bd55eec2882267d7e87 | <|skeleton|>
class ListCodeGenerator:
"""CodeGenerator for List data. :params: Same as :class:`BaseCodeGenerator`."""
def generate_code(self, attr_key, attr_value):
"""See :meth:`.Data_Handler.BaseCodeGenerator.generate_code`"""
<|body_0|>
def get_dict_rep(self, attr_key, attr_value):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ListCodeGenerator:
"""CodeGenerator for List data. :params: Same as :class:`BaseCodeGenerator`."""
def generate_code(self, attr_key, attr_value):
"""See :meth:`.Data_Handler.BaseCodeGenerator.generate_code`"""
assert isinstance(attr_key, str)
assert isinstance(attr_value, list)
... | the_stack_v2_python_sparse | QCA4020_SDK/QCA4020_SDK/target/sectools/qdn/sectools/common/utils/datautils/list_handler.py | r8d8/lastlock | train | 1 |
cd02198ea920f3f8334794de34ed6d3c8ef69bd2 | [
"configurations = config.Config()\nself.SEED = configurations.SEED\nself.relational = risk.graphing.relational.Relational()",
"ax = self.relational.figure(width=3.9, height=3.3)\nkmc = sklearn.cluster.KMeans(random_state=self.SEED, max_iter=1000, algorithm='full')\nybc = yellowbrick.cluster.KElbowVisualizer(estim... | <|body_start_0|>
configurations = config.Config()
self.SEED = configurations.SEED
self.relational = risk.graphing.relational.Relational()
<|end_body_0|>
<|body_start_1|>
ax = self.relational.figure(width=3.9, height=3.3)
kmc = sklearn.cluster.KMeans(random_state=self.SEED, max_i... | Knee | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Knee:
def __init__(self):
"""Constructor"""
<|body_0|>
def exc(self, blob: pd.DataFrame, target: str) -> int:
""":param blob: The data set that will be sampled :param target: The labels field :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_066565 | 1,017 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":param blob: The data set that will be sampled :param target: The labels field :return:",
"name": "exc",
"signature": "def exc(self, blob: pd.DataFrame, target: str) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_019493 | Implement the Python class `Knee` described below.
Class description:
Implement the Knee class.
Method signatures and docstrings:
- def __init__(self): Constructor
- def exc(self, blob: pd.DataFrame, target: str) -> int: :param blob: The data set that will be sampled :param target: The labels field :return: | Implement the Python class `Knee` described below.
Class description:
Implement the Knee class.
Method signatures and docstrings:
- def __init__(self): Constructor
- def exc(self, blob: pd.DataFrame, target: str) -> int: :param blob: The data set that will be sampled :param target: The labels field :return:
<|skelet... | 64e34318fd7c7797d56287973d5749b23f7a5088 | <|skeleton|>
class Knee:
def __init__(self):
"""Constructor"""
<|body_0|>
def exc(self, blob: pd.DataFrame, target: str) -> int:
""":param blob: The data set that will be sampled :param target: The labels field :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Knee:
def __init__(self):
"""Constructor"""
configurations = config.Config()
self.SEED = configurations.SEED
self.relational = risk.graphing.relational.Relational()
def exc(self, blob: pd.DataFrame, target: str) -> int:
""":param blob: The data set that will be sam... | the_stack_v2_python_sparse | risk/functions/knee.py | exhypotheses/risk | train | 0 | |
64a42b19e60bf8e315ae0d59d9c427ccdbb852a4 | [
"self.context_window = context_window\nlogging.config.fileConfig(__file__.rsplit('\\\\', 1)[0] + '/feature_extractor_logger.conf')\nlogger = logging.getLogger(self.__class__.__name__)\nlogger.setLevel(logging.DEBUG)\nself.features = {}\nlogger.info('The features that I will be extracting:')\nfor feature in dir(feat... | <|body_start_0|>
self.context_window = context_window
logging.config.fileConfig(__file__.rsplit('\\', 1)[0] + '/feature_extractor_logger.conf')
logger = logging.getLogger(self.__class__.__name__)
logger.setLevel(logging.DEBUG)
self.features = {}
logger.info('The features ... | A feature extractor for a Seinfeld line. The input is this line, the previous 3 lines and next 3 lines. | FeatureExtractor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureExtractor:
"""A feature extractor for a Seinfeld line. The input is this line, the previous 3 lines and next 3 lines."""
def __init__(self, context_window=7):
""":param line: a Line namedtuple. :param context: the line's context, i.e an array of which the center is the line an... | stack_v2_sparse_classes_75kplus_train_066566 | 3,112 | permissive | [
{
"docstring": ":param line: a Line namedtuple. :param context: the line's context, i.e an array of which the center is the line and the sides are the preceding /prefixing lines.",
"name": "__init__",
"signature": "def __init__(self, context_window=7)"
},
{
"docstring": ":param line: A line from... | 4 | stack_v2_sparse_classes_30k_train_024729 | Implement the Python class `FeatureExtractor` described below.
Class description:
A feature extractor for a Seinfeld line. The input is this line, the previous 3 lines and next 3 lines.
Method signatures and docstrings:
- def __init__(self, context_window=7): :param line: a Line namedtuple. :param context: the line's... | Implement the Python class `FeatureExtractor` described below.
Class description:
A feature extractor for a Seinfeld line. The input is this line, the previous 3 lines and next 3 lines.
Method signatures and docstrings:
- def __init__(self, context_window=7): :param line: a Line namedtuple. :param context: the line's... | b1e1a5208d2d3499144743028205336f8ca34552 | <|skeleton|>
class FeatureExtractor:
"""A feature extractor for a Seinfeld line. The input is this line, the previous 3 lines and next 3 lines."""
def __init__(self, context_window=7):
""":param line: a Line namedtuple. :param context: the line's context, i.e an array of which the center is the line an... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FeatureExtractor:
"""A feature extractor for a Seinfeld line. The input is this line, the previous 3 lines and next 3 lines."""
def __init__(self, context_window=7):
""":param line: a Line namedtuple. :param context: the line's context, i.e an array of which the center is the line and the sides a... | the_stack_v2_python_sparse | seinfeld_laugh_corpus/humor_recogniser/feature_extractor.py | ranyadshalom/seinfeld_laugh_corpus | train | 1 |
deb74ab795854c9cb1325844c0f15c7b24c20cf3 | [
"super().__init__(*args, method=method, **kwargs)\nif method not in RotateCaptchaEnm.list_values():\n raise ValueError(f'Invalid method parameter set, available - {RotateCaptchaEnm.list_values()}')",
"if captcha_file:\n self.post_payload.update({'body': base64.b64encode(self._local_file_captcha(captcha_file... | <|body_start_0|>
super().__init__(*args, method=method, **kwargs)
if method not in RotateCaptchaEnm.list_values():
raise ValueError(f'Invalid method parameter set, available - {RotateCaptchaEnm.list_values()}')
<|end_body_0|>
<|body_start_1|>
if captcha_file:
self.post_p... | The class is used to work with RotateCaptcha Solve description: | RotateCaptcha | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RotateCaptcha:
"""The class is used to work with RotateCaptcha Solve description:"""
def __init__(self, method: str=RotateCaptchaEnm.ROTATECAPTCHA.value, *args, **kwargs):
"""The class is used to work with Rotate Captcha. Args: method: Captcha type kwargs: Not required params for tas... | stack_v2_sparse_classes_75kplus_train_066567 | 7,016 | permissive | [
{
"docstring": "The class is used to work with Rotate Captcha. Args: method: Captcha type kwargs: Not required params for task creation request Examples: >>> RotateCaptcha(rucaptcha_key=\"aa9011f31111181111168611f1151122\", ... ).captcha_handler(captcha_file=\"examples/rotate/rotate_ex.png\") { 'captchaSolve': ... | 3 | stack_v2_sparse_classes_30k_train_023748 | Implement the Python class `RotateCaptcha` described below.
Class description:
The class is used to work with RotateCaptcha Solve description:
Method signatures and docstrings:
- def __init__(self, method: str=RotateCaptchaEnm.ROTATECAPTCHA.value, *args, **kwargs): The class is used to work with Rotate Captcha. Args:... | Implement the Python class `RotateCaptcha` described below.
Class description:
The class is used to work with RotateCaptcha Solve description:
Method signatures and docstrings:
- def __init__(self, method: str=RotateCaptchaEnm.ROTATECAPTCHA.value, *args, **kwargs): The class is used to work with Rotate Captcha. Args:... | 81333168946b063410f2434c7344062cb563faed | <|skeleton|>
class RotateCaptcha:
"""The class is used to work with RotateCaptcha Solve description:"""
def __init__(self, method: str=RotateCaptchaEnm.ROTATECAPTCHA.value, *args, **kwargs):
"""The class is used to work with Rotate Captcha. Args: method: Captcha type kwargs: Not required params for tas... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RotateCaptcha:
"""The class is used to work with RotateCaptcha Solve description:"""
def __init__(self, method: str=RotateCaptchaEnm.ROTATECAPTCHA.value, *args, **kwargs):
"""The class is used to work with Rotate Captcha. Args: method: Captcha type kwargs: Not required params for task creation re... | the_stack_v2_python_sparse | src/python_rucaptcha/rotate_captcha.py | AndreiDrang/python-rucaptcha | train | 103 |
4e41f874aa9b8b59bacbc526ae2b0265e3444895 | [
"self.version = version\nself.socc = socc\nself.uuid = uuid\nself.rotid_rkh_revocation = rotid_rkh_revocation\nself.rotid_rkth_hash = rotid_rkth_hash\nself.cc_soc_pinned = cc_soc_pinned\nself.cc_soc_default = cc_soc_default\nself.cc_vu = cc_vu\nself.challenge = challenge",
"msg = f'Version : {self.... | <|body_start_0|>
self.version = version
self.socc = socc
self.uuid = uuid
self.rotid_rkh_revocation = rotid_rkh_revocation
self.rotid_rkth_hash = rotid_rkth_hash
self.cc_soc_pinned = cc_soc_pinned
self.cc_soc_default = cc_soc_default
self.cc_vu = cc_vu
... | Base class for DebugAuthenticationChallenge. | DebugAuthenticationChallenge | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DebugAuthenticationChallenge:
"""Base class for DebugAuthenticationChallenge."""
def __init__(self, version: str, socc: int, uuid: bytes, rotid_rkh_revocation: int, rotid_rkth_hash: bytes, cc_soc_pinned: int, cc_soc_default: int, cc_vu: int, challenge: bytes) -> None:
"""Initialize t... | stack_v2_sparse_classes_75kplus_train_066568 | 4,011 | permissive | [
{
"docstring": "Initialize the DebugAuthenticationChallenge object. :param version: The string representing version: for RSA: 1.0, for ECC: 2.0, 2.1, 2.2 :param socc: The SoC Class that this credential applies to :param uuid: The string representing the unique device identifier :param rotid_rkh_revocation: Stat... | 4 | null | Implement the Python class `DebugAuthenticationChallenge` described below.
Class description:
Base class for DebugAuthenticationChallenge.
Method signatures and docstrings:
- def __init__(self, version: str, socc: int, uuid: bytes, rotid_rkh_revocation: int, rotid_rkth_hash: bytes, cc_soc_pinned: int, cc_soc_default:... | Implement the Python class `DebugAuthenticationChallenge` described below.
Class description:
Base class for DebugAuthenticationChallenge.
Method signatures and docstrings:
- def __init__(self, version: str, socc: int, uuid: bytes, rotid_rkh_revocation: int, rotid_rkth_hash: bytes, cc_soc_pinned: int, cc_soc_default:... | 4a31fb091f95fb035bc66241ee4e02dabb580072 | <|skeleton|>
class DebugAuthenticationChallenge:
"""Base class for DebugAuthenticationChallenge."""
def __init__(self, version: str, socc: int, uuid: bytes, rotid_rkh_revocation: int, rotid_rkth_hash: bytes, cc_soc_pinned: int, cc_soc_default: int, cc_vu: int, challenge: bytes) -> None:
"""Initialize t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DebugAuthenticationChallenge:
"""Base class for DebugAuthenticationChallenge."""
def __init__(self, version: str, socc: int, uuid: bytes, rotid_rkh_revocation: int, rotid_rkth_hash: bytes, cc_soc_pinned: int, cc_soc_default: int, cc_vu: int, challenge: bytes) -> None:
"""Initialize the DebugAuthe... | the_stack_v2_python_sparse | spsdk/dat/dac_packet.py | AdrianCano-01/spsdk | train | 0 |
99b23e9ba6c8b4521f0c2ce3b08923a2e46e94fd | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn UserExperienceAnalyticsAppHealthAppPerformanceByAppVersionDetails()",
"from .entity import Entity\nfrom .entity import Entity\nfields: Dict[str, Callable[[Any], None]] = {'appCrashCount': lambda n: setattr(self, 'app_crash_count', n.ge... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return UserExperienceAnalyticsAppHealthAppPerformanceByAppVersionDetails()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .entity import Entity
fields: Dict[str, Callab... | The user experience analytics application performance entity contains application performance by application version details. | UserExperienceAnalyticsAppHealthAppPerformanceByAppVersionDetails | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserExperienceAnalyticsAppHealthAppPerformanceByAppVersionDetails:
"""The user experience analytics application performance entity contains application performance by application version details."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAn... | stack_v2_sparse_classes_75kplus_train_066569 | 4,696 | 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: UserExperienceAnalyticsAppHealthAppPerformanceByAppVersionDetails",
"name": "create_from_discriminator_value",
... | 3 | stack_v2_sparse_classes_30k_train_013508 | Implement the Python class `UserExperienceAnalyticsAppHealthAppPerformanceByAppVersionDetails` described below.
Class description:
The user experience analytics application performance entity contains application performance by application version details.
Method signatures and docstrings:
- def create_from_discrimin... | Implement the Python class `UserExperienceAnalyticsAppHealthAppPerformanceByAppVersionDetails` described below.
Class description:
The user experience analytics application performance entity contains application performance by application version details.
Method signatures and docstrings:
- def create_from_discrimin... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class UserExperienceAnalyticsAppHealthAppPerformanceByAppVersionDetails:
"""The user experience analytics application performance entity contains application performance by application version details."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAn... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserExperienceAnalyticsAppHealthAppPerformanceByAppVersionDetails:
"""The user experience analytics application performance entity contains application performance by application version details."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsAppHea... | the_stack_v2_python_sparse | msgraph/generated/models/user_experience_analytics_app_health_app_performance_by_app_version_details.py | microsoftgraph/msgraph-sdk-python | train | 135 |
7f8bebe0bd40aa6caa416b7e0a40529b71406652 | [
"if not root:\n return False\nstack = [(root, target - root.val)]\nwhile stack:\n root, curr_sum = stack.pop()\n if not root.left and (not root.right) and (curr_sum == 0):\n return True\n if root.left:\n stack.append((root.left, curr_sum - root.left.val))\n if root.right:\n stack... | <|body_start_0|>
if not root:
return False
stack = [(root, target - root.val)]
while stack:
root, curr_sum = stack.pop()
if not root.left and (not root.right) and (curr_sum == 0):
return True
if root.left:
stack.appe... | BinaryTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinaryTree:
def is_path_sum(self, root: 'TreeNode', target: int) -> bool:
"""Approach: Iterative Time Complexity: O(N) Space Complexity: O(log N) :param root: :param target: :return:"""
<|body_0|>
def is_path_sum_(self, root: 'TreeNode', target: int) -> bool:
"""Appr... | stack_v2_sparse_classes_75kplus_train_066570 | 1,476 | no_license | [
{
"docstring": "Approach: Iterative Time Complexity: O(N) Space Complexity: O(log N) :param root: :param target: :return:",
"name": "is_path_sum",
"signature": "def is_path_sum(self, root: 'TreeNode', target: int) -> bool"
},
{
"docstring": "Approach: Recursion Time Complexity: O(N) Space Comple... | 2 | null | Implement the Python class `BinaryTree` described below.
Class description:
Implement the BinaryTree class.
Method signatures and docstrings:
- def is_path_sum(self, root: 'TreeNode', target: int) -> bool: Approach: Iterative Time Complexity: O(N) Space Complexity: O(log N) :param root: :param target: :return:
- def ... | Implement the Python class `BinaryTree` described below.
Class description:
Implement the BinaryTree class.
Method signatures and docstrings:
- def is_path_sum(self, root: 'TreeNode', target: int) -> bool: Approach: Iterative Time Complexity: O(N) Space Complexity: O(log N) :param root: :param target: :return:
- def ... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class BinaryTree:
def is_path_sum(self, root: 'TreeNode', target: int) -> bool:
"""Approach: Iterative Time Complexity: O(N) Space Complexity: O(log N) :param root: :param target: :return:"""
<|body_0|>
def is_path_sum_(self, root: 'TreeNode', target: int) -> bool:
"""Appr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BinaryTree:
def is_path_sum(self, root: 'TreeNode', target: int) -> bool:
"""Approach: Iterative Time Complexity: O(N) Space Complexity: O(log N) :param root: :param target: :return:"""
if not root:
return False
stack = [(root, target - root.val)]
while stack:
... | the_stack_v2_python_sparse | revisited/trees/path_sum.py | Shiv2157k/leet_code | train | 1 | |
1c8ed6d4f3895ccde3a9c1b7cc7bf622d2d1c4aa | [
"names = dict()\nparents = dict()\nfor name, *emails in accounts:\n for email in emails:\n while email in parents and email != parents[email]:\n p = parents[email]\n parents[email] = emails[0]\n email = p\n parents[email] = emails[0]\n names[emails[0]] = name\nem... | <|body_start_0|>
names = dict()
parents = dict()
for name, *emails in accounts:
for email in emails:
while email in parents and email != parents[email]:
p = parents[email]
parents[email] = emails[0]
email = p... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
"""09/03/2020 17:27"""
<|body_0|>
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
"""Union find"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n... | stack_v2_sparse_classes_75kplus_train_066571 | 5,564 | no_license | [
{
"docstring": "09/03/2020 17:27",
"name": "accountsMerge",
"signature": "def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]"
},
{
"docstring": "Union find",
"name": "accountsMerge",
"signature": "def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]"
... | 2 | stack_v2_sparse_classes_30k_train_026006 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]: 09/03/2020 17:27
- def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]: Union find | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]: 09/03/2020 17:27
- def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]: Union find
<|ske... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
"""09/03/2020 17:27"""
<|body_0|>
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
"""Union find"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
"""09/03/2020 17:27"""
names = dict()
parents = dict()
for name, *emails in accounts:
for email in emails:
while email in parents and email != parents[email]:
... | the_stack_v2_python_sparse | leetcode/solved/721_Accounts_Merge/solution.py | sungminoh/algorithms | train | 0 | |
fbc71fc9cb47523ce6a7b1aed3f1c24b3723846b | [
"nums = [i ** 2 for i in range(1, n + 1) if i ** 2 <= n]\ndp = [10 ** 4] * (n + 1)\ndp[0] = 0\nfor j in range(1, n + 1):\n for num in nums:\n if j >= num:\n dp[j] = min(dp[j], dp[j - num] + 1)\nreturn dp[n]",
"nums = [i ** 2 for i in range(1, n + 1) if i ** 2 <= n]\ndp = [10 ** 4] * (n + 1)\n... | <|body_start_0|>
nums = [i ** 2 for i in range(1, n + 1) if i ** 2 <= n]
dp = [10 ** 4] * (n + 1)
dp[0] = 0
for j in range(1, n + 1):
for num in nums:
if j >= num:
dp[j] = min(dp[j], dp[j - num] + 1)
return dp[n]
<|end_body_0|>
<|b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSquares(self, n: int) -> int:
"""版本一"""
<|body_0|>
def numSquares1(self, n: int) -> int:
"""版本二"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
nums = [i ** 2 for i in range(1, n + 1) if i ** 2 <= n]
dp = [10 ** 4] * (n + 1)... | stack_v2_sparse_classes_75kplus_train_066572 | 1,301 | no_license | [
{
"docstring": "版本一",
"name": "numSquares",
"signature": "def numSquares(self, n: int) -> int"
},
{
"docstring": "版本二",
"name": "numSquares1",
"signature": "def numSquares1(self, n: int) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_val_001486 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares(self, n: int) -> int: 版本一
- def numSquares1(self, n: int) -> int: 版本二 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares(self, n: int) -> int: 版本一
- def numSquares1(self, n: int) -> int: 版本二
<|skeleton|>
class Solution:
def numSquares(self, n: int) -> int:
"""版本一"""
... | 9aee4fa0ea211d28ff1e5d9b70597421f9562959 | <|skeleton|>
class Solution:
def numSquares(self, n: int) -> int:
"""版本一"""
<|body_0|>
def numSquares1(self, n: int) -> int:
"""版本二"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def numSquares(self, n: int) -> int:
"""版本一"""
nums = [i ** 2 for i in range(1, n + 1) if i ** 2 <= n]
dp = [10 ** 4] * (n + 1)
dp[0] = 0
for j in range(1, n + 1):
for num in nums:
if j >= num:
dp[j] = min(dp[j],... | the_stack_v2_python_sparse | Python/numSquares.py | Litao439420999/LeetCodeAlgorithm | train | 0 | |
f9388c25b30a2c91e3dc6c31b945f6e137a77ff0 | [
"if len(coins) == 0:\n return -1\nif amount == 0:\n return 0\ncoins.sort()\ndp = [amount + 1] * (amount + 1)\nfor i in range(1, amount + 1):\n for c in coins:\n if i == c:\n dp[i] = 1\n elif i - c > 0 and dp[i - c] > 0:\n dp[i] = min(dp[i], dp[i - c] + 1)\n else:\... | <|body_start_0|>
if len(coins) == 0:
return -1
if amount == 0:
return 0
coins.sort()
dp = [amount + 1] * (amount + 1)
for i in range(1, amount + 1):
for c in coins:
if i == c:
dp[i] = 1
elif i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_0|>
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_75kplus_train_066573 | 2,034 | no_license | [
{
"docstring": ":type coins: List[int] :type amount: int :rtype: int",
"name": "coinChange",
"signature": "def coinChange(self, coins, amount)"
},
{
"docstring": ":type coins: List[int] :type amount: int :rtype: int",
"name": "coinChange",
"signature": "def coinChange(self, coins, amount... | 2 | stack_v2_sparse_classes_30k_train_032421 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: int
- def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: int
- def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: ... | 63b7eedc720c1ce14880b80744dcd5ef7107065c | <|skeleton|>
class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_0|>
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
if len(coins) == 0:
return -1
if amount == 0:
return 0
coins.sort()
dp = [amount + 1] * (amount + 1)
for i in range(1, amount + 1):
... | the_stack_v2_python_sparse | problems/coinChange.py | joddiy/leetcode | train | 1 | |
f35c4eeab4ae0f5bc1bdcaa90e18314256783d17 | [
"self.fmap_shape = fmap_shape\nself.indices = None\nself.indices_list = None",
"M, N = self.fmap_shape\nself.X = np.linspace(df.x.min(), df.x.max(), M)\nself.Y = np.linspace(df.y.min(), df.y.max(), N)",
"x = dfnew.x.values\ny = dfnew.y.values\nM, N = self.fmap_shape\nindices = []\nfor i in range(len(dfnew)):\n ... | <|body_start_0|>
self.fmap_shape = fmap_shape
self.indices = None
self.indices_list = None
<|end_body_0|>
<|body_start_1|>
M, N = self.fmap_shape
self.X = np.linspace(df.x.min(), df.x.max(), M)
self.Y = np.linspace(df.y.min(), df.y.max(), N)
<|end_body_1|>
<|body_start_... | Scatter2Array | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Scatter2Array:
def __init__(self, fmap_shape=(128, 128)):
"""convert x,y coords to numpy array"""
<|body_0|>
def _fit(self, df):
"""df: dataframe with x, y columns"""
<|body_1|>
def _transform(self, dfnew):
"""dfnew: dataframe with x, y columns i... | stack_v2_sparse_classes_75kplus_train_066574 | 7,104 | permissive | [
{
"docstring": "convert x,y coords to numpy array",
"name": "__init__",
"signature": "def __init__(self, fmap_shape=(128, 128))"
},
{
"docstring": "df: dataframe with x, y columns",
"name": "_fit",
"signature": "def _fit(self, df)"
},
{
"docstring": "dfnew: dataframe with x, y co... | 5 | stack_v2_sparse_classes_30k_train_034541 | Implement the Python class `Scatter2Array` described below.
Class description:
Implement the Scatter2Array class.
Method signatures and docstrings:
- def __init__(self, fmap_shape=(128, 128)): convert x,y coords to numpy array
- def _fit(self, df): df: dataframe with x, y columns
- def _transform(self, dfnew): dfnew:... | Implement the Python class `Scatter2Array` described below.
Class description:
Implement the Scatter2Array class.
Method signatures and docstrings:
- def __init__(self, fmap_shape=(128, 128)): convert x,y coords to numpy array
- def _fit(self, df): df: dataframe with x, y columns
- def _transform(self, dfnew): dfnew:... | a46526eb1094b87ffa387e357de9313cff7ff7e3 | <|skeleton|>
class Scatter2Array:
def __init__(self, fmap_shape=(128, 128)):
"""convert x,y coords to numpy array"""
<|body_0|>
def _fit(self, df):
"""df: dataframe with x, y columns"""
<|body_1|>
def _transform(self, dfnew):
"""dfnew: dataframe with x, y columns i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Scatter2Array:
def __init__(self, fmap_shape=(128, 128)):
"""convert x,y coords to numpy array"""
self.fmap_shape = fmap_shape
self.indices = None
self.indices_list = None
def _fit(self, df):
"""df: dataframe with x, y columns"""
M, N = self.fmap_shape
... | the_stack_v2_python_sparse | molmap/utils/matrixopt.py | shenwanxiang/bidd-molmap | train | 124 | |
4dc93ee6b10ddf8f87bc9cde6096284e2f3930a5 | [
"p = subprocess.Popen(['/usr/bin/sudo', '-n', '/sbin/reboot'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\nout, _ = p.communicate()\nerr = 'System failed to reboot (status %d): %s' % (p.returncode, out.strip())\nlogger.warn(err)\nraise ttypes.RndException(p.returncode, err)",
"cmd, opts = super(SystemProfi... | <|body_start_0|>
p = subprocess.Popen(['/usr/bin/sudo', '-n', '/sbin/reboot'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
out, _ = p.communicate()
err = 'System failed to reboot (status %d): %s' % (p.returncode, out.strip())
logger.warn(err)
raise ttypes.RndException(p.ret... | SystemProfiler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SystemProfiler:
def reboot(self):
"""reboot() Platform-specific procedure to reboot the system. Should be implemented in a subclass if platform is not POSIX"""
<|body_0|>
def getSubprocessOpts(self, cmd, **kwargs):
"""getSubprocessOpts(list|str cmd, **kwargs) -> (cmd... | stack_v2_sparse_classes_75kplus_train_066575 | 2,743 | permissive | [
{
"docstring": "reboot() Platform-specific procedure to reboot the system. Should be implemented in a subclass if platform is not POSIX",
"name": "reboot",
"signature": "def reboot(self)"
},
{
"docstring": "getSubprocessOpts(list|str cmd, **kwargs) -> (cmd, dict) Method for returning the appropr... | 2 | stack_v2_sparse_classes_30k_train_015075 | Implement the Python class `SystemProfiler` described below.
Class description:
Implement the SystemProfiler class.
Method signatures and docstrings:
- def reboot(self): reboot() Platform-specific procedure to reboot the system. Should be implemented in a subclass if platform is not POSIX
- def getSubprocessOpts(self... | Implement the Python class `SystemProfiler` described below.
Class description:
Implement the SystemProfiler class.
Method signatures and docstrings:
- def reboot(self): reboot() Platform-specific procedure to reboot the system. Should be implemented in a subclass if platform is not POSIX
- def getSubprocessOpts(self... | 5c19c78ce0579f624cc774ac260f3178286ccb07 | <|skeleton|>
class SystemProfiler:
def reboot(self):
"""reboot() Platform-specific procedure to reboot the system. Should be implemented in a subclass if platform is not POSIX"""
<|body_0|>
def getSubprocessOpts(self, cmd, **kwargs):
"""getSubprocessOpts(list|str cmd, **kwargs) -> (cmd... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SystemProfiler:
def reboot(self):
"""reboot() Platform-specific procedure to reboot the system. Should be implemented in a subclass if platform is not POSIX"""
p = subprocess.Popen(['/usr/bin/sudo', '-n', '/sbin/reboot'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
out, _ = p.com... | the_stack_v2_python_sparse | lib/python/plow/rndaemon/profile/posix.py | onexeno/plow | train | 0 | |
52ece4c97166a0325852f5589c321c3a39c46019 | [
"self.id = Customer.id_counter\nCustomer.id_counter += 1\nself.behave_per_month = behavior_rates\nself.behave_per_day = 1.0 / 30.0 * self.behave_per_month\nself.channel = channel_name\nif start_of_month:\n self.age = random.uniform(Customer.MIN_AGE, Customer.MAX_AGE)\n self.date_of_birth = start_of_month + re... | <|body_start_0|>
self.id = Customer.id_counter
Customer.id_counter += 1
self.behave_per_month = behavior_rates
self.behave_per_day = 1.0 / 30.0 * self.behave_per_month
self.channel = channel_name
if start_of_month:
self.age = random.uniform(Customer.MIN_AGE, C... | Customer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Customer:
def __init__(self, behavior_rates, satisfaction=None, channel_name='NA', start_of_month=None, country=None):
"""Creates a customer for simulation, given an ndarray of behavior rates, which are converted to daily. Each customer also has a unique integer id which will become the ... | stack_v2_sparse_classes_75kplus_train_066576 | 3,713 | permissive | [
{
"docstring": "Creates a customer for simulation, given an ndarray of behavior rates, which are converted to daily. Each customer also has a unique integer id which will become the account_id in the database, and holds its own subscriptions and events. :param behavior_rates: ndarray of behavior rates, which ar... | 2 | stack_v2_sparse_classes_30k_train_036849 | Implement the Python class `Customer` described below.
Class description:
Implement the Customer class.
Method signatures and docstrings:
- def __init__(self, behavior_rates, satisfaction=None, channel_name='NA', start_of_month=None, country=None): Creates a customer for simulation, given an ndarray of behavior rates... | Implement the Python class `Customer` described below.
Class description:
Implement the Customer class.
Method signatures and docstrings:
- def __init__(self, behavior_rates, satisfaction=None, channel_name='NA', start_of_month=None, country=None): Creates a customer for simulation, given an ndarray of behavior rates... | 9d9bfec7bbcb97e60ad8d1f614ae58d13b81ee16 | <|skeleton|>
class Customer:
def __init__(self, behavior_rates, satisfaction=None, channel_name='NA', start_of_month=None, country=None):
"""Creates a customer for simulation, given an ndarray of behavior rates, which are converted to daily. Each customer also has a unique integer id which will become the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Customer:
def __init__(self, behavior_rates, satisfaction=None, channel_name='NA', start_of_month=None, country=None):
"""Creates a customer for simulation, given an ndarray of behavior rates, which are converted to daily. Each customer also has a unique integer id which will become the account_id in ... | the_stack_v2_python_sparse | data-generation/py/customer.py | karthiks/fight-churn | train | 1 | |
84e52d59dd3fc8804cc3381bb6a0aaee62b312b9 | [
"guide = poutine.enum(guide, first_available_dim=self.max_iarange_nesting)\nfor i in range(self.num_particles):\n for guide_trace in iter_discrete_traces('flat', guide, *args, **kwargs):\n model_trace = poutine.trace(poutine.replay(model, trace=guide_trace), graph_type='flat').get_trace(*args, **kwargs)\n... | <|body_start_0|>
guide = poutine.enum(guide, first_available_dim=self.max_iarange_nesting)
for i in range(self.num_particles):
for guide_trace in iter_discrete_traces('flat', guide, *args, **kwargs):
model_trace = poutine.trace(poutine.replay(model, trace=guide_trace), graph_... | A trace implementation of ELBO-based SVI that supports enumeration over discrete sample sites. To enumerate over a sample site, the ``guide``'s sample site must specify either ``infer={'enumerate': 'sequential'}`` or ``infer={'enumerate': 'parallel'}``. To configure all sites at once, use :func:`~pyro.infer.enum.config... | TraceEnum_ELBO | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TraceEnum_ELBO:
"""A trace implementation of ELBO-based SVI that supports enumeration over discrete sample sites. To enumerate over a sample site, the ``guide``'s sample site must specify either ``infer={'enumerate': 'sequential'}`` or ``infer={'enumerate': 'parallel'}``. To configure all sites a... | stack_v2_sparse_classes_75kplus_train_066577 | 7,901 | permissive | [
{
"docstring": "runs the guide and runs the model against the guide with the result packaged as a trace generator",
"name": "_get_traces",
"signature": "def _get_traces(self, model, guide, *args, **kwargs)"
},
{
"docstring": ":returns: returns an estimate of the ELBO :rtype: float Estimates the ... | 3 | stack_v2_sparse_classes_30k_train_032698 | Implement the Python class `TraceEnum_ELBO` described below.
Class description:
A trace implementation of ELBO-based SVI that supports enumeration over discrete sample sites. To enumerate over a sample site, the ``guide``'s sample site must specify either ``infer={'enumerate': 'sequential'}`` or ``infer={'enumerate': ... | Implement the Python class `TraceEnum_ELBO` described below.
Class description:
A trace implementation of ELBO-based SVI that supports enumeration over discrete sample sites. To enumerate over a sample site, the ``guide``'s sample site must specify either ``infer={'enumerate': 'sequential'}`` or ``infer={'enumerate': ... | 3b5b2c5de208209365bf26f239f12521de68acc4 | <|skeleton|>
class TraceEnum_ELBO:
"""A trace implementation of ELBO-based SVI that supports enumeration over discrete sample sites. To enumerate over a sample site, the ``guide``'s sample site must specify either ``infer={'enumerate': 'sequential'}`` or ``infer={'enumerate': 'parallel'}``. To configure all sites a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TraceEnum_ELBO:
"""A trace implementation of ELBO-based SVI that supports enumeration over discrete sample sites. To enumerate over a sample site, the ``guide``'s sample site must specify either ``infer={'enumerate': 'sequential'}`` or ``infer={'enumerate': 'parallel'}``. To configure all sites at once, use :... | the_stack_v2_python_sparse | pyro/infer/traceenum_elbo.py | neerajprad/pyro | train | 1 |
5dd2d773e19da4a06c39730ad37300db03d08472 | [
"chosen_row = random.choice(range(len(array2D)))\nchosen_column = random.choice(array2D[chosen_row])\narray2D[chosen_row].remove(chosen_column)\nreturn (chosen_row, chosen_column)",
"dungeon_map = [[DungeonCell.EMPTY] * map_size for i in range(map_size)]\nfree_map_cells = [list(range(map_size)) for i in range(map... | <|body_start_0|>
chosen_row = random.choice(range(len(array2D)))
chosen_column = random.choice(array2D[chosen_row])
array2D[chosen_row].remove(chosen_column)
return (chosen_row, chosen_column)
<|end_body_0|>
<|body_start_1|>
dungeon_map = [[DungeonCell.EMPTY] * map_size for i in... | DungeonGameMapGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DungeonGameMapGenerator:
def __choose_random_index_and_remove(self, array2D):
"""Function chooses a random row and column in 2D array, returns it and removed it's cell from the array2D; :param array2D: a 2D array; :return: a pair of row and column index; :type array2D: a list of lists; :... | stack_v2_sparse_classes_75kplus_train_066578 | 2,235 | permissive | [
{
"docstring": "Function chooses a random row and column in 2D array, returns it and removed it's cell from the array2D; :param array2D: a 2D array; :return: a pair of row and column index; :type array2D: a list of lists; :rtype: a tuple of 2 integers.",
"name": "__choose_random_index_and_remove",
"sign... | 2 | stack_v2_sparse_classes_30k_train_024492 | Implement the Python class `DungeonGameMapGenerator` described below.
Class description:
Implement the DungeonGameMapGenerator class.
Method signatures and docstrings:
- def __choose_random_index_and_remove(self, array2D): Function chooses a random row and column in 2D array, returns it and removed it's cell from the... | Implement the Python class `DungeonGameMapGenerator` described below.
Class description:
Implement the DungeonGameMapGenerator class.
Method signatures and docstrings:
- def __choose_random_index_and_remove(self, array2D): Function chooses a random row and column in 2D array, returns it and removed it's cell from the... | 291592e97b6d8fe9f9e6627dc0023875918d3463 | <|skeleton|>
class DungeonGameMapGenerator:
def __choose_random_index_and_remove(self, array2D):
"""Function chooses a random row and column in 2D array, returns it and removed it's cell from the array2D; :param array2D: a 2D array; :return: a pair of row and column index; :type array2D: a list of lists; :... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DungeonGameMapGenerator:
def __choose_random_index_and_remove(self, array2D):
"""Function chooses a random row and column in 2D array, returns it and removed it's cell from the array2D; :param array2D: a 2D array; :return: a pair of row and column index; :type array2D: a list of lists; :rtype: a tuple... | the_stack_v2_python_sparse | Tihran_Katolikian/10/TKDungeonGamePkg/TKDungeonGamePkg/DungeonGameMapGenerator.py | SmischenkoB/campus_2018_python | train | 0 | |
03d6676cb0569c542778acd9a3767d1b9a28b7f6 | [
"row_A = len(A)\nrow_B = len(B)\ncol_B = len(B[0])\nc = [[0 for i in range(0, col_B)] for i in range(0, row_A)]\nfor row in range(0, len(c)):\n for col in range(0, len(c[0])):\n for k in range(0, row_B):\n c[row][col] += A[row][k] * B[k][col]\nreturn c",
"row_A = len(A)\nrow_B = len(B)\ncol_B... | <|body_start_0|>
row_A = len(A)
row_B = len(B)
col_B = len(B[0])
c = [[0 for i in range(0, col_B)] for i in range(0, row_A)]
for row in range(0, len(c)):
for col in range(0, len(c[0])):
for k in range(0, row_B):
c[row][col] += A[row... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def multiply(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]"""
<|body_0|>
def multiply_fast(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus_train_066579 | 2,016 | no_license | [
{
"docstring": ":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]",
"name": "multiply",
"signature": "def multiply(self, A, B)"
},
{
"docstring": ":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]",
"name": "multiply_fast",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_019987 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def multiply(self, A, B): :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]
- def multiply_fast(self, A, B): :type A: List[List[int]] :type B: List[List[i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def multiply(self, A, B): :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]
- def multiply_fast(self, A, B): :type A: List[List[int]] :type B: List[List[i... | 8731e2ccfbda9323ea5c8629599806cd1c37c3bf | <|skeleton|>
class Solution:
def multiply(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]"""
<|body_0|>
def multiply_fast(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def multiply(self, A, B):
""":type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]"""
row_A = len(A)
row_B = len(B)
col_B = len(B[0])
c = [[0 for i in range(0, col_B)] for i in range(0, row_A)]
for row in range(0, len(c)):
... | the_stack_v2_python_sparse | problems/SparseMatrixMult.py | jonu4u/DataStructuresInPython | train | 0 | |
3c16be858ecfb075c2cd5acd7c1741f9132c003f | [
"sep = '\\n'\noutput = sep.join(data)\nreturn output",
"sep = ' always_nxdomain\\nlocal-zone: '\noutput = sep.join(data)\noutput = 'local-zone: + output + always_nxdomain'\nreturn output"
] | <|body_start_0|>
sep = '\n'
output = sep.join(data)
return output
<|end_body_0|>
<|body_start_1|>
sep = ' always_nxdomain\nlocal-zone: '
output = sep.join(data)
output = 'local-zone: + output + always_nxdomain'
return output
<|end_body_1|>
| produce lists of data to write to a file, inserts formatting and header footers as required by the format NOTE: Validate elsewhere | Format | [
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Format:
"""produce lists of data to write to a file, inserts formatting and header footers as required by the format NOTE: Validate elsewhere"""
def newline(data):
"""easy just return the data with newlines no formatting required"""
<|body_0|>
def unbound_nxdomain(data):... | stack_v2_sparse_classes_75kplus_train_066580 | 3,019 | permissive | [
{
"docstring": "easy just return the data with newlines no formatting required",
"name": "newline",
"signature": "def newline(data)"
},
{
"docstring": "for use with unbound # TODO use generator to fix memory problems",
"name": "unbound_nxdomain",
"signature": "def unbound_nxdomain(data)"... | 2 | null | Implement the Python class `Format` described below.
Class description:
produce lists of data to write to a file, inserts formatting and header footers as required by the format NOTE: Validate elsewhere
Method signatures and docstrings:
- def newline(data): easy just return the data with newlines no formatting requir... | Implement the Python class `Format` described below.
Class description:
produce lists of data to write to a file, inserts formatting and header footers as required by the format NOTE: Validate elsewhere
Method signatures and docstrings:
- def newline(data): easy just return the data with newlines no formatting requir... | 4cda87fe31107e49b338d972824d3ec9fa61c9af | <|skeleton|>
class Format:
"""produce lists of data to write to a file, inserts formatting and header footers as required by the format NOTE: Validate elsewhere"""
def newline(data):
"""easy just return the data with newlines no formatting required"""
<|body_0|>
def unbound_nxdomain(data):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Format:
"""produce lists of data to write to a file, inserts formatting and header footers as required by the format NOTE: Validate elsewhere"""
def newline(data):
"""easy just return the data with newlines no formatting required"""
sep = '\n'
output = sep.join(data)
retur... | the_stack_v2_python_sparse | blacklistparser/core/Data.py | Armorless-Visage/blacklistparser | train | 0 |
9ed5a2425042d0e129ebe8034ec9ba2124835648 | [
"self.logger = policy.logger\nself.policy = policy\nself.yaml = policy.main_policy['locations']['locations_list'][idx]\nvalidate(self.logger, self.yaml, LOCATION_SCHEMA, 'location')\nvalidate_port_set_list(self.logger, self.yaml['port_set_list'], policy)\nself.name = self.yaml['name']\nself.port_set_list = self.yam... | <|body_start_0|>
self.logger = policy.logger
self.policy = policy
self.yaml = policy.main_policy['locations']['locations_list'][idx]
validate(self.logger, self.yaml, LOCATION_SCHEMA, 'location')
validate_port_set_list(self.logger, self.yaml['port_set_list'], policy)
self.... | An object that represents a single location | Location | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Location:
"""An object that represents a single location"""
def __init__(self, policy, idx):
"""Initialise the Location Class"""
<|body_0|>
def check(self, dpid, port):
"""Check a dpid/port to see if it is part of this location and if so return the string name of... | stack_v2_sparse_classes_75kplus_train_066581 | 38,856 | permissive | [
{
"docstring": "Initialise the Location Class",
"name": "__init__",
"signature": "def __init__(self, policy, idx)"
},
{
"docstring": "Check a dpid/port to see if it is part of this location and if so return the string name of the location otherwise return empty string",
"name": "check",
... | 2 | stack_v2_sparse_classes_30k_val_001459 | Implement the Python class `Location` described below.
Class description:
An object that represents a single location
Method signatures and docstrings:
- def __init__(self, policy, idx): Initialise the Location Class
- def check(self, dpid, port): Check a dpid/port to see if it is part of this location and if so retu... | Implement the Python class `Location` described below.
Class description:
An object that represents a single location
Method signatures and docstrings:
- def __init__(self, policy, idx): Initialise the Location Class
- def check(self, dpid, port): Check a dpid/port to see if it is part of this location and if so retu... | 55cc27e81defc42775ff563bfbef31800e089b14 | <|skeleton|>
class Location:
"""An object that represents a single location"""
def __init__(self, policy, idx):
"""Initialise the Location Class"""
<|body_0|>
def check(self, dpid, port):
"""Check a dpid/port to see if it is part of this location and if so return the string name of... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Location:
"""An object that represents a single location"""
def __init__(self, policy, idx):
"""Initialise the Location Class"""
self.logger = policy.logger
self.policy = policy
self.yaml = policy.main_policy['locations']['locations_list'][idx]
validate(self.logger... | the_stack_v2_python_sparse | nmeta/policy.py | awesome-nfv/nmeta | train | 0 |
2dd5cb92ee53c696071e1ed41b264ab33ee20b15 | [
"data = Fun_path.query.filter_by(classify=1).all()\nlist = [{'id': str(i.id), 'text': i.name, 'value': i.fun_id, 'pid': i.fa_id} for i in data]\nid = [str(i.id) for i in data]\ndi = {}\nfor i in id:\n re = []\n for j in list:\n if j['pid'] == i:\n re.append(j)\n if re != []:\n di[i... | <|body_start_0|>
data = Fun_path.query.filter_by(classify=1).all()
list = [{'id': str(i.id), 'text': i.name, 'value': i.fun_id, 'pid': i.fa_id} for i in data]
id = [str(i.id) for i in data]
di = {}
for i in id:
re = []
for j in list:
if j['... | Api_Path | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Api_Path:
def get(self):
"""menu为接口目录,parent为所有目录对象(用于前端关联父级目录使用)"""
<|body_0|>
def post(self):
"""增加或修改目录"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
data = Fun_path.query.filter_by(classify=1).all()
list = [{'id': str(i.id), 'text': i.... | stack_v2_sparse_classes_75kplus_train_066582 | 4,332 | no_license | [
{
"docstring": "menu为接口目录,parent为所有目录对象(用于前端关联父级目录使用)",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "增加或修改目录",
"name": "post",
"signature": "def post(self)"
}
] | 2 | null | Implement the Python class `Api_Path` described below.
Class description:
Implement the Api_Path class.
Method signatures and docstrings:
- def get(self): menu为接口目录,parent为所有目录对象(用于前端关联父级目录使用)
- def post(self): 增加或修改目录 | Implement the Python class `Api_Path` described below.
Class description:
Implement the Api_Path class.
Method signatures and docstrings:
- def get(self): menu为接口目录,parent为所有目录对象(用于前端关联父级目录使用)
- def post(self): 增加或修改目录
<|skeleton|>
class Api_Path:
def get(self):
"""menu为接口目录,parent为所有目录对象(用于前端关联父级目录使用)"... | 00658badbcbf9154c18353b7288680e7b8759300 | <|skeleton|>
class Api_Path:
def get(self):
"""menu为接口目录,parent为所有目录对象(用于前端关联父级目录使用)"""
<|body_0|>
def post(self):
"""增加或修改目录"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Api_Path:
def get(self):
"""menu为接口目录,parent为所有目录对象(用于前端关联父级目录使用)"""
data = Fun_path.query.filter_by(classify=1).all()
list = [{'id': str(i.id), 'text': i.name, 'value': i.fun_id, 'pid': i.fa_id} for i in data]
id = [str(i.id) for i in data]
di = {}
for i in id:... | the_stack_v2_python_sparse | app/main/resources/pubapi.py | tjn123456/ApiManageServer | train | 1 | |
9f2dde6fe21107185cc69b391b2f437cd067dcd7 | [
"if len(self.email_address) == 0:\n abort(400, 'no email address configured')\nsuccess, err_str = subscriber_op(self.fabric, MSG_TYPE.TEST_EMAIL, qnum=0)\nif success:\n return jsonify({'success': True})\nabort(500, err_str)",
"if len(self.syslog_server) == 0:\n abort(400, 'no syslog server configured')\n... | <|body_start_0|>
if len(self.email_address) == 0:
abort(400, 'no email address configured')
success, err_str = subscriber_op(self.fabric, MSG_TYPE.TEST_EMAIL, qnum=0)
if success:
return jsonify({'success': True})
abort(500, err_str)
<|end_body_0|>
<|body_start_1|... | ept settings per fabric auto created with defaults when fabric is created | eptSettings | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class eptSettings:
"""ept settings per fabric auto created with defaults when fabric is created"""
def test_email(self):
"""send a test email to ensure settings are valid and email notifications are successful"""
<|body_0|>
def test_syslog(self):
"""send a test syslog ... | stack_v2_sparse_classes_75kplus_train_066583 | 9,281 | permissive | [
{
"docstring": "send a test email to ensure settings are valid and email notifications are successful",
"name": "test_email",
"signature": "def test_email(self)"
},
{
"docstring": "send a test syslog to ensure settings are valid and syslog notifications are successful",
"name": "test_syslog"... | 2 | null | Implement the Python class `eptSettings` described below.
Class description:
ept settings per fabric auto created with defaults when fabric is created
Method signatures and docstrings:
- def test_email(self): send a test email to ensure settings are valid and email notifications are successful
- def test_syslog(self)... | Implement the Python class `eptSettings` described below.
Class description:
ept settings per fabric auto created with defaults when fabric is created
Method signatures and docstrings:
- def test_email(self): send a test email to ensure settings are valid and email notifications are successful
- def test_syslog(self)... | a4de84c5fc00549e6539dbc1d8d927c74a704dcc | <|skeleton|>
class eptSettings:
"""ept settings per fabric auto created with defaults when fabric is created"""
def test_email(self):
"""send a test email to ensure settings are valid and email notifications are successful"""
<|body_0|>
def test_syslog(self):
"""send a test syslog ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class eptSettings:
"""ept settings per fabric auto created with defaults when fabric is created"""
def test_email(self):
"""send a test email to ensure settings are valid and email notifications are successful"""
if len(self.email_address) == 0:
abort(400, 'no email address configur... | the_stack_v2_python_sparse | Service/app/models/aci/ept/ept_settings.py | Hrishi5/ACI-EnhancedEndpointTracker | train | 0 |
178287d23c96c09c9a2d4c68d6f4547ab7cadaee | [
"magnitudes, edges = np.histogram(data, bins)\nbin_width = edges[1] - edges[0]\nbin_sizes = magnitudes.astype(np.float) / (magnitudes.sum() * resolution)\nvalid_indices = np.where(bin_sizes >= 1)[0]\nif valid_indices.size == 0:\n raise ValueError('Resolution is too low. Cumulative distribution array is empty.')\... | <|body_start_0|>
magnitudes, edges = np.histogram(data, bins)
bin_width = edges[1] - edges[0]
bin_sizes = magnitudes.astype(np.float) / (magnitudes.sum() * resolution)
valid_indices = np.where(bin_sizes >= 1)[0]
if valid_indices.size == 0:
raise ValueError('Resolution... | Random number generator based on a modelled distribution. Given repeated observations of a single random variable, this object first models the probability distribution that governs the variable using a histogram. It then generates new variates according to this distribution. This sampler trades space for time by appro... | HistogramSampler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HistogramSampler:
"""Random number generator based on a modelled distribution. Given repeated observations of a single random variable, this object first models the probability distribution that governs the variable using a histogram. It then generates new variates according to this distribution.... | stack_v2_sparse_classes_75kplus_train_066584 | 5,295 | permissive | [
{
"docstring": "Construct a new sampler object. :param data: Observations for a single random variable. :type data: 1D ndarray :param bins: Number of bins to use when generating the histogram. :type bins: positive int :param resolution: Resolution of each element of the cum-dist array. For example, a resolution... | 2 | stack_v2_sparse_classes_30k_train_036991 | Implement the Python class `HistogramSampler` described below.
Class description:
Random number generator based on a modelled distribution. Given repeated observations of a single random variable, this object first models the probability distribution that governs the variable using a histogram. It then generates new v... | Implement the Python class `HistogramSampler` described below.
Class description:
Random number generator based on a modelled distribution. Given repeated observations of a single random variable, this object first models the probability distribution that governs the variable using a histogram. It then generates new v... | 8b98390850351385acfda5be3088cd4db4cc4a09 | <|skeleton|>
class HistogramSampler:
"""Random number generator based on a modelled distribution. Given repeated observations of a single random variable, this object first models the probability distribution that governs the variable using a histogram. It then generates new variates according to this distribution.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HistogramSampler:
"""Random number generator based on a modelled distribution. Given repeated observations of a single random variable, this object first models the probability distribution that governs the variable using a histogram. It then generates new variates according to this distribution. This sampler... | the_stack_v2_python_sparse | glimpse/util/grandom.py | mthomure/glimpse-project | train | 1 |
2154941b187131f406aecd2088a6cb13670af9e2 | [
"logic = AssociationLogic(self.auth, sid, aid)\nparams = ParamsParser(request.GET)\nlimit = params.int('limit', desc='每页最大渲染数', require=False, default=10)\npage = params.int('page', desc='当前页数', require=False, default=1)\ndepartment = AssociationDepartment.objects.values('id', 'update_time').filter(association__id=... | <|body_start_0|>
logic = AssociationLogic(self.auth, sid, aid)
params = ParamsParser(request.GET)
limit = params.int('limit', desc='每页最大渲染数', require=False, default=10)
page = params.int('page', desc='当前页数', require=False, default=1)
department = AssociationDepartment.objects.val... | DepartmentView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DepartmentView:
def get(self, request, sid, aid):
"""获取协会部门列表 :param request: :param sid: :param aid: :return:"""
<|body_0|>
def post(self, request, sid, aid):
"""批量获取协会部门信息 :param request: :param sid: :param aid: :return:"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_75kplus_train_066585 | 7,635 | no_license | [
{
"docstring": "获取协会部门列表 :param request: :param sid: :param aid: :return:",
"name": "get",
"signature": "def get(self, request, sid, aid)"
},
{
"docstring": "批量获取协会部门信息 :param request: :param sid: :param aid: :return:",
"name": "post",
"signature": "def post(self, request, sid, aid)"
}... | 2 | null | Implement the Python class `DepartmentView` described below.
Class description:
Implement the DepartmentView class.
Method signatures and docstrings:
- def get(self, request, sid, aid): 获取协会部门列表 :param request: :param sid: :param aid: :return:
- def post(self, request, sid, aid): 批量获取协会部门信息 :param request: :param sid... | Implement the Python class `DepartmentView` described below.
Class description:
Implement the DepartmentView class.
Method signatures and docstrings:
- def get(self, request, sid, aid): 获取协会部门列表 :param request: :param sid: :param aid: :return:
- def post(self, request, sid, aid): 批量获取协会部门信息 :param request: :param sid... | a0553be3c259712de1fe5517b06317ad5756f79d | <|skeleton|>
class DepartmentView:
def get(self, request, sid, aid):
"""获取协会部门列表 :param request: :param sid: :param aid: :return:"""
<|body_0|>
def post(self, request, sid, aid):
"""批量获取协会部门信息 :param request: :param sid: :param aid: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DepartmentView:
def get(self, request, sid, aid):
"""获取协会部门列表 :param request: :param sid: :param aid: :return:"""
logic = AssociationLogic(self.auth, sid, aid)
params = ParamsParser(request.GET)
limit = params.int('limit', desc='每页最大渲染数', require=False, default=10)
page... | the_stack_v2_python_sparse | LittlePigHoHo/server/association/views/department/info.py | shoogoome/hoho | train | 1 | |
9a85cf7f4508426a89be7e582ee7619075537bbf | [
"dump_kwargs = dump_kwargs or cls.DEFAULT_DUMP_KWARGS\nwith open(file_path, 'w') as file:\n json.dump(obj, file, **dump_kwargs)",
"with open(file_path, 'r') as file:\n obj = json.load(file)\nreturn obj"
] | <|body_start_0|>
dump_kwargs = dump_kwargs or cls.DEFAULT_DUMP_KWARGS
with open(file_path, 'w') as file:
json.dump(obj, file, **dump_kwargs)
<|end_body_0|>
<|body_start_1|>
with open(file_path, 'r') as file:
obj = json.load(file)
return obj
<|end_body_1|>
| A static class for managing json files. | _JSONFormatter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _JSONFormatter:
"""A static class for managing json files."""
def write(cls, obj: Union[list, dict], file_path: str, **dump_kwargs: dict):
"""Write the object to a json file. The object must be serializable according to the json format. :param obj: The object to write. :param file_pa... | stack_v2_sparse_classes_75kplus_train_066586 | 6,393 | permissive | [
{
"docstring": "Write the object to a json file. The object must be serializable according to the json format. :param obj: The object to write. :param file_path: The file path to write to. :param dump_kwargs: Additional keyword arguments to pass to the `json.dump` method of the formatter in use.",
"name": "... | 2 | null | Implement the Python class `_JSONFormatter` described below.
Class description:
A static class for managing json files.
Method signatures and docstrings:
- def write(cls, obj: Union[list, dict], file_path: str, **dump_kwargs: dict): Write the object to a json file. The object must be serializable according to the jso... | Implement the Python class `_JSONFormatter` described below.
Class description:
A static class for managing json files.
Method signatures and docstrings:
- def write(cls, obj: Union[list, dict], file_path: str, **dump_kwargs: dict): Write the object to a json file. The object must be serializable according to the jso... | b5fe0c05ae7f5818a4a5a5a40245c851ff9b2c77 | <|skeleton|>
class _JSONFormatter:
"""A static class for managing json files."""
def write(cls, obj: Union[list, dict], file_path: str, **dump_kwargs: dict):
"""Write the object to a json file. The object must be serializable according to the json format. :param obj: The object to write. :param file_pa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _JSONFormatter:
"""A static class for managing json files."""
def write(cls, obj: Union[list, dict], file_path: str, **dump_kwargs: dict):
"""Write the object to a json file. The object must be serializable according to the json format. :param obj: The object to write. :param file_path: The file ... | the_stack_v2_python_sparse | mlrun/package/utils/_formatter.py | mlrun/mlrun | train | 1,093 |
500bd1291abc2514a42f87040782b27f7e778456 | [
"if id == 'current':\n id = request.user.id\nreturn api.keystone.user_get(request, id, False).to_dict()",
"if id == 'current':\n raise django.http.HttpResponseNotFound('current')\napi.keystone.user_delete(request, id)",
"keys = tuple(request.DATA)\nuser = api.keystone.user_get(request, id)\nif 'password' ... | <|body_start_0|>
if id == 'current':
id = request.user.id
return api.keystone.user_get(request, id, False).to_dict()
<|end_body_0|>
<|body_start_1|>
if id == 'current':
raise django.http.HttpResponseNotFound('current')
api.keystone.user_delete(request, id)
<|end_... | API for a single keystone user. | User | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class User:
"""API for a single keystone user."""
def get(self, request, id):
"""Get a specific user by id. If the id supplied is 'current' then the current logged-in user will be returned, otherwise the user specified by the id."""
<|body_0|>
def delete(self, request, id):
... | stack_v2_sparse_classes_75kplus_train_066587 | 34,106 | permissive | [
{
"docstring": "Get a specific user by id. If the id supplied is 'current' then the current logged-in user will be returned, otherwise the user specified by the id.",
"name": "get",
"signature": "def get(self, request, id)"
},
{
"docstring": "Delete a single user by id. This method returns HTTP ... | 3 | stack_v2_sparse_classes_30k_val_002164 | Implement the Python class `User` described below.
Class description:
API for a single keystone user.
Method signatures and docstrings:
- def get(self, request, id): Get a specific user by id. If the id supplied is 'current' then the current logged-in user will be returned, otherwise the user specified by the id.
- d... | Implement the Python class `User` described below.
Class description:
API for a single keystone user.
Method signatures and docstrings:
- def get(self, request, id): Get a specific user by id. If the id supplied is 'current' then the current logged-in user will be returned, otherwise the user specified by the id.
- d... | 9524f1952461c83db485d5d1702c350b158d7ce0 | <|skeleton|>
class User:
"""API for a single keystone user."""
def get(self, request, id):
"""Get a specific user by id. If the id supplied is 'current' then the current logged-in user will be returned, otherwise the user specified by the id."""
<|body_0|>
def delete(self, request, id):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class User:
"""API for a single keystone user."""
def get(self, request, id):
"""Get a specific user by id. If the id supplied is 'current' then the current logged-in user will be returned, otherwise the user specified by the id."""
if id == 'current':
id = request.user.id
r... | the_stack_v2_python_sparse | easystack_dashboard/api/rest/keystone.py | oksbsb/horizon-acc | train | 0 |
b945688c780e58e7b82d5ee87e270494f68bbd39 | [
"if decoded_imgs.shape[-1] == 1:\n decoded_imgs_b = 1 - decoded_imgs\n decoded_imgs = np.concatenate((decoded_imgs[:, :, :, None], decoded_imgs_b[:, :, :, None]), axis=3)\nself.decoded_imgs = decoded_imgs\nself.threshold = threshold\nself.verbose = verbose",
"def find_com(image_data):\n \"\"\"Find atoms ... | <|body_start_0|>
if decoded_imgs.shape[-1] == 1:
decoded_imgs_b = 1 - decoded_imgs
decoded_imgs = np.concatenate((decoded_imgs[:, :, :, None], decoded_imgs_b[:, :, :, None]), axis=3)
self.decoded_imgs = decoded_imgs
self.threshold = threshold
self.verbose = verbos... | Transforms pixel data from decoded images into a structure 'file' of atoms coordinates | find_atoms | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class find_atoms:
"""Transforms pixel data from decoded images into a structure 'file' of atoms coordinates"""
def __init__(self, decoded_imgs, threshold=0.5, verbose=1):
"""Args: decoded_imgs: the output of a neural network (softmax/sigmoid layer) threshold: value at which the neural netw... | stack_v2_sparse_classes_75kplus_train_066588 | 8,743 | no_license | [
{
"docstring": "Args: decoded_imgs: the output of a neural network (softmax/sigmoid layer) threshold: value at which the neural network output is thresholded",
"name": "__init__",
"signature": "def __init__(self, decoded_imgs, threshold=0.5, verbose=1)"
},
{
"docstring": "Extract all atomic coor... | 3 | stack_v2_sparse_classes_30k_train_001052 | Implement the Python class `find_atoms` described below.
Class description:
Transforms pixel data from decoded images into a structure 'file' of atoms coordinates
Method signatures and docstrings:
- def __init__(self, decoded_imgs, threshold=0.5, verbose=1): Args: decoded_imgs: the output of a neural network (softmax... | Implement the Python class `find_atoms` described below.
Class description:
Transforms pixel data from decoded images into a structure 'file' of atoms coordinates
Method signatures and docstrings:
- def __init__(self, decoded_imgs, threshold=0.5, verbose=1): Args: decoded_imgs: the output of a neural network (softmax... | d9a27493d8770982e2c933bc1e4b1aa31d682f14 | <|skeleton|>
class find_atoms:
"""Transforms pixel data from decoded images into a structure 'file' of atoms coordinates"""
def __init__(self, decoded_imgs, threshold=0.5, verbose=1):
"""Args: decoded_imgs: the output of a neural network (softmax/sigmoid layer) threshold: value at which the neural netw... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class find_atoms:
"""Transforms pixel data from decoded images into a structure 'file' of atoms coordinates"""
def __init__(self, decoded_imgs, threshold=0.5, verbose=1):
"""Args: decoded_imgs: the output of a neural network (softmax/sigmoid layer) threshold: value at which the neural network output is... | the_stack_v2_python_sparse | AtomNet/atomfind.py | gduscher/AICrystallographer | train | 1 |
d95b10af1d87947d430005c2e09c0d51cb431e7f | [
"month_bounds_error = gettext('Month must be between 1 and 11')\nyear_bounds_error = gettext('You must have known the referee for at least 1 year')\nself.fields = [forms.IntegerField(min_value=0, error_messages={'min_value': year_bounds_error, 'max_value': year_bounds_error, 'invalid': gettext('You must have known ... | <|body_start_0|>
month_bounds_error = gettext('Month must be between 1 and 11')
year_bounds_error = gettext('You must have known the referee for at least 1 year')
self.fields = [forms.IntegerField(min_value=0, error_messages={'min_value': year_bounds_error, 'max_value': year_bounds_error, 'inval... | Class that defines the field type used for both month and years in the TimeKnownWidget | TimeKnownField | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeKnownField:
"""Class that defines the field type used for both month and years in the TimeKnownWidget"""
def __init__(self, *args, **kwargs):
"""The contructor defines each field for the object, the errors it can raise and the resultant error text should an error be returned :par... | stack_v2_sparse_classes_75kplus_train_066589 | 21,840 | no_license | [
{
"docstring": "The contructor defines each field for the object, the errors it can raise and the resultant error text should an error be returned :param args: Standard arguments parameter :param kwargs: Standard key word arguments parameter",
"name": "__init__",
"signature": "def __init__(self, *args, ... | 3 | stack_v2_sparse_classes_30k_val_001553 | Implement the Python class `TimeKnownField` described below.
Class description:
Class that defines the field type used for both month and years in the TimeKnownWidget
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): The contructor defines each field for the object, the errors it can raise and ... | Implement the Python class `TimeKnownField` described below.
Class description:
Class that defines the field type used for both month and years in the TimeKnownWidget
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): The contructor defines each field for the object, the errors it can raise and ... | fa6ca6a8164763e1dfe1581702ca5d36e44859de | <|skeleton|>
class TimeKnownField:
"""Class that defines the field type used for both month and years in the TimeKnownWidget"""
def __init__(self, *args, **kwargs):
"""The contructor defines each field for the object, the errors it can raise and the resultant error text should an error be returned :par... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TimeKnownField:
"""Class that defines the field type used for both month and years in the TimeKnownWidget"""
def __init__(self, *args, **kwargs):
"""The contructor defines each field for the object, the errors it can raise and the resultant error text should an error be returned :param args: Stan... | the_stack_v2_python_sparse | application/customfields.py | IS-JAQU-CAZ/OFS-MORE-Childminder-Website | train | 0 |
c0957ef11d647f69fc1e803968be861f6d109a3b | [
"try:\n connection = mysql.connector.Connect(user=user, password=password, host=host, database=database)\n cursor = connection.cursor(buffered=True)\n return (cursor, connection)\nexcept Exception as e:\n return str(e)",
"try:\n print('execute def called')\n print(query)\n cursor.execute(quer... | <|body_start_0|>
try:
connection = mysql.connector.Connect(user=user, password=password, host=host, database=database)
cursor = connection.cursor(buffered=True)
return (cursor, connection)
except Exception as e:
return str(e)
<|end_body_0|>
<|body_start_1... | Database | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Database:
def connection(self, user='root', password='Armlock21@', host='localhost', database='wpos_dev'):
"""Connection method will create a cursor for executing queries. args user(str): username for connecting to DB password(str): password for connecting to DB host(str): Hot ip to conn... | stack_v2_sparse_classes_75kplus_train_066590 | 2,079 | no_license | [
{
"docstring": "Connection method will create a cursor for executing queries. args user(str): username for connecting to DB password(str): password for connecting to DB host(str): Hot ip to connect with DB database(str): Database to use returns connection(obj): mysql connection object cursor(obj): cursor object... | 3 | stack_v2_sparse_classes_30k_train_044845 | Implement the Python class `Database` described below.
Class description:
Implement the Database class.
Method signatures and docstrings:
- def connection(self, user='root', password='Armlock21@', host='localhost', database='wpos_dev'): Connection method will create a cursor for executing queries. args user(str): use... | Implement the Python class `Database` described below.
Class description:
Implement the Database class.
Method signatures and docstrings:
- def connection(self, user='root', password='Armlock21@', host='localhost', database='wpos_dev'): Connection method will create a cursor for executing queries. args user(str): use... | 396fd8354f29d759c302a04d3c474f46f072cbda | <|skeleton|>
class Database:
def connection(self, user='root', password='Armlock21@', host='localhost', database='wpos_dev'):
"""Connection method will create a cursor for executing queries. args user(str): username for connecting to DB password(str): password for connecting to DB host(str): Hot ip to conn... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Database:
def connection(self, user='root', password='Armlock21@', host='localhost', database='wpos_dev'):
"""Connection method will create a cursor for executing queries. args user(str): username for connecting to DB password(str): password for connecting to DB host(str): Hot ip to connect with DB da... | the_stack_v2_python_sparse | libs/db1.py | westchesterputnamonestop/yourproject | train | 1 | |
f090e4aa50ba6abaebde98419d0bdcb8e1e460e8 | [
"res = []\nif root:\n res.extend(self._inorderTraversal(root.left))\n res.append(root.val)\n res.extend(self._inorderTraversal(root.right))\nreturn res",
"res = []\ncurrent_node = pre_node = root\nwhile current_node:\n if not current_node.left:\n res.append(current_node.val)\n current_no... | <|body_start_0|>
res = []
if root:
res.extend(self._inorderTraversal(root.left))
res.append(root.val)
res.extend(self._inorderTraversal(root.right))
return res
<|end_body_0|>
<|body_start_1|>
res = []
current_node = pre_node = root
whi... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def __inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
def ___inorderTraversal(self, root):
""":type root: T... | stack_v2_sparse_classes_75kplus_train_066591 | 3,683 | permissive | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "_inorderTraversal",
"signature": "def _inorderTraversal(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "__inorderTraversal",
"signature": "def __inorderTraversal(self, root)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_006820 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _inorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def __inorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def ___inorderTraversal(s... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _inorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def __inorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def ___inorderTraversal(s... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def __inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
def ___inorderTraversal(self, root):
""":type root: T... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def _inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
res = []
if root:
res.extend(self._inorderTraversal(root.left))
res.append(root.val)
res.extend(self._inorderTraversal(root.right))
return res
def ... | the_stack_v2_python_sparse | 94.binary-tree-inorder-traversal.py | windard/leeeeee | train | 0 | |
db202112691f12a9213a1b8e97a3c36e7fa8c65c | [
"Parametre.__init__(self, 'apprendre', 'learn')\nself.groupe = 'administrateur'\nself.schema = '<nombre> <cle>'\nself.aide_courte = 'apprend un sort'\nself.aide_longue = \"Cette commande force l'apprentissage d'un sort. Vous devez préciser en premier paramètre le nombre auquel vous voulez apprendre le sort et, en s... | <|body_start_0|>
Parametre.__init__(self, 'apprendre', 'learn')
self.groupe = 'administrateur'
self.schema = '<nombre> <cle>'
self.aide_courte = 'apprend un sort'
self.aide_longue = "Cette commande force l'apprentissage d'un sort. Vous devez préciser en premier paramètre le nombr... | Commande 'sort apprendre'. | PrmApprendre | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmApprendre:
"""Commande 'sort apprendre'."""
def __init__(self):
"""Constructeur de la commande"""
<|body_0|>
def ajouter(self):
"""Méthode appelée lors de l'ajout de la commande à l'interpréteur"""
<|body_1|>
def interpreter(self, personnage, dic_... | stack_v2_sparse_classes_75kplus_train_066592 | 3,737 | permissive | [
{
"docstring": "Constructeur de la commande",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Méthode appelée lors de l'ajout de la commande à l'interpréteur",
"name": "ajouter",
"signature": "def ajouter(self)"
},
{
"docstring": "Méthode d'interprétation... | 3 | stack_v2_sparse_classes_30k_train_030999 | Implement the Python class `PrmApprendre` described below.
Class description:
Commande 'sort apprendre'.
Method signatures and docstrings:
- def __init__(self): Constructeur de la commande
- def ajouter(self): Méthode appelée lors de l'ajout de la commande à l'interpréteur
- def interpreter(self, personnage, dic_masq... | Implement the Python class `PrmApprendre` described below.
Class description:
Commande 'sort apprendre'.
Method signatures and docstrings:
- def __init__(self): Constructeur de la commande
- def ajouter(self): Méthode appelée lors de l'ajout de la commande à l'interpréteur
- def interpreter(self, personnage, dic_masq... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmApprendre:
"""Commande 'sort apprendre'."""
def __init__(self):
"""Constructeur de la commande"""
<|body_0|>
def ajouter(self):
"""Méthode appelée lors de l'ajout de la commande à l'interpréteur"""
<|body_1|>
def interpreter(self, personnage, dic_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PrmApprendre:
"""Commande 'sort apprendre'."""
def __init__(self):
"""Constructeur de la commande"""
Parametre.__init__(self, 'apprendre', 'learn')
self.groupe = 'administrateur'
self.schema = '<nombre> <cle>'
self.aide_courte = 'apprend un sort'
self.aide_... | the_stack_v2_python_sparse | src/secondaires/magie/commandes/sorts/apprendre.py | vincent-lg/tsunami | train | 5 |
779b08f10a723058e61abf3d83301d8763d85038 | [
"if t not in cls.EMBED_MAPPER:\n raise DependencyEmbedderError('Type %s is not mapped! Types mapped: %s' % (t, cls.EMBED_MAPPER.keys()))\nreturn ['.'.join([base_path, e]) for e in cls.EMBED_MAPPER[t]]",
"if not isinstance(additional_embeds, list):\n raise DependencyEmbedderError('Invalid type for additional... | <|body_start_0|>
if t not in cls.EMBED_MAPPER:
raise DependencyEmbedderError('Type %s is not mapped! Types mapped: %s' % (t, cls.EMBED_MAPPER.keys()))
return ['.'.join([base_path, e]) for e in cls.EMBED_MAPPER[t]]
<|end_body_0|>
<|body_start_1|>
if not isinstance(additional_embeds, ... | Utility class intended to be used to produce the embedded list necessary for a default embed of a given type. This class is intended to be used by calling the `embed_defaults_for_type` method. Note that the type mappings are specified in EMBED_MAPPER and that 'compound' embeds are specified verbosely ie: bio_feature em... | DependencyEmbedder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DependencyEmbedder:
"""Utility class intended to be used to produce the embedded list necessary for a default embed of a given type. This class is intended to be used by calling the `embed_defaults_for_type` method. Note that the type mappings are specified in EMBED_MAPPER and that 'compound' emb... | stack_v2_sparse_classes_75kplus_train_066593 | 2,667 | permissive | [
{
"docstring": "Embeds the fields necessary for a default embed of the given type and base_path :param base_path: path to linkTo :param t: item type this embed is for :return: list of embeds",
"name": "embed_defaults_for_type",
"signature": "def embed_defaults_for_type(cls, *, base_path, t)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_001788 | Implement the Python class `DependencyEmbedder` described below.
Class description:
Utility class intended to be used to produce the embedded list necessary for a default embed of a given type. This class is intended to be used by calling the `embed_defaults_for_type` method. Note that the type mappings are specified ... | Implement the Python class `DependencyEmbedder` described below.
Class description:
Utility class intended to be used to produce the embedded list necessary for a default embed of a given type. This class is intended to be used by calling the `embed_defaults_for_type` method. Note that the type mappings are specified ... | 10d3f81776963b416488c8121c7e0db8b66727bf | <|skeleton|>
class DependencyEmbedder:
"""Utility class intended to be used to produce the embedded list necessary for a default embed of a given type. This class is intended to be used by calling the `embed_defaults_for_type` method. Note that the type mappings are specified in EMBED_MAPPER and that 'compound' emb... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DependencyEmbedder:
"""Utility class intended to be used to produce the embedded list necessary for a default embed of a given type. This class is intended to be used by calling the `embed_defaults_for_type` method. Note that the type mappings are specified in EMBED_MAPPER and that 'compound' embeds are speci... | the_stack_v2_python_sparse | src/encoded/types/dependencies.py | dbmi-bgm/cgap-portal | train | 7 |
95f11a1193538ab704fe93befa22ae48d8e67322 | [
"result = []\nfor num in nums2:\n if num in nums1:\n result.append(num)\nreturn result",
"if len(nums1) == 0 or len(nums2) == 0:\n return []\nnums1 = set(nums1)\nnums2 = set(nums2)\nif len(nums1) >= len(nums2):\n return self.final(nums1, nums2)\nelse:\n return self.final(nums2, nums1)"
] | <|body_start_0|>
result = []
for num in nums2:
if num in nums1:
result.append(num)
return result
<|end_body_0|>
<|body_start_1|>
if len(nums1) == 0 or len(nums2) == 0:
return []
nums1 = set(nums1)
nums2 = set(nums2)
if len(... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def final(self, nums1, nums2):
"""nums1 is longer, nums2 is shorter"""
<|body_0|>
def intersection(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
resu... | stack_v2_sparse_classes_75kplus_train_066594 | 1,327 | permissive | [
{
"docstring": "nums1 is longer, nums2 is shorter",
"name": "final",
"signature": "def final(self, nums1, nums2)"
},
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: List[int]",
"name": "intersection",
"signature": "def intersection(self, nums1, nums2)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def final(self, nums1, nums2): nums1 is longer, nums2 is shorter
- def intersection(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def final(self, nums1, nums2): nums1 is longer, nums2 is shorter
- def intersection(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int]
<|skelet... | 45178e7d40fde8bd042df48bbf0f2f1e534a4d52 | <|skeleton|>
class Solution:
def final(self, nums1, nums2):
"""nums1 is longer, nums2 is shorter"""
<|body_0|>
def intersection(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def final(self, nums1, nums2):
"""nums1 is longer, nums2 is shorter"""
result = []
for num in nums2:
if num in nums1:
result.append(num)
return result
def intersection(self, nums1, nums2):
""":type nums1: List[int] :type nums2:... | the_stack_v2_python_sparse | Code/349.两个数组的交集.py | Yuranus/Leetcode-Chinese-Version | train | 0 | |
be9c84ce8c5d55f7b08a5e5d1ddbf2b7373fe49b | [
"FetcherApp.__init__(self, classify, critical_max_repeat=10, critical_sleep_time=60)\ncookie_string = 'PHPSESSID=btqkg9amjrtoeev8coq0m78396; USERINFO=n6nxTHTY%2BJA39z6CpNB4eKN8f0KsYLjAQTwPe%2BhLHLruEbjaeh4ulhWAS5RysUM%2B; Hm_lvt_0bcb16196dddadaf61c121323a9ec0b6=1472528976; Hm_lpvt_0bcb16196dddadaf61c121323a9ec0b6=1... | <|body_start_0|>
FetcherApp.__init__(self, classify, critical_max_repeat=10, critical_sleep_time=60)
cookie_string = 'PHPSESSID=btqkg9amjrtoeev8coq0m78396; USERINFO=n6nxTHTY%2BJA39z6CpNB4eKN8f0KsYLjAQTwPe%2BhLHLruEbjaeh4ulhWAS5RysUM%2B; Hm_lvt_0bcb16196dddadaf61c121323a9ec0b6=1472528976; Hm_lpvt_0bcb161... | class of FetcherASO | FetcherASO | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FetcherASO:
"""class of FetcherASO"""
def __init__(self, classify):
"""constructor"""
<|body_0|>
def url_fetch(self, url, keys, critical, repeat):
"""fetch the content of a url"""
<|body_1|>
def htm_parse(self, url, keys, cur_html):
"""parse ... | stack_v2_sparse_classes_75kplus_train_066595 | 17,241 | no_license | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self, classify)"
},
{
"docstring": "fetch the content of a url",
"name": "url_fetch",
"signature": "def url_fetch(self, url, keys, critical, repeat)"
},
{
"docstring": "parse the content of a url :return... | 3 | stack_v2_sparse_classes_30k_train_045104 | Implement the Python class `FetcherASO` described below.
Class description:
class of FetcherASO
Method signatures and docstrings:
- def __init__(self, classify): constructor
- def url_fetch(self, url, keys, critical, repeat): fetch the content of a url
- def htm_parse(self, url, keys, cur_html): parse the content of ... | Implement the Python class `FetcherASO` described below.
Class description:
class of FetcherASO
Method signatures and docstrings:
- def __init__(self, classify): constructor
- def url_fetch(self, url, keys, critical, repeat): fetch the content of a url
- def htm_parse(self, url, keys, cur_html): parse the content of ... | 8d40508a568fcdeb091c51c95050bb936621613f | <|skeleton|>
class FetcherASO:
"""class of FetcherASO"""
def __init__(self, classify):
"""constructor"""
<|body_0|>
def url_fetch(self, url, keys, critical, repeat):
"""fetch the content of a url"""
<|body_1|>
def htm_parse(self, url, keys, cur_html):
"""parse ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FetcherASO:
"""class of FetcherASO"""
def __init__(self, classify):
"""constructor"""
FetcherApp.__init__(self, classify, critical_max_repeat=10, critical_sleep_time=60)
cookie_string = 'PHPSESSID=btqkg9amjrtoeev8coq0m78396; USERINFO=n6nxTHTY%2BJA39z6CpNB4eKN8f0KsYLjAQTwPe%2BhLHLr... | the_stack_v2_python_sparse | demos_apps/app_fetcher.py | Java-via/AppSpider | train | 0 |
e688e235226bef00ac82b0e5806b081bbf580c3e | [
"index1 = self._select_index(population=population)\nindex2 = index1\nwhile index2 == index1:\n index2 = self._select_index(population=population)\nreturn (population.get(index1), population.get(index2))",
"total_fitness = 0\nfor solution in population.solutions:\n total_fitness += solution.fitness\nwheel_p... | <|body_start_0|>
index1 = self._select_index(population=population)
index2 = index1
while index2 == index1:
index2 = self._select_index(population=population)
return (population.get(index1), population.get(index2))
<|end_body_0|>
<|body_start_1|>
total_fitness = 0
... | Main idea: better individuals get higher chance The chances are proportional to the fitness Implementation: roulette wheel technique Assign to each individual a part of the roulette wheel Spin the wheel n times to select n individuals REMARK: This implementation does not consider minimization problem | RouletteWheelSelection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RouletteWheelSelection:
"""Main idea: better individuals get higher chance The chances are proportional to the fitness Implementation: roulette wheel technique Assign to each individual a part of the roulette wheel Spin the wheel n times to select n individuals REMARK: This implementation does no... | stack_v2_sparse_classes_75kplus_train_066596 | 10,268 | no_license | [
{
"docstring": "select two different parents using roulette wheel",
"name": "select",
"signature": "def select(self, population, objective, params)"
},
{
"docstring": "This is the roullete wheel itself",
"name": "_select_index",
"signature": "def _select_index(self, population)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020387 | Implement the Python class `RouletteWheelSelection` described below.
Class description:
Main idea: better individuals get higher chance The chances are proportional to the fitness Implementation: roulette wheel technique Assign to each individual a part of the roulette wheel Spin the wheel n times to select n individu... | Implement the Python class `RouletteWheelSelection` described below.
Class description:
Main idea: better individuals get higher chance The chances are proportional to the fitness Implementation: roulette wheel technique Assign to each individual a part of the roulette wheel Spin the wheel n times to select n individu... | 4dd77d5d72186f446fead55371c9941c4020f431 | <|skeleton|>
class RouletteWheelSelection:
"""Main idea: better individuals get higher chance The chances are proportional to the fitness Implementation: roulette wheel technique Assign to each individual a part of the roulette wheel Spin the wheel n times to select n individuals REMARK: This implementation does no... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RouletteWheelSelection:
"""Main idea: better individuals get higher chance The chances are proportional to the fitness Implementation: roulette wheel technique Assign to each individual a part of the roulette wheel Spin the wheel n times to select n individuals REMARK: This implementation does not consider mi... | the_stack_v2_python_sparse | Customer Segmentation for Insurance Dataset/Extra Code/GA for ML/algorithm/ga_operators.py | apanchot/Projects | train | 1 |
7e09de1c5dc520c79c269c897db4b3fe602bd1f3 | [
"assert isinstance(response, scrapy.http.response.html.HtmlResponse)\nurls = [response.url]\nposts_per_page = 50\nlast_page = response.selector.xpath('//a[contains(@title, \"Click to jump to page\")]/strong[2]/text()').extract_first()\nif last_page:\n last_page = read_number(last_page)\nelse:\n last_page = 0\... | <|body_start_0|>
assert isinstance(response, scrapy.http.response.html.HtmlResponse)
urls = [response.url]
posts_per_page = 50
last_page = response.selector.xpath('//a[contains(@title, "Click to jump to page")]/strong[2]/text()').extract_first()
if last_page:
last_pag... | scrape images from angling addicts forum | SeaAnglingIrelandArchives | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SeaAnglingIrelandArchives:
"""scrape images from angling addicts forum"""
def parse(self, response):
"""get links to report boards yields: http://www.sea-angling-ireland.org/forum/viewforum.php?f=62 http://www.sea-angling-ireland.org/forum/viewforum.php?f=62&start=50"""
<|bod... | stack_v2_sparse_classes_75kplus_train_066597 | 5,577 | no_license | [
{
"docstring": "get links to report boards yields: http://www.sea-angling-ireland.org/forum/viewforum.php?f=62 http://www.sea-angling-ireland.org/forum/viewforum.php?f=62&start=50",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "get links to all reports from boards ... | 3 | stack_v2_sparse_classes_30k_train_016531 | Implement the Python class `SeaAnglingIrelandArchives` described below.
Class description:
scrape images from angling addicts forum
Method signatures and docstrings:
- def parse(self, response): get links to report boards yields: http://www.sea-angling-ireland.org/forum/viewforum.php?f=62 http://www.sea-angling-irela... | Implement the Python class `SeaAnglingIrelandArchives` described below.
Class description:
scrape images from angling addicts forum
Method signatures and docstrings:
- def parse(self, response): get links to report boards yields: http://www.sea-angling-ireland.org/forum/viewforum.php?f=62 http://www.sea-angling-irela... | 9123aa6baf538b662143b9098d963d55165e8409 | <|skeleton|>
class SeaAnglingIrelandArchives:
"""scrape images from angling addicts forum"""
def parse(self, response):
"""get links to report boards yields: http://www.sea-angling-ireland.org/forum/viewforum.php?f=62 http://www.sea-angling-ireland.org/forum/viewforum.php?f=62&start=50"""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SeaAnglingIrelandArchives:
"""scrape images from angling addicts forum"""
def parse(self, response):
"""get links to report boards yields: http://www.sea-angling-ireland.org/forum/viewforum.php?f=62 http://www.sea-angling-ireland.org/forum/viewforum.php?f=62&start=50"""
assert isinstance(... | the_stack_v2_python_sparse | imgscrape/spiders/seaanglingireland.py | gmonkman/python | train | 0 |
ba300d671ffddfa7e7187bb0d641f2dcc803c52a | [
"self.ans = None\n\ndef help(head, k):\n if not head:\n return 0\n n = help(head.next, k) + 1\n if n == k:\n self.ans = head\n return n\nhelp(head, k)\nreturn self.ans",
"if not head:\n return None\nlength = 0\ncur = head\nwhile cur:\n length += 1\n cur = cur.next\nans = head\nw... | <|body_start_0|>
self.ans = None
def help(head, k):
if not head:
return 0
n = help(head.next, k) + 1
if n == k:
self.ans = head
return n
help(head, k)
return self.ans
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getKthFromEnd(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_0|>
def getKthFromEnd0(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_066598 | 1,619 | no_license | [
{
"docstring": ":type head: ListNode :type k: int :rtype: ListNode",
"name": "getKthFromEnd",
"signature": "def getKthFromEnd(self, head, k)"
},
{
"docstring": ":type head: ListNode :type k: int :rtype: ListNode",
"name": "getKthFromEnd0",
"signature": "def getKthFromEnd0(self, head, k)"... | 2 | stack_v2_sparse_classes_30k_train_002772 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getKthFromEnd(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
- def getKthFromEnd0(self, head, k): :type head: ListNode :type k: int :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getKthFromEnd(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
- def getKthFromEnd0(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
<|sk... | 6e18c5d257840489cc3fb1079ae3804c743982a4 | <|skeleton|>
class Solution:
def getKthFromEnd(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_0|>
def getKthFromEnd0(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def getKthFromEnd(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
self.ans = None
def help(head, k):
if not head:
return 0
n = help(head.next, k) + 1
if n == k:
self.ans = head
... | the_stack_v2_python_sparse | 剑指 Offer 22. 链表中倒数第k个节点.py | yangyuxiang1996/leetcode | train | 0 | |
a486de4c6a0bdcc3ccff86aeb351b3d774ae0b4d | [
"self._parse_eval_args(*args, _noOrbUnitsCheck=True, **kwargs)\nself._z = self._eval_z\nself._vz = self._eval_vz\nif not 'pot' in kwargs:\n raise IOError('Must specify pot= for actionAngleVertical')\nself._verticalpot = kwargs['pot']\nreturn None",
"if hasattr(self, '_Jz'):\n return self._Jz\nzmax = self.ca... | <|body_start_0|>
self._parse_eval_args(*args, _noOrbUnitsCheck=True, **kwargs)
self._z = self._eval_z
self._vz = self._eval_vz
if not 'pot' in kwargs:
raise IOError('Must specify pot= for actionAngleVertical')
self._verticalpot = kwargs['pot']
return None
<|en... | Action-angle formalism for vertical integral using the adiabatic approximation | actionAngleVertical | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class actionAngleVertical:
"""Action-angle formalism for vertical integral using the adiabatic approximation"""
def __init__(self, *args, **kwargs):
"""NAME: __init__ PURPOSE: initialize an actionAngleVertical object INPUT: Either: a) z,vz b) Orbit instance: initial condition used if that'... | stack_v2_sparse_classes_75kplus_train_066599 | 6,559 | permissive | [
{
"docstring": "NAME: __init__ PURPOSE: initialize an actionAngleVertical object INPUT: Either: a) z,vz b) Orbit instance: initial condition used if that's it, orbit(t) if there is a time given as well pot= potential or list of potentials (planarPotentials) OUTPUT: HISTORY: 2012-06-01 - Written - Bovy (IAS)",
... | 5 | stack_v2_sparse_classes_30k_train_014139 | Implement the Python class `actionAngleVertical` described below.
Class description:
Action-angle formalism for vertical integral using the adiabatic approximation
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): NAME: __init__ PURPOSE: initialize an actionAngleVertical object INPUT: Either: a... | Implement the Python class `actionAngleVertical` described below.
Class description:
Action-angle formalism for vertical integral using the adiabatic approximation
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): NAME: __init__ PURPOSE: initialize an actionAngleVertical object INPUT: Either: a... | 58c4ac9622b475439463264d0ae658246b914cdc | <|skeleton|>
class actionAngleVertical:
"""Action-angle formalism for vertical integral using the adiabatic approximation"""
def __init__(self, *args, **kwargs):
"""NAME: __init__ PURPOSE: initialize an actionAngleVertical object INPUT: Either: a) z,vz b) Orbit instance: initial condition used if that'... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class actionAngleVertical:
"""Action-angle formalism for vertical integral using the adiabatic approximation"""
def __init__(self, *args, **kwargs):
"""NAME: __init__ PURPOSE: initialize an actionAngleVertical object INPUT: Either: a) z,vz b) Orbit instance: initial condition used if that's it, orbit(t... | the_stack_v2_python_sparse | galpy/actionAngle_src/actionAngleVertical.py | wilmatrick/galpy | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.