blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
05bba5aa4ea1cbe2a52f4232e42693ebf5acd2e2 | [
"self.tasks = tasks\nlog.debug(f'HPCWorker ready with {len(self.tasks)}')\nself.job_num = num\nself.job_id = job_id\nself.job_status = 'unknown'\nself.moddir = Path(tasks[0].envvars['MODDIR'])\nself.toppar = tasks[0].envvars['TOPPAR']\nself.cns_folder = tasks[0].envvars['MODULE']\nmodule_name = Path(tasks[0].envvar... | <|body_start_0|>
self.tasks = tasks
log.debug(f'HPCWorker ready with {len(self.tasks)}')
self.job_num = num
self.job_id = job_id
self.job_status = 'unknown'
self.moddir = Path(tasks[0].envvars['MODDIR'])
self.toppar = tasks[0].envvars['TOPPAR']
self.cns_fo... | Defines the HPC Job. | HPCWorker | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HPCWorker:
"""Defines the HPC Job."""
def __init__(self, tasks, num, job_id=None, workfload_manager='slurm', queue=None):
"""Define the HPC job. Parameters ---------- tasks : list of libs.libcns.CNSJob objects num : int The number of the worker."""
<|body_0|>
def prepare... | stack_v2_sparse_classes_36k_train_033200 | 11,076 | permissive | [
{
"docstring": "Define the HPC job. Parameters ---------- tasks : list of libs.libcns.CNSJob objects num : int The number of the worker.",
"name": "__init__",
"signature": "def __init__(self, tasks, num, job_id=None, workfload_manager='slurm', queue=None)"
},
{
"docstring": "Prepare the job file... | 5 | stack_v2_sparse_classes_30k_train_015655 | Implement the Python class `HPCWorker` described below.
Class description:
Defines the HPC Job.
Method signatures and docstrings:
- def __init__(self, tasks, num, job_id=None, workfload_manager='slurm', queue=None): Define the HPC job. Parameters ---------- tasks : list of libs.libcns.CNSJob objects num : int The num... | Implement the Python class `HPCWorker` described below.
Class description:
Defines the HPC Job.
Method signatures and docstrings:
- def __init__(self, tasks, num, job_id=None, workfload_manager='slurm', queue=None): Define the HPC job. Parameters ---------- tasks : list of libs.libcns.CNSJob objects num : int The num... | e770b786cdfee8011ff4cc8c00520946b25a35e3 | <|skeleton|>
class HPCWorker:
"""Defines the HPC Job."""
def __init__(self, tasks, num, job_id=None, workfload_manager='slurm', queue=None):
"""Define the HPC job. Parameters ---------- tasks : list of libs.libcns.CNSJob objects num : int The number of the worker."""
<|body_0|>
def prepare... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HPCWorker:
"""Defines the HPC Job."""
def __init__(self, tasks, num, job_id=None, workfload_manager='slurm', queue=None):
"""Define the HPC job. Parameters ---------- tasks : list of libs.libcns.CNSJob objects num : int The number of the worker."""
self.tasks = tasks
log.debug(f'H... | the_stack_v2_python_sparse | src/haddock/libs/libhpc.py | haddocking/haddock3 | train | 59 |
eec88c8120371ad4b00b2b31c8afc56dba6a0dd8 | [
"import boto3\nif session:\n self._session = session\nelse:\n self._session = boto3.Session(aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, aws_session_token=aws_session_token, region_name=region_name, profile_name=profile_name)\nself.requester_pays = requester_pays\nself.uns... | <|body_start_0|>
import boto3
if session:
self._session = session
else:
self._session = boto3.Session(aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, aws_session_token=aws_session_token, region_name=region_name, profile_name=profile_name)... | Configures access to secured resources stored in AWS S3. | AWSSession | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AWSSession:
"""Configures access to secured resources stored in AWS S3."""
def __init__(self, session=None, aws_unsigned=False, aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None, region_name=None, profile_name=None, requester_pays=False):
"""Create a new boto... | stack_v2_sparse_classes_36k_train_033201 | 6,487 | permissive | [
{
"docstring": "Create a new boto3 session Parameters ---------- session : optional A boto3 session object. aws_unsigned : bool, optional (default: False) If True, requests will be unsigned. aws_access_key_id : str, optional An access key id, as per boto3. aws_secret_access_key : str, optional A secret access k... | 3 | stack_v2_sparse_classes_30k_train_000694 | Implement the Python class `AWSSession` described below.
Class description:
Configures access to secured resources stored in AWS S3.
Method signatures and docstrings:
- def __init__(self, session=None, aws_unsigned=False, aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None, region_name=None, pr... | Implement the Python class `AWSSession` described below.
Class description:
Configures access to secured resources stored in AWS S3.
Method signatures and docstrings:
- def __init__(self, session=None, aws_unsigned=False, aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None, region_name=None, pr... | aace2ce55694087550951c5372c57aa7c67c6d3a | <|skeleton|>
class AWSSession:
"""Configures access to secured resources stored in AWS S3."""
def __init__(self, session=None, aws_unsigned=False, aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None, region_name=None, profile_name=None, requester_pays=False):
"""Create a new boto... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AWSSession:
"""Configures access to secured resources stored in AWS S3."""
def __init__(self, session=None, aws_unsigned=False, aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None, region_name=None, profile_name=None, requester_pays=False):
"""Create a new boto3 session Par... | the_stack_v2_python_sparse | venv/lib/python3.9/site-packages/fiona/session.py | PariyaPm/foresite | train | 1 |
c0d3195495447ad9fd8fb9a2cb2f7de3a41e0d98 | [
"number = lfs.voucher.utils.create_voucher_number()\nself.failUnless(len(number) == 5)\nletters = 'ABCDEFGHIJKLMNOPQRSTUVXYZ'\nfor letter in number:\n self.failIf(letter not in letters)",
"VoucherOptions.objects.create(number_prefix='DH', number_suffix='XM', number_length=4, number_letters='abcdefghijklmnopqrs... | <|body_start_0|>
number = lfs.voucher.utils.create_voucher_number()
self.failUnless(len(number) == 5)
letters = 'ABCDEFGHIJKLMNOPQRSTUVXYZ'
for letter in number:
self.failIf(letter not in letters)
<|end_body_0|>
<|body_start_1|>
VoucherOptions.objects.create(number_p... | VoucherUtilsTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VoucherUtilsTestCase:
def test_create_vouchers_1(self):
"""Tests the default voucher options"""
<|body_0|>
def test_create_vouchers_2(self):
"""Tests the custom options."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
number = lfs.voucher.utils.crea... | stack_v2_sparse_classes_36k_train_033202 | 8,563 | no_license | [
{
"docstring": "Tests the default voucher options",
"name": "test_create_vouchers_1",
"signature": "def test_create_vouchers_1(self)"
},
{
"docstring": "Tests the custom options.",
"name": "test_create_vouchers_2",
"signature": "def test_create_vouchers_2(self)"
}
] | 2 | null | Implement the Python class `VoucherUtilsTestCase` described below.
Class description:
Implement the VoucherUtilsTestCase class.
Method signatures and docstrings:
- def test_create_vouchers_1(self): Tests the default voucher options
- def test_create_vouchers_2(self): Tests the custom options. | Implement the Python class `VoucherUtilsTestCase` described below.
Class description:
Implement the VoucherUtilsTestCase class.
Method signatures and docstrings:
- def test_create_vouchers_1(self): Tests the default voucher options
- def test_create_vouchers_2(self): Tests the custom options.
<|skeleton|>
class Vouc... | 77e9c70687b35fd8b65a7f2d879e0261ae69c00e | <|skeleton|>
class VoucherUtilsTestCase:
def test_create_vouchers_1(self):
"""Tests the default voucher options"""
<|body_0|>
def test_create_vouchers_2(self):
"""Tests the custom options."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VoucherUtilsTestCase:
def test_create_vouchers_1(self):
"""Tests the default voucher options"""
number = lfs.voucher.utils.create_voucher_number()
self.failUnless(len(number) == 5)
letters = 'ABCDEFGHIJKLMNOPQRSTUVXYZ'
for letter in number:
self.failIf(lette... | the_stack_v2_python_sparse | eggs/django_lfs-0.10.2-py2.7.egg/lfs/voucher/tests.py | yunmengyanjin/website | train | 2 | |
85d99c349eaed6abb904cab48233eb3b76b78124 | [
"if not fields:\n fields = ('id',)\ndb_sess = db_session.create_session()\narticle = db_sess.query(Article).get(article_id)\nif not article:\n raise ArticleNotFoundError\nreturn article.to_dict(only=fields)",
"if not fields:\n fields = ('id',)\ndb_sess = db_session.create_session()\narticles = db_sess.qu... | <|body_start_0|>
if not fields:
fields = ('id',)
db_sess = db_session.create_session()
article = db_sess.query(Article).get(article_id)
if not article:
raise ArticleNotFoundError
return article.to_dict(only=fields)
<|end_body_0|>
<|body_start_1|>
... | Класс для работы с моделью Article | ArticleModelWorker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArticleModelWorker:
"""Класс для работы с моделью Article"""
def get_article(article_id, fields=('id', 'title')):
"""Статья в JSON формате. Применяется в основном в API"""
<|body_0|>
def get_all_articles(fields=('id', 'title'), author=None, sorted_by='create_date', limit... | stack_v2_sparse_classes_36k_train_033203 | 5,022 | no_license | [
{
"docstring": "Статья в JSON формате. Применяется в основном в API",
"name": "get_article",
"signature": "def get_article(article_id, fields=('id', 'title'))"
},
{
"docstring": "Список статей в JSON формате. Применяется в основном в API",
"name": "get_all_articles",
"signature": "def ge... | 6 | stack_v2_sparse_classes_30k_test_000952 | Implement the Python class `ArticleModelWorker` described below.
Class description:
Класс для работы с моделью Article
Method signatures and docstrings:
- def get_article(article_id, fields=('id', 'title')): Статья в JSON формате. Применяется в основном в API
- def get_all_articles(fields=('id', 'title'), author=None... | Implement the Python class `ArticleModelWorker` described below.
Class description:
Класс для работы с моделью Article
Method signatures and docstrings:
- def get_article(article_id, fields=('id', 'title')): Статья в JSON формате. Применяется в основном в API
- def get_all_articles(fields=('id', 'title'), author=None... | 1bc59640f13ae4fe6582bb10c9093ff3d671aeb1 | <|skeleton|>
class ArticleModelWorker:
"""Класс для работы с моделью Article"""
def get_article(article_id, fields=('id', 'title')):
"""Статья в JSON формате. Применяется в основном в API"""
<|body_0|>
def get_all_articles(fields=('id', 'title'), author=None, sorted_by='create_date', limit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArticleModelWorker:
"""Класс для работы с моделью Article"""
def get_article(article_id, fields=('id', 'title')):
"""Статья в JSON формате. Применяется в основном в API"""
if not fields:
fields = ('id',)
db_sess = db_session.create_session()
article = db_sess.q... | the_stack_v2_python_sparse | model_workers/article.py | KosenokIvan/articles_website | train | 1 |
9682346c68a85916086928d54dcaeefedb7c6e33 | [
"vip = 0\nif appId and int(appId) == 9999:\n gameDataKey = 'gamedata:9999:%s' % userId\n vip_exp = TyContext.RedisUser.execute(userId, 'HGET', gameDataKey, 'vip.exp')\n if vip_exp:\n for i, exp in enumerate(cls.VIP_EXP_LEVEL):\n if int(vip_exp) < exp:\n break\n v... | <|body_start_0|>
vip = 0
if appId and int(appId) == 9999:
gameDataKey = 'gamedata:9999:%s' % userId
vip_exp = TyContext.RedisUser.execute(userId, 'HGET', gameDataKey, 'vip.exp')
if vip_exp:
for i, exp in enumerate(cls.VIP_EXP_LEVEL):
... | AccountGameData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountGameData:
def get_user_vip(cls, appId, userId):
"""获取用户vip等级 :param userId: :return:"""
<|body_0|>
def get_user_total_time(self, appId, userId):
"""获取用户累计在线时长 :param userId: :return:"""
<|body_1|>
def get_user_today_time(self, appId, userId):
... | stack_v2_sparse_classes_36k_train_033204 | 4,335 | no_license | [
{
"docstring": "获取用户vip等级 :param userId: :return:",
"name": "get_user_vip",
"signature": "def get_user_vip(cls, appId, userId)"
},
{
"docstring": "获取用户累计在线时长 :param userId: :return:",
"name": "get_user_total_time",
"signature": "def get_user_total_time(self, appId, userId)"
},
{
... | 5 | null | Implement the Python class `AccountGameData` described below.
Class description:
Implement the AccountGameData class.
Method signatures and docstrings:
- def get_user_vip(cls, appId, userId): 获取用户vip等级 :param userId: :return:
- def get_user_total_time(self, appId, userId): 获取用户累计在线时长 :param userId: :return:
- def get... | Implement the Python class `AccountGameData` described below.
Class description:
Implement the AccountGameData class.
Method signatures and docstrings:
- def get_user_vip(cls, appId, userId): 获取用户vip等级 :param userId: :return:
- def get_user_total_time(self, appId, userId): 获取用户累计在线时长 :param userId: :return:
- def get... | 21ea94c5b048bc611fb1557ac0b6e3ef4fdbbc09 | <|skeleton|>
class AccountGameData:
def get_user_vip(cls, appId, userId):
"""获取用户vip等级 :param userId: :return:"""
<|body_0|>
def get_user_total_time(self, appId, userId):
"""获取用户累计在线时长 :param userId: :return:"""
<|body_1|>
def get_user_today_time(self, appId, userId):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccountGameData:
def get_user_vip(cls, appId, userId):
"""获取用户vip等级 :param userId: :return:"""
vip = 0
if appId and int(appId) == 9999:
gameDataKey = 'gamedata:9999:%s' % userId
vip_exp = TyContext.RedisUser.execute(userId, 'HGET', gameDataKey, 'vip.exp')
... | the_stack_v2_python_sparse | source/tygame-sdk/src/tysdk/entity/user3/account_game_data.py | hi-noikiy/hall0 | train | 0 | |
53240d84ef2b9d134e41d91d2ed18bc1f2ed5cef | [
"def foo(n):\n if not n:\n yield None\n return\n yield n.val\n yield from foo(n.left)\n yield from foo(n.right)\n\ndef bar(n):\n if not n:\n yield None\n return\n yield n.val\n yield from bar(n.right)\n yield from bar(n.left)\nif not root:\n return True\nn1, n2... | <|body_start_0|>
def foo(n):
if not n:
yield None
return
yield n.val
yield from foo(n.left)
yield from foo(n.right)
def bar(n):
if not n:
yield None
return
yield n.val... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSymmetric_first(self, root: TreeNode) -> bool:
"""first attempt"""
<|body_0|>
def isSymmetric(self, root: TreeNode) -> bool:
"""optimization"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def foo(n):
if not n:
... | stack_v2_sparse_classes_36k_train_033205 | 1,679 | no_license | [
{
"docstring": "first attempt",
"name": "isSymmetric_first",
"signature": "def isSymmetric_first(self, root: TreeNode) -> bool"
},
{
"docstring": "optimization",
"name": "isSymmetric",
"signature": "def isSymmetric(self, root: TreeNode) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_train_005934 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSymmetric_first(self, root: TreeNode) -> bool: first attempt
- def isSymmetric(self, root: TreeNode) -> bool: optimization | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSymmetric_first(self, root: TreeNode) -> bool: first attempt
- def isSymmetric(self, root: TreeNode) -> bool: optimization
<|skeleton|>
class Solution:
def isSymmetri... | d4d44e6dfd3df4cb47b855ad30e6849038cea0a5 | <|skeleton|>
class Solution:
def isSymmetric_first(self, root: TreeNode) -> bool:
"""first attempt"""
<|body_0|>
def isSymmetric(self, root: TreeNode) -> bool:
"""optimization"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isSymmetric_first(self, root: TreeNode) -> bool:
"""first attempt"""
def foo(n):
if not n:
yield None
return
yield n.val
yield from foo(n.left)
yield from foo(n.right)
def bar(n):
... | the_stack_v2_python_sparse | leetcode/amazon/trees_and_graphs/symmetric_tree.py | alvaronaschez/amazon | train | 0 | |
444e3caa509117de0416db2e7eddae8940caac82 | [
"super().__init__(target)\nif wrap:\n if wrap < 1:\n raise ValueError\nself.wrap = wrap\nself.record2title = record2title",
"if self.record2title:\n title = self.clean(self.record2title(record))\nelse:\n id = self.clean(record.id)\n description = self.clean(record.description)\n if descripti... | <|body_start_0|>
super().__init__(target)
if wrap:
if wrap < 1:
raise ValueError
self.wrap = wrap
self.record2title = record2title
<|end_body_0|>
<|body_start_1|>
if self.record2title:
title = self.clean(self.record2title(record))
... | Class to write Fasta format files (OBSOLETE). Please use the ``as_fasta`` function instead, or the top level ``Bio.SeqIO.write()`` function instead using ``format="fasta"``. | FastaWriter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FastaWriter:
"""Class to write Fasta format files (OBSOLETE). Please use the ``as_fasta`` function instead, or the top level ``Bio.SeqIO.write()`` function instead using ``format="fasta"``."""
def __init__(self, target, wrap=60, record2title=None):
"""Create a Fasta writer (OBSOLETE)... | stack_v2_sparse_classes_36k_train_033206 | 14,957 | permissive | [
{
"docstring": "Create a Fasta writer (OBSOLETE). Arguments: - target - Output stream opened in text mode, or a path to a file. - wrap - Optional line length used to wrap sequence lines. Defaults to wrapping the sequence at 60 characters Use zero (or None) for no wrapping, giving a single long line for the sequ... | 2 | null | Implement the Python class `FastaWriter` described below.
Class description:
Class to write Fasta format files (OBSOLETE). Please use the ``as_fasta`` function instead, or the top level ``Bio.SeqIO.write()`` function instead using ``format="fasta"``.
Method signatures and docstrings:
- def __init__(self, target, wrap... | Implement the Python class `FastaWriter` described below.
Class description:
Class to write Fasta format files (OBSOLETE). Please use the ``as_fasta`` function instead, or the top level ``Bio.SeqIO.write()`` function instead using ``format="fasta"``.
Method signatures and docstrings:
- def __init__(self, target, wrap... | 595c5c46794ae08a1f19716636eac7430cededa1 | <|skeleton|>
class FastaWriter:
"""Class to write Fasta format files (OBSOLETE). Please use the ``as_fasta`` function instead, or the top level ``Bio.SeqIO.write()`` function instead using ``format="fasta"``."""
def __init__(self, target, wrap=60, record2title=None):
"""Create a Fasta writer (OBSOLETE)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FastaWriter:
"""Class to write Fasta format files (OBSOLETE). Please use the ``as_fasta`` function instead, or the top level ``Bio.SeqIO.write()`` function instead using ``format="fasta"``."""
def __init__(self, target, wrap=60, record2title=None):
"""Create a Fasta writer (OBSOLETE). Arguments: ... | the_stack_v2_python_sparse | .venv/Lib/site-packages/Bio/SeqIO/FastaIO.py | abner-lucas/tp-cruzi-db | train | 2 |
c8f63fd76b6864a5e765e3ee05f3fd4f48f6a6b1 | [
"if s1ap_wrapper.TestWrapper.TEST_CASE_EXECUTION_COUNT != 0:\n print('\\n**Running the test case again to identify flaky behavior')\ns1ap_wrapper.TestWrapper.TEST_CASE_EXECUTION_COUNT += 1\nprint('Test Case Execution Count:', s1ap_wrapper.TestWrapper.TEST_CASE_EXECUTION_COUNT)\nself._s1_util = S1ApUtil()",
"is... | <|body_start_0|>
if s1ap_wrapper.TestWrapper.TEST_CASE_EXECUTION_COUNT != 0:
print('\n**Running the test case again to identify flaky behavior')
s1ap_wrapper.TestWrapper.TEST_CASE_EXECUTION_COUNT += 1
print('Test Case Execution Count:', s1ap_wrapper.TestWrapper.TEST_CASE_EXECUTION_CO... | Integration Test: TestS1SetupFailureIncorrectTac | TestS1SetupFailureIncorrectTac | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestS1SetupFailureIncorrectTac:
"""Integration Test: TestS1SetupFailureIncorrectTac"""
def setUp(self):
"""Initialize before test case execution"""
<|body_0|>
def tearDown(self):
"""Cleanup after test case execution"""
<|body_1|>
def test_s1setup_fai... | stack_v2_sparse_classes_36k_train_033207 | 3,657 | permissive | [
{
"docstring": "Initialize before test case execution",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Cleanup after test case execution",
"name": "tearDown",
"signature": "def tearDown(self)"
},
{
"docstring": "S1 Setup Request with incorrect TAC value",
... | 3 | null | Implement the Python class `TestS1SetupFailureIncorrectTac` described below.
Class description:
Integration Test: TestS1SetupFailureIncorrectTac
Method signatures and docstrings:
- def setUp(self): Initialize before test case execution
- def tearDown(self): Cleanup after test case execution
- def test_s1setup_failure... | Implement the Python class `TestS1SetupFailureIncorrectTac` described below.
Class description:
Integration Test: TestS1SetupFailureIncorrectTac
Method signatures and docstrings:
- def setUp(self): Initialize before test case execution
- def tearDown(self): Cleanup after test case execution
- def test_s1setup_failure... | 0e1d895dfe625681229e181fbc2dbad83e13c5cb | <|skeleton|>
class TestS1SetupFailureIncorrectTac:
"""Integration Test: TestS1SetupFailureIncorrectTac"""
def setUp(self):
"""Initialize before test case execution"""
<|body_0|>
def tearDown(self):
"""Cleanup after test case execution"""
<|body_1|>
def test_s1setup_fai... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestS1SetupFailureIncorrectTac:
"""Integration Test: TestS1SetupFailureIncorrectTac"""
def setUp(self):
"""Initialize before test case execution"""
if s1ap_wrapper.TestWrapper.TEST_CASE_EXECUTION_COUNT != 0:
print('\n**Running the test case again to identify flaky behavior')
... | the_stack_v2_python_sparse | lte/gateway/python/integ_tests/s1aptests/test_s1setup_failure_incorrect_tac.py | magma/magma | train | 1,219 |
85b7c5dc6d142e4d24efdcab7991750d1981a662 | [
"SQL_mgr = SQL_database_manager()\nfor i in range(len(self.shapes)):\n shape = setpoint_shape + list(self.shapes[i])\n if i <= len(self.oid):\n if len(self.data) > i:\n arr = self.data[i]\n else:\n arr = np.full(shape, np.nan, order='C')\n self.data.append(arr)\n... | <|body_start_0|>
SQL_mgr = SQL_database_manager()
for i in range(len(self.shapes)):
shape = setpoint_shape + list(self.shapes[i])
if i <= len(self.oid):
if len(self.data) > i:
arr = self.data[i]
else:
arr = n... | dataclass_raw_parent | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class dataclass_raw_parent:
def generate_data_buffer(self, setpoint_shape=[]):
"""generate the buffers that are needed to write the data to the database. Args: setpoint_shape (list) : shape of the setpoints (if applicable) (measurent param is measured exactly the same amount of times than the ... | stack_v2_sparse_classes_36k_train_033208 | 7,808 | permissive | [
{
"docstring": "generate the buffers that are needed to write the data to the database. Args: setpoint_shape (list) : shape of the setpoints (if applicable) (measurent param is measured exactly the same amount of times than the setpoint)",
"name": "generate_data_buffer",
"signature": "def generate_data_... | 3 | stack_v2_sparse_classes_30k_train_008774 | Implement the Python class `dataclass_raw_parent` described below.
Class description:
Implement the dataclass_raw_parent class.
Method signatures and docstrings:
- def generate_data_buffer(self, setpoint_shape=[]): generate the buffers that are needed to write the data to the database. Args: setpoint_shape (list) : s... | Implement the Python class `dataclass_raw_parent` described below.
Class description:
Implement the dataclass_raw_parent class.
Method signatures and docstrings:
- def generate_data_buffer(self, setpoint_shape=[]): generate the buffers that are needed to write the data to the database. Args: setpoint_shape (list) : s... | dd16192256a4a2fb084f179a5eb80cf13fe689dc | <|skeleton|>
class dataclass_raw_parent:
def generate_data_buffer(self, setpoint_shape=[]):
"""generate the buffers that are needed to write the data to the database. Args: setpoint_shape (list) : shape of the setpoints (if applicable) (measurent param is measured exactly the same amount of times than the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class dataclass_raw_parent:
def generate_data_buffer(self, setpoint_shape=[]):
"""generate the buffers that are needed to write the data to the database. Args: setpoint_shape (list) : shape of the setpoints (if applicable) (measurent param is measured exactly the same amount of times than the setpoint)"""
... | the_stack_v2_python_sparse | core_tools/data/lib/data_class.py | stephanlphilips/core_tools | train | 1 | |
328333e39e08143d2f5baa92665b415619f10277 | [
"exc_type = type(exc)\nif exc_type in (exceptions.BadResponse, exceptions.ConnectionFailed):\n raise Recoverable('Encountered %s; try again' % exc) from exc\nelif exc_type is exceptions.RequestFailed:\n if exc.status_code >= 500:\n msg = 'Classifier service choked: %i' % exc.status_code\n raise ... | <|body_start_0|>
exc_type = type(exc)
if exc_type in (exceptions.BadResponse, exceptions.ConnectionFailed):
raise Recoverable('Encountered %s; try again' % exc) from exc
elif exc_type is exceptions.RequestFailed:
if exc.status_code >= 500:
msg = 'Classifie... | Extract plain text and poll the autoclassifier. In addition to generating classification suggestions, the current implementation of the autoclassifier also generates features (like word counts) and content flags (e.g. possible language issues, line numbers). | RunAutoclassifier | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunAutoclassifier:
"""Extract plain text and poll the autoclassifier. In addition to generating classification suggestions, the current implementation of the autoclassifier also generates features (like word counts) and content flags (e.g. possible language issues, line numbers)."""
def hand... | stack_v2_sparse_classes_36k_train_033209 | 8,823 | permissive | [
{
"docstring": "Handle exceptions raised when calling the classifier service.",
"name": "handle_classifier_exception",
"signature": "def handle_classifier_exception(self, exc: Exception) -> None"
},
{
"docstring": "Send plain text content to the autoclassifier.",
"name": "call_classifier",
... | 3 | stack_v2_sparse_classes_30k_train_019070 | Implement the Python class `RunAutoclassifier` described below.
Class description:
Extract plain text and poll the autoclassifier. In addition to generating classification suggestions, the current implementation of the autoclassifier also generates features (like word counts) and content flags (e.g. possible language ... | Implement the Python class `RunAutoclassifier` described below.
Class description:
Extract plain text and poll the autoclassifier. In addition to generating classification suggestions, the current implementation of the autoclassifier also generates features (like word counts) and content flags (e.g. possible language ... | 6077ce4e0685d67ce7010800083a898857158112 | <|skeleton|>
class RunAutoclassifier:
"""Extract plain text and poll the autoclassifier. In addition to generating classification suggestions, the current implementation of the autoclassifier also generates features (like word counts) and content flags (e.g. possible language issues, line numbers)."""
def hand... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RunAutoclassifier:
"""Extract plain text and poll the autoclassifier. In addition to generating classification suggestions, the current implementation of the autoclassifier also generates features (like word counts) and content flags (e.g. possible language issues, line numbers)."""
def handle_classifier... | the_stack_v2_python_sparse | agent/agent/process/classification_and_content.py | arXiv/arxiv-submission-core | train | 14 |
c278fdc10c19afbe0cab604cb5697d9da7d68e5f | [
"first_match = False\nif len(s) == 0 and len(p) == 0:\n return True\nif len(s) > 0 and len(p) > 0:\n first_match = p[0] in [s[0], '.']\nif len(p) >= 2 and p[1] == '*':\n return first_match and self.isMatch(s[1:], p) or self.isMatch(s, p[2:])\nelse:\n return first_match and self.isMatch(s[1:], p[1:])",
... | <|body_start_0|>
first_match = False
if len(s) == 0 and len(p) == 0:
return True
if len(s) > 0 and len(p) > 0:
first_match = p[0] in [s[0], '.']
if len(p) >= 2 and p[1] == '*':
return first_match and self.isMatch(s[1:], p) or self.isMatch(s, p[2:])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isMatch2(self, s, p):
"""Runtime: 1896ms :param s: str :param p: str :return: bool"""
<|body_0|>
def isMatch(self, s, p):
"""Runtime: 112ms :param s: str :param p: str :return: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
first... | stack_v2_sparse_classes_36k_train_033210 | 1,557 | no_license | [
{
"docstring": "Runtime: 1896ms :param s: str :param p: str :return: bool",
"name": "isMatch2",
"signature": "def isMatch2(self, s, p)"
},
{
"docstring": "Runtime: 112ms :param s: str :param p: str :return: bool",
"name": "isMatch",
"signature": "def isMatch(self, s, p)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014634 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isMatch2(self, s, p): Runtime: 1896ms :param s: str :param p: str :return: bool
- def isMatch(self, s, p): Runtime: 112ms :param s: str :param p: str :return: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isMatch2(self, s, p): Runtime: 1896ms :param s: str :param p: str :return: bool
- def isMatch(self, s, p): Runtime: 112ms :param s: str :param p: str :return: bool
<|skeleto... | c1c5ee72b8fe608b278ca20a58bc240fdc62b599 | <|skeleton|>
class Solution:
def isMatch2(self, s, p):
"""Runtime: 1896ms :param s: str :param p: str :return: bool"""
<|body_0|>
def isMatch(self, s, p):
"""Runtime: 112ms :param s: str :param p: str :return: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isMatch2(self, s, p):
"""Runtime: 1896ms :param s: str :param p: str :return: bool"""
first_match = False
if len(s) == 0 and len(p) == 0:
return True
if len(s) > 0 and len(p) > 0:
first_match = p[0] in [s[0], '.']
if len(p) >= 2 and... | the_stack_v2_python_sparse | 10_regular_expression_matching.py | eazow/leetcode | train | 5 | |
26fa63c095903cba2aa4389c09b75d70a999e571 | [
"dicts_node = {root.val: None}\ndicts_n = {}\n\ndef visit(root, dicts_node, dicts_n):\n dicts_n[root.val] = root\n if root.left:\n dicts_node[root.left.val] = root\n visit(root.left, dicts_node, dicts_n)\n if root.right:\n dicts_node[root.right.val] = root\n visit(root.right, di... | <|body_start_0|>
dicts_node = {root.val: None}
dicts_n = {}
def visit(root, dicts_node, dicts_n):
dicts_n[root.val] = root
if root.left:
dicts_node[root.left.val] = root
visit(root.left, dicts_node, dicts_n)
if root.right:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def distanceK(self, root, target, K):
""":type root: TreeNode :type target: TreeNode !!!!!!!!! :rtype: List[int] 48 ms"""
<|body_0|>
def distanceK_1(self, root, target, K):
"""44ms :param root: :param target: :param K: :return:"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_033211 | 3,430 | no_license | [
{
"docstring": ":type root: TreeNode :type target: TreeNode !!!!!!!!! :rtype: List[int] 48 ms",
"name": "distanceK",
"signature": "def distanceK(self, root, target, K)"
},
{
"docstring": "44ms :param root: :param target: :param K: :return:",
"name": "distanceK_1",
"signature": "def dista... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def distanceK(self, root, target, K): :type root: TreeNode :type target: TreeNode !!!!!!!!! :rtype: List[int] 48 ms
- def distanceK_1(self, root, target, K): 44ms :param root: :p... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def distanceK(self, root, target, K): :type root: TreeNode :type target: TreeNode !!!!!!!!! :rtype: List[int] 48 ms
- def distanceK_1(self, root, target, K): 44ms :param root: :p... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def distanceK(self, root, target, K):
""":type root: TreeNode :type target: TreeNode !!!!!!!!! :rtype: List[int] 48 ms"""
<|body_0|>
def distanceK_1(self, root, target, K):
"""44ms :param root: :param target: :param K: :return:"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def distanceK(self, root, target, K):
""":type root: TreeNode :type target: TreeNode !!!!!!!!! :rtype: List[int] 48 ms"""
dicts_node = {root.val: None}
dicts_n = {}
def visit(root, dicts_node, dicts_n):
dicts_n[root.val] = root
if root.left:
... | the_stack_v2_python_sparse | AllNodesDistanceKInBinaryTree_MID_863.py | 953250587/leetcode-python | train | 2 | |
d8229174eac98cd51a50c4ce0cf320bb6fa01493 | [
"super().__init__(*args, **kwargs)\nself.processor = 'scratch'\nself.pattern = re.compile(ext.processor_info[self.processor]['pattern'])\nself.template = ext.jinja_templates[self.processor]\nself.fenced_compatibility = 'fenced_code_block' in ext.compatibility",
"code_elements = []\nfor node in root.iterfind('.//p... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.processor = 'scratch'
self.pattern = re.compile(ext.processor_info[self.processor]['pattern'])
self.template = ext.jinja_templates[self.processor]
self.fenced_compatibility = 'fenced_code_block' in ext.compatibility
<|end_bo... | Searches a Document for codeblocks with the scratch language. These are then processed into the verto result and hashed for another program in the pipeline to retrieve or create into images. | ScratchTreeprocessor | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScratchTreeprocessor:
"""Searches a Document for codeblocks with the scratch language. These are then processed into the verto result and hashed for another program in the pipeline to retrieve or create into images."""
def __init__(self, ext, *args, **kwargs):
"""Args: ext: The paren... | stack_v2_sparse_classes_36k_train_033212 | 3,528 | permissive | [
{
"docstring": "Args: ext: The parent node of the element tree that children will reside in.",
"name": "__init__",
"signature": "def __init__(self, ext, *args, **kwargs)"
},
{
"docstring": "Processes the html tree finding code tags where scratch code is used and replaces with template html. Args... | 3 | stack_v2_sparse_classes_30k_test_001080 | Implement the Python class `ScratchTreeprocessor` described below.
Class description:
Searches a Document for codeblocks with the scratch language. These are then processed into the verto result and hashed for another program in the pipeline to retrieve or create into images.
Method signatures and docstrings:
- def _... | Implement the Python class `ScratchTreeprocessor` described below.
Class description:
Searches a Document for codeblocks with the scratch language. These are then processed into the verto result and hashed for another program in the pipeline to retrieve or create into images.
Method signatures and docstrings:
- def _... | bfce624d59968767c07ee805352dceae3a543bd1 | <|skeleton|>
class ScratchTreeprocessor:
"""Searches a Document for codeblocks with the scratch language. These are then processed into the verto result and hashed for another program in the pipeline to retrieve or create into images."""
def __init__(self, ext, *args, **kwargs):
"""Args: ext: The paren... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScratchTreeprocessor:
"""Searches a Document for codeblocks with the scratch language. These are then processed into the verto result and hashed for another program in the pipeline to retrieve or create into images."""
def __init__(self, ext, *args, **kwargs):
"""Args: ext: The parent node of the... | the_stack_v2_python_sparse | verto/processors/ScratchTreeprocessor.py | uccser/verto | train | 4 |
684710d8b3e5fda9ec855ba73efbd6443531772d | [
"super(DelayCross, self).__init__()\nself.x, self.y = array_cross_check(x, y, 1)\nself.tau = None",
"self.tau = tau\nn = self.x.size\n_sum = 0\nfor i in range(n - self.tau):\n _sum += (self.x[i] - self.x.mean()) / self.x.std() * ((self.y[i + self.tau] - self.y.mean()) / self.y.std())\nself.statistics = _sum / ... | <|body_start_0|>
super(DelayCross, self).__init__()
self.x, self.y = array_cross_check(x, y, 1)
self.tau = None
<|end_body_0|>
<|body_start_1|>
self.tau = tau
n = self.x.size
_sum = 0
for i in range(n - self.tau):
_sum += (self.x[i] - self.x.mean()) /... | Two variable delay cross correlation. | DelayCross | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DelayCross:
"""Two variable delay cross correlation."""
def __init__(self, x: array_like, y: array_like):
""":param x: array_like :param y: array_like"""
<|body_0|>
def __call__(self, tau: int):
"""Calculate delay cross correlation. :param tau: int delay length :... | stack_v2_sparse_classes_36k_train_033213 | 8,613 | no_license | [
{
"docstring": ":param x: array_like :param y: array_like",
"name": "__init__",
"signature": "def __init__(self, x: array_like, y: array_like)"
},
{
"docstring": "Calculate delay cross correlation. :param tau: int delay length :return: class self",
"name": "__call__",
"signature": "def _... | 3 | null | Implement the Python class `DelayCross` described below.
Class description:
Two variable delay cross correlation.
Method signatures and docstrings:
- def __init__(self, x: array_like, y: array_like): :param x: array_like :param y: array_like
- def __call__(self, tau: int): Calculate delay cross correlation. :param ta... | Implement the Python class `DelayCross` described below.
Class description:
Two variable delay cross correlation.
Method signatures and docstrings:
- def __init__(self, x: array_like, y: array_like): :param x: array_like :param y: array_like
- def __call__(self, tau: int): Calculate delay cross correlation. :param ta... | 1c8d5fbf3676dc81e9f143e93ee2564359519b11 | <|skeleton|>
class DelayCross:
"""Two variable delay cross correlation."""
def __init__(self, x: array_like, y: array_like):
""":param x: array_like :param y: array_like"""
<|body_0|>
def __call__(self, tau: int):
"""Calculate delay cross correlation. :param tau: int delay length :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DelayCross:
"""Two variable delay cross correlation."""
def __init__(self, x: array_like, y: array_like):
""":param x: array_like :param y: array_like"""
super(DelayCross, self).__init__()
self.x, self.y = array_cross_check(x, y, 1)
self.tau = None
def __call__(self, ... | the_stack_v2_python_sparse | statistics/correlation.py | qliu0/PythonInAirSeaScience | train | 0 |
70901bf4a8b9ea2cbf198774073b2eabffcf3ec4 | [
"self.login_params = {'continue': 'http://www.google.com/trends', 'PersistentCookie': 'yes', 'Email': username, 'Passwd': password}\nself.headers = [('Referrer', 'https://www.google.com/accounts/ServiceLoginBoxAuth'), ('Content-type', 'application/x-www-form-urlencoded'), ('User-Agent', 'Mozilla/5.0 (X11; Linux x86... | <|body_start_0|>
self.login_params = {'continue': 'http://www.google.com/trends', 'PersistentCookie': 'yes', 'Email': username, 'Passwd': password}
self.headers = [('Referrer', 'https://www.google.com/accounts/ServiceLoginBoxAuth'), ('Content-type', 'application/x-www-form-urlencoded'), ('User-Agent', '... | Google Trends API Recommended usage: from csv import DictReader r = pyGTrends(username, password) r.download_report(('pants', 'skirt')) d = DictReader(r.csv().split(' ')) | pyGTrends | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class pyGTrends:
"""Google Trends API Recommended usage: from csv import DictReader r = pyGTrends(username, password) r.download_report(('pants', 'skirt')) d = DictReader(r.csv().split(' '))"""
def __init__(self, username, password):
"""provide login and password to be used to connect to G... | stack_v2_sparse_classes_36k_train_033214 | 4,159 | permissive | [
{
"docstring": "provide login and password to be used to connect to Google Analytics all immutable system variables are also defined here website_id is the ID of the specific site on google analytics",
"name": "__init__",
"signature": "def __init__(self, username, password)"
},
{
"docstring": "c... | 4 | null | Implement the Python class `pyGTrends` described below.
Class description:
Google Trends API Recommended usage: from csv import DictReader r = pyGTrends(username, password) r.download_report(('pants', 'skirt')) d = DictReader(r.csv().split(' '))
Method signatures and docstrings:
- def __init__(self, username, passwor... | Implement the Python class `pyGTrends` described below.
Class description:
Google Trends API Recommended usage: from csv import DictReader r = pyGTrends(username, password) r.download_report(('pants', 'skirt')) d = DictReader(r.csv().split(' '))
Method signatures and docstrings:
- def __init__(self, username, passwor... | 72dbdf41b0250708ad525030128cc7c3948b3f41 | <|skeleton|>
class pyGTrends:
"""Google Trends API Recommended usage: from csv import DictReader r = pyGTrends(username, password) r.download_report(('pants', 'skirt')) d = DictReader(r.csv().split(' '))"""
def __init__(self, username, password):
"""provide login and password to be used to connect to G... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class pyGTrends:
"""Google Trends API Recommended usage: from csv import DictReader r = pyGTrends(username, password) r.download_report(('pants', 'skirt')) d = DictReader(r.csv().split(' '))"""
def __init__(self, username, password):
"""provide login and password to be used to connect to Google Analyti... | the_stack_v2_python_sparse | ut/others/pytrends.py | thorwhalen/ut | train | 6 |
3f57ee985d79ce69b0e510aff3a59a90e31c59d9 | [
"super(CNN_Text, self).__init__()\nself.args = args\nembed_num = args.embed_num\nembed_dim = args.embed_dim\nclass_num = args.class_num\nchannel_num = args.kernel_num\nkernel_size = args.kernel_sizes\nself.embedding = nn.Embedding(embed_num, embed_dim)\nself.conv = nn.ModuleList([nn.Conv2d(1, channel_num, (K, embed... | <|body_start_0|>
super(CNN_Text, self).__init__()
self.args = args
embed_num = args.embed_num
embed_dim = args.embed_dim
class_num = args.class_num
channel_num = args.kernel_num
kernel_size = args.kernel_sizes
self.embedding = nn.Embedding(embed_num, embed... | CNN_Text | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CNN_Text:
def __init__(self, args):
"""Your code here. Define a text CNN structure. Note that args.kernel_sizes is a list, so you may need to use nn.ModuleList."""
<|body_0|>
def forward(self, x):
"""Your code here. Give the forward pass of the model. With multiple k... | stack_v2_sparse_classes_36k_train_033215 | 1,450 | no_license | [
{
"docstring": "Your code here. Define a text CNN structure. Note that args.kernel_sizes is a list, so you may need to use nn.ModuleList.",
"name": "__init__",
"signature": "def __init__(self, args)"
},
{
"docstring": "Your code here. Give the forward pass of the model. With multiple kernel size... | 2 | stack_v2_sparse_classes_30k_train_017079 | Implement the Python class `CNN_Text` described below.
Class description:
Implement the CNN_Text class.
Method signatures and docstrings:
- def __init__(self, args): Your code here. Define a text CNN structure. Note that args.kernel_sizes is a list, so you may need to use nn.ModuleList.
- def forward(self, x): Your c... | Implement the Python class `CNN_Text` described below.
Class description:
Implement the CNN_Text class.
Method signatures and docstrings:
- def __init__(self, args): Your code here. Define a text CNN structure. Note that args.kernel_sizes is a list, so you may need to use nn.ModuleList.
- def forward(self, x): Your c... | f1af0599ac8c3c8be4852472838dca775a22aa53 | <|skeleton|>
class CNN_Text:
def __init__(self, args):
"""Your code here. Define a text CNN structure. Note that args.kernel_sizes is a list, so you may need to use nn.ModuleList."""
<|body_0|>
def forward(self, x):
"""Your code here. Give the forward pass of the model. With multiple k... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CNN_Text:
def __init__(self, args):
"""Your code here. Define a text CNN structure. Note that args.kernel_sizes is a list, so you may need to use nn.ModuleList."""
super(CNN_Text, self).__init__()
self.args = args
embed_num = args.embed_num
embed_dim = args.embed_dim
... | the_stack_v2_python_sparse | homework5/HuaiyuanYing/model.py | Lukeming-tsinghua/pytorch-NLP-guidance | train | 12 | |
1ad46e6399499ed48c7764d6b2bc56c5184d04f3 | [
"self.url = str(url) + '/' + ODL_NETWORKS + '?limit=1'\nself.username = username\nself.password = password\nself.auth_cookies = None\nself.last_request = None\nself.expired = None\nself.session_timeout = cfg.CONF.ml2_odl.session_timeout * 60\nself.session_deadline = 0",
"try:\n r = requests.get(self.url, auth=... | <|body_start_0|>
self.url = str(url) + '/' + ODL_NETWORKS + '?limit=1'
self.username = username
self.password = password
self.auth_cookies = None
self.last_request = None
self.expired = None
self.session_timeout = cfg.CONF.ml2_odl.session_timeout * 60
self... | Attaches the JSESSIONID and JSESSIONIDSSO cookies to an HTTP Request. If the cookies are not available or when the session expires, a new set of cookies are obtained. | JsessionId | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JsessionId:
"""Attaches the JSESSIONID and JSESSIONIDSSO cookies to an HTTP Request. If the cookies are not available or when the session expires, a new set of cookies are obtained."""
def __init__(self, url, username, password):
"""Initialization function for JsessionId."""
... | stack_v2_sparse_classes_36k_train_033216 | 13,929 | permissive | [
{
"docstring": "Initialization function for JsessionId.",
"name": "__init__",
"signature": "def __init__(self, url, username, password)"
},
{
"docstring": "Make a REST call to obtain cookies for ODL authenticiation.",
"name": "obtain_auth_cookies",
"signature": "def obtain_auth_cookies(s... | 3 | stack_v2_sparse_classes_30k_train_002402 | Implement the Python class `JsessionId` described below.
Class description:
Attaches the JSESSIONID and JSESSIONIDSSO cookies to an HTTP Request. If the cookies are not available or when the session expires, a new set of cookies are obtained.
Method signatures and docstrings:
- def __init__(self, url, username, passw... | Implement the Python class `JsessionId` described below.
Class description:
Attaches the JSESSIONID and JSESSIONIDSSO cookies to an HTTP Request. If the cookies are not available or when the session expires, a new set of cookies are obtained.
Method signatures and docstrings:
- def __init__(self, url, username, passw... | 0c0e233290a0012f4d8320d047de63f213984944 | <|skeleton|>
class JsessionId:
"""Attaches the JSESSIONID and JSESSIONIDSSO cookies to an HTTP Request. If the cookies are not available or when the session expires, a new set of cookies are obtained."""
def __init__(self, url, username, password):
"""Initialization function for JsessionId."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JsessionId:
"""Attaches the JSESSIONID and JSESSIONIDSSO cookies to an HTTP Request. If the cookies are not available or when the session expires, a new set of cookies are obtained."""
def __init__(self, url, username, password):
"""Initialization function for JsessionId."""
self.url = st... | the_stack_v2_python_sparse | neutron/plugins/ml2/drivers/mechanism_odl.py | cernops/neutron | train | 3 |
662627630756f53d82ef36047548231f793618e1 | [
"model_name = model._meta.label_lower\npos = model_name.find('.')\ntable_name = model_name[pos + 1:]\nif table_name in self.route_encuestas:\n return 'encuestas'\nelif table_name in self.route_uxxienc_resul:\n return 'uxxienc_resul'\nreturn None",
"if model._meta.label_lower in self.route_encuestas:\n re... | <|body_start_0|>
model_name = model._meta.label_lower
pos = model_name.find('.')
table_name = model_name[pos + 1:]
if table_name in self.route_encuestas:
return 'encuestas'
elif table_name in self.route_uxxienc_resul:
return 'uxxienc_resul'
return ... | A router to control all database operations on models in the Encuestas applications. | EncuestasRouter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncuestasRouter:
"""A router to control all database operations on models in the Encuestas applications."""
def db_for_read(self, model, **hints):
"""Attempts to read TipoCampania models go to Encuestas db."""
<|body_0|>
def db_for_write(self, model, **hints):
""... | stack_v2_sparse_classes_36k_train_033217 | 1,730 | no_license | [
{
"docstring": "Attempts to read TipoCampania models go to Encuestas db.",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "Attempts to write TipoCampania models go to Encuestas db.",
"name": "db_for_write",
"signature": "def db_for_write(sel... | 4 | stack_v2_sparse_classes_30k_train_013943 | Implement the Python class `EncuestasRouter` described below.
Class description:
A router to control all database operations on models in the Encuestas applications.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read TipoCampania models go to Encuestas db.
- def db_for_write(s... | Implement the Python class `EncuestasRouter` described below.
Class description:
A router to control all database operations on models in the Encuestas applications.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read TipoCampania models go to Encuestas db.
- def db_for_write(s... | ea41397bbee7c204f590d39569a9060f1410a819 | <|skeleton|>
class EncuestasRouter:
"""A router to control all database operations on models in the Encuestas applications."""
def db_for_read(self, model, **hints):
"""Attempts to read TipoCampania models go to Encuestas db."""
<|body_0|>
def db_for_write(self, model, **hints):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EncuestasRouter:
"""A router to control all database operations on models in the Encuestas applications."""
def db_for_read(self, model, **hints):
"""Attempts to read TipoCampania models go to Encuestas db."""
model_name = model._meta.label_lower
pos = model_name.find('.')
... | the_stack_v2_python_sparse | django/tfmsurveysapp/router_copy.py | dsm9/TreballFiMaster | train | 0 |
7c14b88af4a3ab5335c490bed3c663ac80c2b02e | [
"w = ScaleProperties(None)\nyield w\nw.close()",
"assert isinstance(widget, QtWidgets.QDialog)\nassert widget.windowTitle() == 'Scale Properties'\nassert widget.cbX.count() == 6\nassert widget.cbY.count() == 12\nassert widget.cbView.count() == 7",
"assert widget.getValues() == ('x', 'y')\nwidget.cbX.setCurrentI... | <|body_start_0|>
w = ScaleProperties(None)
yield w
w.close()
<|end_body_0|>
<|body_start_1|>
assert isinstance(widget, QtWidgets.QDialog)
assert widget.windowTitle() == 'Scale Properties'
assert widget.cbX.count() == 6
assert widget.cbY.count() == 12
asse... | Test the ScaleProperties | ScalePropertiesTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScalePropertiesTest:
"""Test the ScaleProperties"""
def widget(self, qapp):
"""Create/Destroy the ScaleProperties"""
<|body_0|>
def testDefaults(self, widget):
"""Test the GUI in its default state"""
<|body_1|>
def testGetValues(self, widget):
... | stack_v2_sparse_classes_36k_train_033218 | 1,631 | permissive | [
{
"docstring": "Create/Destroy the ScaleProperties",
"name": "widget",
"signature": "def widget(self, qapp)"
},
{
"docstring": "Test the GUI in its default state",
"name": "testDefaults",
"signature": "def testDefaults(self, widget)"
},
{
"docstring": "Test the values returned",
... | 4 | null | Implement the Python class `ScalePropertiesTest` described below.
Class description:
Test the ScaleProperties
Method signatures and docstrings:
- def widget(self, qapp): Create/Destroy the ScaleProperties
- def testDefaults(self, widget): Test the GUI in its default state
- def testGetValues(self, widget): Test the v... | Implement the Python class `ScalePropertiesTest` described below.
Class description:
Test the ScaleProperties
Method signatures and docstrings:
- def widget(self, qapp): Create/Destroy the ScaleProperties
- def testDefaults(self, widget): Test the GUI in its default state
- def testGetValues(self, widget): Test the v... | 55b1e9f6db58e33729f2a93b7dd1d8bf255b46f7 | <|skeleton|>
class ScalePropertiesTest:
"""Test the ScaleProperties"""
def widget(self, qapp):
"""Create/Destroy the ScaleProperties"""
<|body_0|>
def testDefaults(self, widget):
"""Test the GUI in its default state"""
<|body_1|>
def testGetValues(self, widget):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScalePropertiesTest:
"""Test the ScaleProperties"""
def widget(self, qapp):
"""Create/Destroy the ScaleProperties"""
w = ScaleProperties(None)
yield w
w.close()
def testDefaults(self, widget):
"""Test the GUI in its default state"""
assert isinstance(w... | the_stack_v2_python_sparse | src/sas/qtgui/Plotting/UnitTesting/ScalePropertiesTest.py | SasView/sasview | train | 48 |
7e550de9e4ee34d1b366e209c3afb30bffed2875 | [
"try:\n self.inputFile = path\n self.reader = csv.reader(open(path), delimiter=',')\nexcept Exception as e:\n print('Cannot find File.')",
"result = []\ndata = pd.read_csv(self.inputFile, nrows=1)\nprev_id = data['obj_id'].values[0]\ntry:\n tmp = None\n index = 0\n for line in self.reader:\n ... | <|body_start_0|>
try:
self.inputFile = path
self.reader = csv.reader(open(path), delimiter=',')
except Exception as e:
print('Cannot find File.')
<|end_body_0|>
<|body_start_1|>
result = []
data = pd.read_csv(self.inputFile, nrows=1)
prev_id =... | generated source for class TrajectoryParser | TrajectoryParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrajectoryParser:
"""generated source for class TrajectoryParser"""
def __init__(self, path):
"""generated source for method __init__"""
<|body_0|>
def get_traj_set(self):
"""generated source for method get_traj_set"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_033219 | 1,579 | no_license | [
{
"docstring": "generated source for method __init__",
"name": "__init__",
"signature": "def __init__(self, path)"
},
{
"docstring": "generated source for method get_traj_set",
"name": "get_traj_set",
"signature": "def get_traj_set(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002044 | Implement the Python class `TrajectoryParser` described below.
Class description:
generated source for class TrajectoryParser
Method signatures and docstrings:
- def __init__(self, path): generated source for method __init__
- def get_traj_set(self): generated source for method get_traj_set | Implement the Python class `TrajectoryParser` described below.
Class description:
generated source for class TrajectoryParser
Method signatures and docstrings:
- def __init__(self, path): generated source for method __init__
- def get_traj_set(self): generated source for method get_traj_set
<|skeleton|>
class Trajec... | 5ef2064249e7e81dbf01e1e01107fb2dc088ab07 | <|skeleton|>
class TrajectoryParser:
"""generated source for class TrajectoryParser"""
def __init__(self, path):
"""generated source for method __init__"""
<|body_0|>
def get_traj_set(self):
"""generated source for method get_traj_set"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TrajectoryParser:
"""generated source for class TrajectoryParser"""
def __init__(self, path):
"""generated source for method __init__"""
try:
self.inputFile = path
self.reader = csv.reader(open(path), delimiter=',')
except Exception as e:
print(... | the_stack_v2_python_sparse | src/Patterns/Convoy/TrajectoryParser.py | storrijos/FourSquare-Dataset | train | 0 |
24eda61b4eb9bf82940f548487f7ff09425ca867 | [
"if minfo is None:\n minfo = {}\nsuper(DumpJournalBlocksMessage, self).__init__(minfo)\nself.IsSystemMessage = False\nself.IsForward = True\nself.IsReliable = True\nself.Count = minfo.get('Count', 0)",
"result = super(DumpJournalBlocksMessage, self).dump()\nresult['Count'] = self.Count\nreturn result"
] | <|body_start_0|>
if minfo is None:
minfo = {}
super(DumpJournalBlocksMessage, self).__init__(minfo)
self.IsSystemMessage = False
self.IsForward = True
self.IsReliable = True
self.Count = minfo.get('Count', 0)
<|end_body_0|>
<|body_start_1|>
result = s... | Dump journal blocks messages represent the message format for exchanging dump journal blocks messages. Attributes: DumpJournalBlocksMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this message is a system message. IsForward (bool): Whether or not this message is forwarde... | DumpJournalBlocksMessage | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DumpJournalBlocksMessage:
"""Dump journal blocks messages represent the message format for exchanging dump journal blocks messages. Attributes: DumpJournalBlocksMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this message is a system message. IsFor... | stack_v2_sparse_classes_36k_train_033220 | 5,835 | permissive | [
{
"docstring": "Constructor for DumpJournalBlocksMessage class. Args: minfo (dict): A dict containing intialization values for a DumpJournalBlocksMessage.",
"name": "__init__",
"signature": "def __init__(self, minfo=None)"
},
{
"docstring": "Returns a dict containing information about the DumpJo... | 2 | stack_v2_sparse_classes_30k_train_001220 | Implement the Python class `DumpJournalBlocksMessage` described below.
Class description:
Dump journal blocks messages represent the message format for exchanging dump journal blocks messages. Attributes: DumpJournalBlocksMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not ... | Implement the Python class `DumpJournalBlocksMessage` described below.
Class description:
Dump journal blocks messages represent the message format for exchanging dump journal blocks messages. Attributes: DumpJournalBlocksMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not ... | 8f4ca1aab54ef420a0db10c8ca822ec8686cd423 | <|skeleton|>
class DumpJournalBlocksMessage:
"""Dump journal blocks messages represent the message format for exchanging dump journal blocks messages. Attributes: DumpJournalBlocksMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this message is a system message. IsFor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DumpJournalBlocksMessage:
"""Dump journal blocks messages represent the message format for exchanging dump journal blocks messages. Attributes: DumpJournalBlocksMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this message is a system message. IsForward (bool): ... | the_stack_v2_python_sparse | validator/journal/messages/journal_debug.py | aludvik/sawtooth-core | train | 0 |
e68390486d8f965e8575efa1a2af47ed64b1ccb4 | [
"super(DataDisplay, self).__init__(parent)\nself.setupUi(self)\nself.parent = parent\ntmpstr = self.titleLbl.text() + ' ' + self.parent.datatype\nself.titleLbl.setText(tmpstr)\nself.dataEdit.setText(self.parent.datastr)\nself.acceptBttn.clicked.connect(self.accept)\nself.helpBttn.clicked.connect(self.displayhelp)\n... | <|body_start_0|>
super(DataDisplay, self).__init__(parent)
self.setupUi(self)
self.parent = parent
tmpstr = self.titleLbl.text() + ' ' + self.parent.datatype
self.titleLbl.setText(tmpstr)
self.dataEdit.setText(self.parent.datastr)
self.acceptBttn.clicked.connect(s... | A GUI to display English sentences generated with random data. | DataDisplay | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataDisplay:
"""A GUI to display English sentences generated with random data."""
def __init__(self, parent=None):
"""Initialize the GUI and display the data."""
<|body_0|>
def resizeEvent(self, event):
"""Resize the GUI and record GUI sizing data."""
<|b... | stack_v2_sparse_classes_36k_train_033221 | 2,732 | no_license | [
{
"docstring": "Initialize the GUI and display the data.",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "Resize the GUI and record GUI sizing data.",
"name": "resizeEvent",
"signature": "def resizeEvent(self, event)"
},
{
"docstring": "Disp... | 4 | stack_v2_sparse_classes_30k_train_004941 | Implement the Python class `DataDisplay` described below.
Class description:
A GUI to display English sentences generated with random data.
Method signatures and docstrings:
- def __init__(self, parent=None): Initialize the GUI and display the data.
- def resizeEvent(self, event): Resize the GUI and record GUI sizing... | Implement the Python class `DataDisplay` described below.
Class description:
A GUI to display English sentences generated with random data.
Method signatures and docstrings:
- def __init__(self, parent=None): Initialize the GUI and display the data.
- def resizeEvent(self, event): Resize the GUI and record GUI sizing... | 2fff3361cfd1f9f479c5f36f110a10b3122c02f8 | <|skeleton|>
class DataDisplay:
"""A GUI to display English sentences generated with random data."""
def __init__(self, parent=None):
"""Initialize the GUI and display the data."""
<|body_0|>
def resizeEvent(self, event):
"""Resize the GUI and record GUI sizing data."""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataDisplay:
"""A GUI to display English sentences generated with random data."""
def __init__(self, parent=None):
"""Initialize the GUI and display the data."""
super(DataDisplay, self).__init__(parent)
self.setupUi(self)
self.parent = parent
tmpstr = self.titleLb... | the_stack_v2_python_sparse | machinetrans/parser/datadisplay.py | eberdeed/machinetrans | train | 0 |
e9084fd4389f61fc0a3efa6bbec6de19d3d46f7b | [
"self.radius = radius\nself.x_center = x_center\nself.y_center = y_center",
"while 1:\n x = random.uniform(self.x_center - self.radius, self.x_center + self.radius)\n y = random.uniform(self.y_center - self.radius, self.y_center + self.radius)\n if (x - self.x_center) ** 2 + (y - self.y_center) ** 2 <= s... | <|body_start_0|>
self.radius = radius
self.x_center = x_center
self.y_center = y_center
<|end_body_0|>
<|body_start_1|>
while 1:
x = random.uniform(self.x_center - self.radius, self.x_center + self.radius)
y = random.uniform(self.y_center - self.radius, self.y_ce... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float"""
<|body_0|>
def randPoint(self):
""":rtype: List[float]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.radius = radi... | stack_v2_sparse_classes_36k_train_033222 | 759 | no_license | [
{
"docstring": ":type radius: float :type x_center: float :type y_center: float",
"name": "__init__",
"signature": "def __init__(self, radius, x_center, y_center)"
},
{
"docstring": ":rtype: List[float]",
"name": "randPoint",
"signature": "def randPoint(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005011 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, radius, x_center, y_center): :type radius: float :type x_center: float :type y_center: float
- def randPoint(self): :rtype: List[float] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, radius, x_center, y_center): :type radius: float :type x_center: float :type y_center: float
- def randPoint(self): :rtype: List[float]
<|skeleton|>
class Sol... | baa50a759218809f5e92b54e134ad77a43a0da3b | <|skeleton|>
class Solution:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float"""
<|body_0|>
def randPoint(self):
""":rtype: List[float]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float"""
self.radius = radius
self.x_center = x_center
self.y_center = y_center
def randPoint(self):
""":rtype: List[float]"""
while 1:
... | the_stack_v2_python_sparse | GenerateRandomPointinaCircle478.py | wyf19901121/LeetCodeForPython | train | 0 | |
6ed33c6bf49f25268418a621a2d6612f225609f7 | [
"dummy = ListNode(0)\ndummy.next = head\nfast, slow = (dummy, dummy)\nfor i in range(n + 1):\n fast = fast.next\nwhile fast is not None:\n fast = fast.next\n slow = slow.next\nslow.next = slow.next.next\nreturn dummy.next",
"dummy = ListNode(0)\ndummy.next = head\nlength = 0\nindex = head\nwhile index is... | <|body_start_0|>
dummy = ListNode(0)
dummy.next = head
fast, slow = (dummy, dummy)
for i in range(n + 1):
fast = fast.next
while fast is not None:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy.next
<|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
"""一次遍历 :param head: :param n: :return:"""
<|body_0|>
def removeNthFromEnd2(self, head: ListNode, n: int) -> ListNode:
"""两次遍历,第一次遍历获得链表长度,第二次遍历到相应位置然后进行删除操作 :param head: :param n: :return:"""
... | stack_v2_sparse_classes_36k_train_033223 | 1,493 | no_license | [
{
"docstring": "一次遍历 :param head: :param n: :return:",
"name": "removeNthFromEnd",
"signature": "def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode"
},
{
"docstring": "两次遍历,第一次遍历获得链表长度,第二次遍历到相应位置然后进行删除操作 :param head: :param n: :return:",
"name": "removeNthFromEnd2",
"signatur... | 2 | stack_v2_sparse_classes_30k_train_017251 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: 一次遍历 :param head: :param n: :return:
- def removeNthFromEnd2(self, head: ListNode, n: int) -> ListNode: 两次遍历,第一次遍历... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: 一次遍历 :param head: :param n: :return:
- def removeNthFromEnd2(self, head: ListNode, n: int) -> ListNode: 两次遍历,第一次遍历... | 5647b418cc932cceb9e311fec016c089ca7d22d5 | <|skeleton|>
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
"""一次遍历 :param head: :param n: :return:"""
<|body_0|>
def removeNthFromEnd2(self, head: ListNode, n: int) -> ListNode:
"""两次遍历,第一次遍历获得链表长度,第二次遍历到相应位置然后进行删除操作 :param head: :param n: :return:"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
"""一次遍历 :param head: :param n: :return:"""
dummy = ListNode(0)
dummy.next = head
fast, slow = (dummy, dummy)
for i in range(n + 1):
fast = fast.next
while fast is not None:
... | the_stack_v2_python_sparse | 链表相关/删除链表倒数第N个节点并返回头节点.py | EricWangyz/Exercises | train | 0 | |
1f1767f70b8fc5fb4f5bf2a925a98dadd3df7ed0 | [
"if len(chars) == 1:\n return 1\nstart = 0\ncount = 1\ni = 1\nwhile i < len(chars):\n if chars[i] != chars[i - 1]:\n if count > 1:\n temp = list(str(count))\n for el in temp:\n chars[start + 1] = el\n start += 1\n del chars[start + 1:i]\n ... | <|body_start_0|>
if len(chars) == 1:
return 1
start = 0
count = 1
i = 1
while i < len(chars):
if chars[i] != chars[i - 1]:
if count > 1:
temp = list(str(count))
for el in temp:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def compress(self, chars):
""":type chars: List[str] :rtype: int"""
<|body_0|>
def compress2(self, chars):
""":type chars: List[str] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(chars) == 1:
return 1
... | stack_v2_sparse_classes_36k_train_033224 | 1,940 | no_license | [
{
"docstring": ":type chars: List[str] :rtype: int",
"name": "compress",
"signature": "def compress(self, chars)"
},
{
"docstring": ":type chars: List[str] :rtype: int",
"name": "compress2",
"signature": "def compress2(self, chars)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012873 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def compress(self, chars): :type chars: List[str] :rtype: int
- def compress2(self, chars): :type chars: List[str] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def compress(self, chars): :type chars: List[str] :rtype: int
- def compress2(self, chars): :type chars: List[str] :rtype: int
<|skeleton|>
class Solution:
def compress(sel... | 131aae52be6a62b284aee686dcb17ff85809a416 | <|skeleton|>
class Solution:
def compress(self, chars):
""":type chars: List[str] :rtype: int"""
<|body_0|>
def compress2(self, chars):
""":type chars: List[str] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def compress(self, chars):
""":type chars: List[str] :rtype: int"""
if len(chars) == 1:
return 1
start = 0
count = 1
i = 1
while i < len(chars):
if chars[i] != chars[i - 1]:
if count > 1:
temp... | the_stack_v2_python_sparse | string/443.py | zxmeng/LeetCode | train | 0 | |
7ed6f25daa476db5a0a995c7573647110e05404d | [
"if not matrix or not matrix[0]:\n return 0\nm, n = (len(matrix), len(matrix[0]))\nsm = []\nfor i in range(m):\n for j in range(n):\n sm.append((matrix[i][j], i, j))\nsm.sort()\ndxy = [0, 1, 0, -1, 0]\ndp = [[1] * n for i in range(m)]\nfor v, i, j in sm:\n for k in range(4):\n di, dj = (i + d... | <|body_start_0|>
if not matrix or not matrix[0]:
return 0
m, n = (len(matrix), len(matrix[0]))
sm = []
for i in range(m):
for j in range(n):
sm.append((matrix[i][j], i, j))
sm.sort()
dxy = [0, 1, 0, -1, 0]
dp = [[1] * n for ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestIncreasingPath(self, matrix):
""":type matrix: List[List[int]] :rtype: int 解法1:时间复杂度O(n^2)"""
<|body_0|>
def longestIncreasingPath2(self, matrix):
""":type matrix: List[List[int]] :rtype: int 解法2:时间复杂度O(n^3) 会超时"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_033225 | 40,727 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :rtype: int 解法1:时间复杂度O(n^2)",
"name": "longestIncreasingPath",
"signature": "def longestIncreasingPath(self, matrix)"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: int 解法2:时间复杂度O(n^3) 会超时",
"name": "longestIncreasingPath2",
"signat... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestIncreasingPath(self, matrix): :type matrix: List[List[int]] :rtype: int 解法1:时间复杂度O(n^2)
- def longestIncreasingPath2(self, matrix): :type matrix: List[List[int]] :rtyp... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestIncreasingPath(self, matrix): :type matrix: List[List[int]] :rtype: int 解法1:时间复杂度O(n^2)
- def longestIncreasingPath2(self, matrix): :type matrix: List[List[int]] :rtyp... | fe9fb43fca35ba493c2c57baa66f126571450ef9 | <|skeleton|>
class Solution:
def longestIncreasingPath(self, matrix):
""":type matrix: List[List[int]] :rtype: int 解法1:时间复杂度O(n^2)"""
<|body_0|>
def longestIncreasingPath2(self, matrix):
""":type matrix: List[List[int]] :rtype: int 解法2:时间复杂度O(n^3) 会超时"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestIncreasingPath(self, matrix):
""":type matrix: List[List[int]] :rtype: int 解法1:时间复杂度O(n^2)"""
if not matrix or not matrix[0]:
return 0
m, n = (len(matrix), len(matrix[0]))
sm = []
for i in range(m):
for j in range(n):
... | the_stack_v2_python_sparse | Week_03/id_26/LeetCode_329_26.py | xiaoluome/algorithm | train | 1 | |
49aad1596cf4e496a21fe7c155aa8eb3c85975cf | [
"body = eval(response_self.request.body)\nuser_id = str(body['userId'])\nuser_name_want = str(body['userName'])\nif judgeIfPermiss(user_id=user_id, mode=1, page='systemUsers') == False:\n return {'status': 0, 'errorInfo': '用户没有权限查看', 'data': {}}\nreturn self.returnData(user_id, user_name_want)",
"res = MyBaseM... | <|body_start_0|>
body = eval(response_self.request.body)
user_id = str(body['userId'])
user_name_want = str(body['userName'])
if judgeIfPermiss(user_id=user_id, mode=1, page='systemUsers') == False:
return {'status': 0, 'errorInfo': '用户没有权限查看', 'data': {}}
return self... | 查看一个用户的基本信息,前端发来的信息为: "userId":"admin", "userName":"用户一", 本函数接收该信息,判断userId用户是否拥有查看权限,并按查询结果返回: { "status":1,//1表示成功,0表示失败 "errorInfo":"用户没有权限查看",//status为0时,前端展示errorinfo "data":{ "userName":"用户一", "description":"巴拉巴拉", "userTeam":"用户组一", "roleTeam":"角色组一" } } | GetOneUser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetOneUser:
"""查看一个用户的基本信息,前端发来的信息为: "userId":"admin", "userName":"用户一", 本函数接收该信息,判断userId用户是否拥有查看权限,并按查询结果返回: { "status":1,//1表示成功,0表示失败 "errorInfo":"用户没有权限查看",//status为0时,前端展示errorinfo "data":{ "userName":"用户一", "description":"巴拉巴拉", "userTeam":"用户组一", "roleTeam":"角色组一" } }"""
def entry(se... | stack_v2_sparse_classes_36k_train_033226 | 2,221 | no_license | [
{
"docstring": "response为tornado下get函数接收到前端数据后的self",
"name": "entry",
"signature": "def entry(self, response_self)"
},
{
"docstring": "从数据库中取出信息并返回 data: { name: \"用户一\", description: \"巴拉巴拉\", userTeamName: \"一号用户组\", roleTeamName: \"一号角色组\", passWord: \"XXX\" }",
"name": "returnData",
... | 2 | stack_v2_sparse_classes_30k_train_018390 | Implement the Python class `GetOneUser` described below.
Class description:
查看一个用户的基本信息,前端发来的信息为: "userId":"admin", "userName":"用户一", 本函数接收该信息,判断userId用户是否拥有查看权限,并按查询结果返回: { "status":1,//1表示成功,0表示失败 "errorInfo":"用户没有权限查看",//status为0时,前端展示errorinfo "data":{ "userName":"用户一", "description":"巴拉巴拉", "userTeam":"用户组一", "ro... | Implement the Python class `GetOneUser` described below.
Class description:
查看一个用户的基本信息,前端发来的信息为: "userId":"admin", "userName":"用户一", 本函数接收该信息,判断userId用户是否拥有查看权限,并按查询结果返回: { "status":1,//1表示成功,0表示失败 "errorInfo":"用户没有权限查看",//status为0时,前端展示errorinfo "data":{ "userName":"用户一", "description":"巴拉巴拉", "userTeam":"用户组一", "ro... | a31364869894c72349e3587944ecb4fda018e020 | <|skeleton|>
class GetOneUser:
"""查看一个用户的基本信息,前端发来的信息为: "userId":"admin", "userName":"用户一", 本函数接收该信息,判断userId用户是否拥有查看权限,并按查询结果返回: { "status":1,//1表示成功,0表示失败 "errorInfo":"用户没有权限查看",//status为0时,前端展示errorinfo "data":{ "userName":"用户一", "description":"巴拉巴拉", "userTeam":"用户组一", "roleTeam":"角色组一" } }"""
def entry(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetOneUser:
"""查看一个用户的基本信息,前端发来的信息为: "userId":"admin", "userName":"用户一", 本函数接收该信息,判断userId用户是否拥有查看权限,并按查询结果返回: { "status":1,//1表示成功,0表示失败 "errorInfo":"用户没有权限查看",//status为0时,前端展示errorinfo "data":{ "userName":"用户一", "description":"巴拉巴拉", "userTeam":"用户组一", "roleTeam":"角色组一" } }"""
def entry(self, response_... | the_stack_v2_python_sparse | tornado/system/get_one_user.py | fxrc/care-system | train | 1 |
79dc669b800405f49eac753ec6022d673168ebc8 | [
"super(ComputeAnomalySubtask, self).__init__(config=parentTask.config, taskName=parentTask.taskName, componentName='ocean', tags=parentTask.tags, subtaskName=subtaskName)\nself.mpasTimeSeriesTask = mpasTimeSeriesTask\nself.run_after(mpasTimeSeriesTask)\nself.outFileName = outFileName\nself.variableList = variableLi... | <|body_start_0|>
super(ComputeAnomalySubtask, self).__init__(config=parentTask.config, taskName=parentTask.taskName, componentName='ocean', tags=parentTask.tags, subtaskName=subtaskName)
self.mpasTimeSeriesTask = mpasTimeSeriesTask
self.run_after(mpasTimeSeriesTask)
self.outFileName = ou... | A subtask for computing anomalies of moving averages and writing them out. Attributes ---------- mpasTimeSeriesTask : ``MpasTimeSeriesTask`` The task that extracts the time series from MPAS monthly output outFileName : str The file name (usually without full path) where the resulting data set should be written variable... | ComputeAnomalySubtask | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComputeAnomalySubtask:
"""A subtask for computing anomalies of moving averages and writing them out. Attributes ---------- mpasTimeSeriesTask : ``MpasTimeSeriesTask`` The task that extracts the time series from MPAS monthly output outFileName : str The file name (usually without full path) where ... | stack_v2_sparse_classes_36k_train_033227 | 5,592 | no_license | [
{
"docstring": "Construct the analysis task. Parameters ---------- parentTask : ``AnalysisTask`` The parent task of which this is a subtask mpasTimeSeriesTask : ``MpasTimeSeriesTask`` The task that extracts the time series from MPAS monthly output outFileName : str The file name (usually without full path) wher... | 3 | null | Implement the Python class `ComputeAnomalySubtask` described below.
Class description:
A subtask for computing anomalies of moving averages and writing them out. Attributes ---------- mpasTimeSeriesTask : ``MpasTimeSeriesTask`` The task that extracts the time series from MPAS monthly output outFileName : str The file ... | Implement the Python class `ComputeAnomalySubtask` described below.
Class description:
A subtask for computing anomalies of moving averages and writing them out. Attributes ---------- mpasTimeSeriesTask : ``MpasTimeSeriesTask`` The task that extracts the time series from MPAS monthly output outFileName : str The file ... | e56da52b9885a79c051e2f0f7c2619e14caf8a21 | <|skeleton|>
class ComputeAnomalySubtask:
"""A subtask for computing anomalies of moving averages and writing them out. Attributes ---------- mpasTimeSeriesTask : ``MpasTimeSeriesTask`` The task that extracts the time series from MPAS monthly output outFileName : str The file name (usually without full path) where ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ComputeAnomalySubtask:
"""A subtask for computing anomalies of moving averages and writing them out. Attributes ---------- mpasTimeSeriesTask : ``MpasTimeSeriesTask`` The task that extracts the time series from MPAS monthly output outFileName : str The file name (usually without full path) where the resulting... | the_stack_v2_python_sparse | mpas_analysis/ocean/compute_anomaly_subtask.py | zengxiaoqing/MPAS-Analysis | train | 0 |
88000392ff7ed945a764d5d379e590379727bad8 | [
"super().__init__()\nself.unified_encoder = unified_encoder\nself.mlp_non_seq_cat_list = mlp_non_seq_cat_list\nself.mlp_non_seq_cont = mlp_non_seq_cont\nself.decoder = decoder",
"encoder_out, (hn, cn) = self.unified_encoder(*args)\ndevice = hn.device\nnon_sequential_cont_decoded = self.mlp_non_seq_cont(hn)\nnon_s... | <|body_start_0|>
super().__init__()
self.unified_encoder = unified_encoder
self.mlp_non_seq_cat_list = mlp_non_seq_cat_list
self.mlp_non_seq_cont = mlp_non_seq_cont
self.decoder = decoder
<|end_body_0|>
<|body_start_1|>
encoder_out, (hn, cn) = self.unified_encoder(*args)... | Implementation of an autoencoder with multiple criterion. Args: unified_encoder (nn.Module): # noqa: W0223 Object of the unified_encoder class mlp_non_seq_cat_list (list of nn.module): List of linear layers with non-linear activation funtions mlp_non_seq_cont (nn.Module): # noqa: W0223 linear layers with non-linear act... | LSTMAutoencoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LSTMAutoencoder:
"""Implementation of an autoencoder with multiple criterion. Args: unified_encoder (nn.Module): # noqa: W0223 Object of the unified_encoder class mlp_non_seq_cat_list (list of nn.module): List of linear layers with non-linear activation funtions mlp_non_seq_cont (nn.Module): # no... | stack_v2_sparse_classes_36k_train_033228 | 15,906 | permissive | [
{
"docstring": "Initialize model with params.",
"name": "__init__",
"signature": "def __init__(self, unified_encoder, mlp_non_seq_cat_list, mlp_non_seq_cont, decoder)"
},
{
"docstring": "Run a forward pass of model over the data.",
"name": "forward",
"signature": "def forward(self, *args... | 3 | stack_v2_sparse_classes_30k_train_011519 | Implement the Python class `LSTMAutoencoder` described below.
Class description:
Implementation of an autoencoder with multiple criterion. Args: unified_encoder (nn.Module): # noqa: W0223 Object of the unified_encoder class mlp_non_seq_cat_list (list of nn.module): List of linear layers with non-linear activation funt... | Implement the Python class `LSTMAutoencoder` described below.
Class description:
Implementation of an autoencoder with multiple criterion. Args: unified_encoder (nn.Module): # noqa: W0223 Object of the unified_encoder class mlp_non_seq_cat_list (list of nn.module): List of linear layers with non-linear activation funt... | 9cdbf270487751a0ad6862b2fea2ccc0e23a0b67 | <|skeleton|>
class LSTMAutoencoder:
"""Implementation of an autoencoder with multiple criterion. Args: unified_encoder (nn.Module): # noqa: W0223 Object of the unified_encoder class mlp_non_seq_cat_list (list of nn.module): List of linear layers with non-linear activation funtions mlp_non_seq_cont (nn.Module): # no... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LSTMAutoencoder:
"""Implementation of an autoencoder with multiple criterion. Args: unified_encoder (nn.Module): # noqa: W0223 Object of the unified_encoder class mlp_non_seq_cat_list (list of nn.module): List of linear layers with non-linear activation funtions mlp_non_seq_cont (nn.Module): # noqa: W0223 lin... | the_stack_v2_python_sparse | caspr/models/model_wrapper.py | microsoft/CASPR | train | 29 |
8b9d2ddf9b8fd4f964a1efb0e006efcefa4de2f6 | [
"self.radius = size\nself.wiggle = raysize\nself.n = rays\nself.point = None",
"if self.point is not None:\n x, y = self.point.getXY()\n return pyx.box.polygon([(x - (self.radius - self.wiggle * (i % 2)) * math.sin(i * math.pi / self.n), y + (self.radius - self.wiggle * (i % 2)) * math.cos(i * math.pi / sel... | <|body_start_0|>
self.radius = size
self.wiggle = raysize
self.n = rays
self.point = None
<|end_body_0|>
<|body_start_1|>
if self.point is not None:
x, y = self.point.getXY()
return pyx.box.polygon([(x - (self.radius - self.wiggle * (i % 2)) * math.sin(i ... | StarshapeMark | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StarshapeMark:
def __init__(self, size=0.075, raysize=0.05, rays=3):
"""A star-shaped mark."""
<|body_0|>
def getPath(self):
"""Return the path for this marker."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.radius = size
self.wiggle =... | stack_v2_sparse_classes_36k_train_033229 | 12,026 | no_license | [
{
"docstring": "A star-shaped mark.",
"name": "__init__",
"signature": "def __init__(self, size=0.075, raysize=0.05, rays=3)"
},
{
"docstring": "Return the path for this marker.",
"name": "getPath",
"signature": "def getPath(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007132 | Implement the Python class `StarshapeMark` described below.
Class description:
Implement the StarshapeMark class.
Method signatures and docstrings:
- def __init__(self, size=0.075, raysize=0.05, rays=3): A star-shaped mark.
- def getPath(self): Return the path for this marker. | Implement the Python class `StarshapeMark` described below.
Class description:
Implement the StarshapeMark class.
Method signatures and docstrings:
- def __init__(self, size=0.075, raysize=0.05, rays=3): A star-shaped mark.
- def getPath(self): Return the path for this marker.
<|skeleton|>
class StarshapeMark:
... | 62f64e33d900280b26a6de5bbd9ee86c38c69cd0 | <|skeleton|>
class StarshapeMark:
def __init__(self, size=0.075, raysize=0.05, rays=3):
"""A star-shaped mark."""
<|body_0|>
def getPath(self):
"""Return the path for this marker."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StarshapeMark:
def __init__(self, size=0.075, raysize=0.05, rays=3):
"""A star-shaped mark."""
self.radius = size
self.wiggle = raysize
self.n = rays
self.point = None
def getPath(self):
"""Return the path for this marker."""
if self.point is not No... | the_stack_v2_python_sparse | pyfeyn/points.py | kpedro88/pyfeyn | train | 0 | |
e69a253017953ed1d8f8f62ad2bb5d04f8c3b6e5 | [
"annotationjob_interface = AnnotationJobsInterface(session)\njob = annotationjob_interface.patch(id, status=data.get('status'), message=data.get('message'), task_id=data.get('task_id'))\nsession.commit()\nreturn (schemas.AnnotationJobSchema().dump(job).data, 200)",
"job = session.query(annotationjob.AnnotationJob... | <|body_start_0|>
annotationjob_interface = AnnotationJobsInterface(session)
job = annotationjob_interface.patch(id, status=data.get('status'), message=data.get('message'), task_id=data.get('task_id'))
session.commit()
return (schemas.AnnotationJobSchema().dump(job).data, 200)
<|end_body_... | AnnotationJob | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnnotationJob:
def patch(self, session, id, data=None, user=None):
"""Updates an annotation job in the system. --- summary: Update annotation job tags: - Import"""
<|body_0|>
def delete(self, session, id):
"""Removes an annotation job in the system. --- summary: Remo... | stack_v2_sparse_classes_36k_train_033230 | 3,720 | permissive | [
{
"docstring": "Updates an annotation job in the system. --- summary: Update annotation job tags: - Import",
"name": "patch",
"signature": "def patch(self, session, id, data=None, user=None)"
},
{
"docstring": "Removes an annotation job in the system. --- summary: Remove annotation job tags: - I... | 2 | null | Implement the Python class `AnnotationJob` described below.
Class description:
Implement the AnnotationJob class.
Method signatures and docstrings:
- def patch(self, session, id, data=None, user=None): Updates an annotation job in the system. --- summary: Update annotation job tags: - Import
- def delete(self, sessio... | Implement the Python class `AnnotationJob` described below.
Class description:
Implement the AnnotationJob class.
Method signatures and docstrings:
- def patch(self, session, id, data=None, user=None): Updates an annotation job in the system. --- summary: Update annotation job tags: - Import
- def delete(self, sessio... | e38631d302611a143c9baaa684bcbd014d9734e4 | <|skeleton|>
class AnnotationJob:
def patch(self, session, id, data=None, user=None):
"""Updates an annotation job in the system. --- summary: Update annotation job tags: - Import"""
<|body_0|>
def delete(self, session, id):
"""Removes an annotation job in the system. --- summary: Remo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnnotationJob:
def patch(self, session, id, data=None, user=None):
"""Updates an annotation job in the system. --- summary: Update annotation job tags: - Import"""
annotationjob_interface = AnnotationJobsInterface(session)
job = annotationjob_interface.patch(id, status=data.get('status... | the_stack_v2_python_sparse | src/api/v1/resources/annotationjob.py | dabble-of-devops-consulting/ella | train | 0 | |
4eb2547610c4c276c18ce6cfe18ca135b47fcbcb | [
"dxf = super(DXFGraphic, self).load_dxf_attribs(processor)\nif processor:\n processor.simple_dxfattribs_loader(dxf, merged_shape_group_codes)\n if processor.r12:\n elevation_to_z_axis(dxf, ('center',))\nreturn dxf",
"super().export_entity(tagwriter)\nif tagwriter.dxfversion > DXF12:\n tagwriter.wr... | <|body_start_0|>
dxf = super(DXFGraphic, self).load_dxf_attribs(processor)
if processor:
processor.simple_dxfattribs_loader(dxf, merged_shape_group_codes)
if processor.r12:
elevation_to_z_axis(dxf, ('center',))
return dxf
<|end_body_0|>
<|body_start_1|>
... | DXF SHAPE entity | Shape | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Shape:
"""DXF SHAPE entity"""
def load_dxf_attribs(self, processor: Optional[SubclassProcessor]=None) -> DXFNamespace:
"""Loading interface. (internal API)"""
<|body_0|>
def export_entity(self, tagwriter: AbstractTagWriter) -> None:
"""Export entity specific data... | stack_v2_sparse_classes_36k_train_033231 | 4,684 | permissive | [
{
"docstring": "Loading interface. (internal API)",
"name": "load_dxf_attribs",
"signature": "def load_dxf_attribs(self, processor: Optional[SubclassProcessor]=None) -> DXFNamespace"
},
{
"docstring": "Export entity specific data as DXF tags.",
"name": "export_entity",
"signature": "def ... | 3 | stack_v2_sparse_classes_30k_train_020019 | Implement the Python class `Shape` described below.
Class description:
DXF SHAPE entity
Method signatures and docstrings:
- def load_dxf_attribs(self, processor: Optional[SubclassProcessor]=None) -> DXFNamespace: Loading interface. (internal API)
- def export_entity(self, tagwriter: AbstractTagWriter) -> None: Export... | Implement the Python class `Shape` described below.
Class description:
DXF SHAPE entity
Method signatures and docstrings:
- def load_dxf_attribs(self, processor: Optional[SubclassProcessor]=None) -> DXFNamespace: Loading interface. (internal API)
- def export_entity(self, tagwriter: AbstractTagWriter) -> None: Export... | ba6ab0264dcb6833173042a37b1b5ae878d75113 | <|skeleton|>
class Shape:
"""DXF SHAPE entity"""
def load_dxf_attribs(self, processor: Optional[SubclassProcessor]=None) -> DXFNamespace:
"""Loading interface. (internal API)"""
<|body_0|>
def export_entity(self, tagwriter: AbstractTagWriter) -> None:
"""Export entity specific data... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Shape:
"""DXF SHAPE entity"""
def load_dxf_attribs(self, processor: Optional[SubclassProcessor]=None) -> DXFNamespace:
"""Loading interface. (internal API)"""
dxf = super(DXFGraphic, self).load_dxf_attribs(processor)
if processor:
processor.simple_dxfattribs_loader(dxf... | the_stack_v2_python_sparse | src/ezdxf/entities/shape.py | mozman/ezdxf | train | 750 |
65ddfe564e8b2d39790d8a59ec1564e085a39334 | [
"self.ROWS = len(board)\nself.COLS = len(board[0])\nself.board = board\nfor row in range(self.ROWS):\n for col in range(self.COLS):\n if self.back_track(row, col, word):\n return True\nreturn False",
"if len(suffix) == 0:\n return True\nif row < 0 or row == self.ROWS or col < 0 or (col == ... | <|body_start_0|>
self.ROWS = len(board)
self.COLS = len(board[0])
self.board = board
for row in range(self.ROWS):
for col in range(self.COLS):
if self.back_track(row, col, word):
return True
return False
<|end_body_0|>
<|body_start... | WordSearch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordSearch:
def exist(self, board: List[List[str]], word: str) -> bool:
"""Approach: Back Tracking N - length of the grid L - Number of letters in the word Time Complexity: O(N * 3^L) Space Complexity: O(L) :param board: :param word: :return:"""
<|body_0|>
def back_track(sel... | stack_v2_sparse_classes_36k_train_033232 | 1,985 | no_license | [
{
"docstring": "Approach: Back Tracking N - length of the grid L - Number of letters in the word Time Complexity: O(N * 3^L) Space Complexity: O(L) :param board: :param word: :return:",
"name": "exist",
"signature": "def exist(self, board: List[List[str]], word: str) -> bool"
},
{
"docstring": "... | 2 | stack_v2_sparse_classes_30k_test_000616 | Implement the Python class `WordSearch` described below.
Class description:
Implement the WordSearch class.
Method signatures and docstrings:
- def exist(self, board: List[List[str]], word: str) -> bool: Approach: Back Tracking N - length of the grid L - Number of letters in the word Time Complexity: O(N * 3^L) Space... | Implement the Python class `WordSearch` described below.
Class description:
Implement the WordSearch class.
Method signatures and docstrings:
- def exist(self, board: List[List[str]], word: str) -> bool: Approach: Back Tracking N - length of the grid L - Number of letters in the word Time Complexity: O(N * 3^L) Space... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class WordSearch:
def exist(self, board: List[List[str]], word: str) -> bool:
"""Approach: Back Tracking N - length of the grid L - Number of letters in the word Time Complexity: O(N * 3^L) Space Complexity: O(L) :param board: :param word: :return:"""
<|body_0|>
def back_track(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordSearch:
def exist(self, board: List[List[str]], word: str) -> bool:
"""Approach: Back Tracking N - length of the grid L - Number of letters in the word Time Complexity: O(N * 3^L) Space Complexity: O(L) :param board: :param word: :return:"""
self.ROWS = len(board)
self.COLS = len(b... | the_stack_v2_python_sparse | expedia/word_search.py | Shiv2157k/leet_code | train | 1 | |
a57637e13030d2d006ca9a225a2765a675b9785e | [
"super().__init__()\nself.critic1 = SoftCriticNet(state_dim, action_spec, hidden_dims=hidden_dims)\nself.critic2 = SoftCriticNet(state_dim, action_spec, hidden_dims=hidden_dims)",
"q1 = self.critic1(states, actions)\nq2 = self.critic2(states, actions)\nreturn (q1, q2)"
] | <|body_start_0|>
super().__init__()
self.critic1 = SoftCriticNet(state_dim, action_spec, hidden_dims=hidden_dims)
self.critic2 = SoftCriticNet(state_dim, action_spec, hidden_dims=hidden_dims)
<|end_body_0|>
<|body_start_1|>
q1 = self.critic1(states, actions)
q2 = self.critic2(st... | A critic network that estimates a dual Q-function. | SoftCritic | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SoftCritic:
"""A critic network that estimates a dual Q-function."""
def __init__(self, state_dim, action_spec, hidden_dims=(256, 256)):
"""Creates networks. Args: state_dim: State size. action_spec: Action specification. hidden_dims: List of hidden dimensions."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_033233 | 10,984 | permissive | [
{
"docstring": "Creates networks. Args: state_dim: State size. action_spec: Action specification. hidden_dims: List of hidden dimensions.",
"name": "__init__",
"signature": "def __init__(self, state_dim, action_spec, hidden_dims=(256, 256))"
},
{
"docstring": "Returns Q-value estimates for given... | 2 | null | Implement the Python class `SoftCritic` described below.
Class description:
A critic network that estimates a dual Q-function.
Method signatures and docstrings:
- def __init__(self, state_dim, action_spec, hidden_dims=(256, 256)): Creates networks. Args: state_dim: State size. action_spec: Action specification. hidde... | Implement the Python class `SoftCritic` described below.
Class description:
A critic network that estimates a dual Q-function.
Method signatures and docstrings:
- def __init__(self, state_dim, action_spec, hidden_dims=(256, 256)): Creates networks. Args: state_dim: State size. action_spec: Action specification. hidde... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class SoftCritic:
"""A critic network that estimates a dual Q-function."""
def __init__(self, state_dim, action_spec, hidden_dims=(256, 256)):
"""Creates networks. Args: state_dim: State size. action_spec: Action specification. hidden_dims: List of hidden dimensions."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SoftCritic:
"""A critic network that estimates a dual Q-function."""
def __init__(self, state_dim, action_spec, hidden_dims=(256, 256)):
"""Creates networks. Args: state_dim: State size. action_spec: Action specification. hidden_dims: List of hidden dimensions."""
super().__init__()
... | the_stack_v2_python_sparse | rl_repr/batch_rl/critic.py | Jimmy-INL/google-research | train | 1 |
734f5992c1cd1a09d4f64caaef513aabc9e0b32b | [
"self = object.__new__(cls)\nself._exception = None\nself._future = None\nself._finished = False\nself._message = message\nself._check = check\nself._timeouter = None\nself._queue = None\nself.timeout = timeout\nself.count = count\nif timeout is not None:\n self._timeouter = Timeouter(self, timeout)\nclient.slas... | <|body_start_0|>
self = object.__new__(cls)
self._exception = None
self._future = None
self._finished = False
self._message = message
self._check = check
self._timeouter = None
self._queue = None
self.timeout = timeout
self.count = count
... | Component interaction iterator which goes brr. Parameters ---------- _check : `None`, `callable` The check to call to validate whether the response is sufficient. _exception : `None`, ``BaseException`` Whether the waiter finished with an exception. _finished : `bool` Whether the interaction iterator is finished. _futur... | ComponentInteractionIterator | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComponentInteractionIterator:
"""Component interaction iterator which goes brr. Parameters ---------- _check : `None`, `callable` The check to call to validate whether the response is sufficient. _exception : `None`, ``BaseException`` Whether the waiter finished with an exception. _finished : `bo... | stack_v2_sparse_classes_36k_train_033234 | 20,084 | permissive | [
{
"docstring": "Creates a new ``ComponentInteractionWaiter`` with the given parameters. Parameters ---------- client : ``Client`` The client who will wait for component interaction. message : ``Message`` The waited interaction component's message. check : `None`, `callable` The check to call to validate whether... | 5 | null | Implement the Python class `ComponentInteractionIterator` described below.
Class description:
Component interaction iterator which goes brr. Parameters ---------- _check : `None`, `callable` The check to call to validate whether the response is sufficient. _exception : `None`, ``BaseException`` Whether the waiter fini... | Implement the Python class `ComponentInteractionIterator` described below.
Class description:
Component interaction iterator which goes brr. Parameters ---------- _check : `None`, `callable` The check to call to validate whether the response is sufficient. _exception : `None`, ``BaseException`` Whether the waiter fini... | 53f24fdb38459dc5a4fd04f11bdbfee8295b76a4 | <|skeleton|>
class ComponentInteractionIterator:
"""Component interaction iterator which goes brr. Parameters ---------- _check : `None`, `callable` The check to call to validate whether the response is sufficient. _exception : `None`, ``BaseException`` Whether the waiter finished with an exception. _finished : `bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ComponentInteractionIterator:
"""Component interaction iterator which goes brr. Parameters ---------- _check : `None`, `callable` The check to call to validate whether the response is sufficient. _exception : `None`, ``BaseException`` Whether the waiter finished with an exception. _finished : `bool` Whether t... | the_stack_v2_python_sparse | hata/ext/slash/waiters.py | HuyaneMatsu/hata | train | 3 |
2cd1d2eb857b11ea1fc9524154aad3b0d2bd6147 | [
"ints = getattr(self, '_InterfaceMixin__interfaces', [])\nif interface is None:\n return ints\nreturn interface in ints",
"if not hasattr(self, '_InterfaceMixin__interfaces'):\n self.__interfaces = []\nif name not in self.__interfaces:\n self.__interfaces.append(name)"
] | <|body_start_0|>
ints = getattr(self, '_InterfaceMixin__interfaces', [])
if interface is None:
return ints
return interface in ints
<|end_body_0|>
<|body_start_1|>
if not hasattr(self, '_InterfaceMixin__interfaces'):
self.__interfaces = []
if name not in ... | Mixin class used to allow objects to declare which APIs they implement. Use addInterface() to declare a supported API:: class MyObject(InterfaceMixin): def __init__(self): self.addInterface("my_api") Use implements() to determine whether an object supports an API: if hasattr(obj, 'implements') and obj.implements('my_ap... | InterfaceMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterfaceMixin:
"""Mixin class used to allow objects to declare which APIs they implement. Use addInterface() to declare a supported API:: class MyObject(InterfaceMixin): def __init__(self): self.addInterface("my_api") Use implements() to determine whether an object supports an API: if hasattr(ob... | stack_v2_sparse_classes_36k_train_033235 | 5,066 | permissive | [
{
"docstring": "Return True if this device implements the specified API. If no API name is given, then return the list of APIs implemented by this device.",
"name": "implements",
"signature": "def implements(self, interface=None)"
},
{
"docstring": "Declare that this device implements a particul... | 2 | null | Implement the Python class `InterfaceMixin` described below.
Class description:
Mixin class used to allow objects to declare which APIs they implement. Use addInterface() to declare a supported API:: class MyObject(InterfaceMixin): def __init__(self): self.addInterface("my_api") Use implements() to determine whether a... | Implement the Python class `InterfaceMixin` described below.
Class description:
Mixin class used to allow objects to declare which APIs they implement. Use addInterface() to declare a supported API:: class MyObject(InterfaceMixin): def __init__(self): self.addInterface("my_api") Use implements() to determine whether a... | e5ffd699549df96d6ac32a7fe4fe5869e0dcb2af | <|skeleton|>
class InterfaceMixin:
"""Mixin class used to allow objects to declare which APIs they implement. Use addInterface() to declare a supported API:: class MyObject(InterfaceMixin): def __init__(self): self.addInterface("my_api") Use implements() to determine whether an object supports an API: if hasattr(ob... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InterfaceMixin:
"""Mixin class used to allow objects to declare which APIs they implement. Use addInterface() to declare a supported API:: class MyObject(InterfaceMixin): def __init__(self): self.addInterface("my_api") Use implements() to determine whether an object supports an API: if hasattr(obj, 'implement... | the_stack_v2_python_sparse | acq4/Interfaces.py | acq4/acq4 | train | 57 |
91c97ce7766e396254f0aa336e7154f161a748dc | [
"headers = {}\nif create_update_metadata:\n for key in create_update_metadata:\n metadata_header_name = create_update_metadata_prefix + key\n headers[metadata_header_name] = create_update_metadata[key]\nif delete_metadata:\n for key in delete_metadata:\n headers[delete_metadata_prefix + k... | <|body_start_0|>
headers = {}
if create_update_metadata:
for key in create_update_metadata:
metadata_header_name = create_update_metadata_prefix + key
headers[metadata_header_name] = create_update_metadata[key]
if delete_metadata:
for key i... | AccountClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountClient:
def create_update_or_delete_account_metadata(self, create_update_metadata=None, delete_metadata=None, create_update_metadata_prefix='X-Account-Meta-', delete_metadata_prefix='X-Remove-Account-Meta-'):
"""Creates, Updates or deletes an account metadata entry. Account Metada... | stack_v2_sparse_classes_36k_train_033236 | 3,052 | permissive | [
{
"docstring": "Creates, Updates or deletes an account metadata entry. Account Metadata can be created, updated or deleted based on metadata header or value. For detailed info, please refer to the official API reference: https://docs.openstack.org/api-ref/object-store/#create-update-or-delete-account-metadata",... | 3 | stack_v2_sparse_classes_30k_val_000040 | Implement the Python class `AccountClient` described below.
Class description:
Implement the AccountClient class.
Method signatures and docstrings:
- def create_update_or_delete_account_metadata(self, create_update_metadata=None, delete_metadata=None, create_update_metadata_prefix='X-Account-Meta-', delete_metadata_p... | Implement the Python class `AccountClient` described below.
Class description:
Implement the AccountClient class.
Method signatures and docstrings:
- def create_update_or_delete_account_metadata(self, create_update_metadata=None, delete_metadata=None, create_update_metadata_prefix='X-Account-Meta-', delete_metadata_p... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class AccountClient:
def create_update_or_delete_account_metadata(self, create_update_metadata=None, delete_metadata=None, create_update_metadata_prefix='X-Account-Meta-', delete_metadata_prefix='X-Remove-Account-Meta-'):
"""Creates, Updates or deletes an account metadata entry. Account Metada... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccountClient:
def create_update_or_delete_account_metadata(self, create_update_metadata=None, delete_metadata=None, create_update_metadata_prefix='X-Account-Meta-', delete_metadata_prefix='X-Remove-Account-Meta-'):
"""Creates, Updates or deletes an account metadata entry. Account Metadata can be crea... | the_stack_v2_python_sparse | tempest/lib/services/object_storage/account_client.py | openstack/tempest | train | 270 | |
d2289870702674fa2206b2e58e1cc745c0ce08a1 | [
"qid = len([name for name in os.listdir(TweetCorpus.CORPUS_ROUTE)])\nif qid > 0:\n rdata, rtest = self.read_corpus()\n rdata = rdata + rtest\n user_dict = set([str(tweet['id']) for tweet in rdata]).union(set([str(tweet['user']) for tweet in rdata]))\nelse:\n user_dict = set()\nfor k in self.keywords:\n ... | <|body_start_0|>
qid = len([name for name in os.listdir(TweetCorpus.CORPUS_ROUTE)])
if qid > 0:
rdata, rtest = self.read_corpus()
rdata = rdata + rtest
user_dict = set([str(tweet['id']) for tweet in rdata]).union(set([str(tweet['user']) for tweet in rdata]))
e... | TweetCorpus | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TweetCorpus:
def create_corpus(self):
"""Generates a Tweepy corpus, saving it in CORPUS_ROUTE"""
<|body_0|>
def __init__(self, reload: bool, add_more=True, n_tweets=500, keywords_filter=None):
"""This constructor makes a new corpus Args: reload (bool): Put this to tr... | stack_v2_sparse_classes_36k_train_033237 | 8,102 | permissive | [
{
"docstring": "Generates a Tweepy corpus, saving it in CORPUS_ROUTE",
"name": "create_corpus",
"signature": "def create_corpus(self)"
},
{
"docstring": "This constructor makes a new corpus Args: reload (bool): Put this to true to override the previous corpus with new data n_tweets (int, optiona... | 4 | stack_v2_sparse_classes_30k_train_008801 | Implement the Python class `TweetCorpus` described below.
Class description:
Implement the TweetCorpus class.
Method signatures and docstrings:
- def create_corpus(self): Generates a Tweepy corpus, saving it in CORPUS_ROUTE
- def __init__(self, reload: bool, add_more=True, n_tweets=500, keywords_filter=None): This co... | Implement the Python class `TweetCorpus` described below.
Class description:
Implement the TweetCorpus class.
Method signatures and docstrings:
- def create_corpus(self): Generates a Tweepy corpus, saving it in CORPUS_ROUTE
- def __init__(self, reload: bool, add_more=True, n_tweets=500, keywords_filter=None): This co... | 999cf06a2b75810f1711852fa94a27e7ff9d4620 | <|skeleton|>
class TweetCorpus:
def create_corpus(self):
"""Generates a Tweepy corpus, saving it in CORPUS_ROUTE"""
<|body_0|>
def __init__(self, reload: bool, add_more=True, n_tweets=500, keywords_filter=None):
"""This constructor makes a new corpus Args: reload (bool): Put this to tr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TweetCorpus:
def create_corpus(self):
"""Generates a Tweepy corpus, saving it in CORPUS_ROUTE"""
qid = len([name for name in os.listdir(TweetCorpus.CORPUS_ROUTE)])
if qid > 0:
rdata, rtest = self.read_corpus()
rdata = rdata + rtest
user_dict = set([s... | the_stack_v2_python_sparse | src/corpus_manager.py | andresh26-uam/political_role_extractionTDT4310 | train | 0 | |
c5c0111bbd97010873a7726c6de103ab3282c9fc | [
"def encode(root):\n val = []\n if not root:\n val.append('None')\n else:\n val.append(str(root.val))\n val.extend(encode(root.left))\n val.extend(encode(root.right))\n return val\nreturn ' '.join(encode(root))",
"def decode():\n node = data.popleft()\n if node == 'No... | <|body_start_0|>
def encode(root):
val = []
if not root:
val.append('None')
else:
val.append(str(root.val))
val.extend(encode(root.left))
val.extend(encode(root.right))
return val
return ' '.j... | Codec | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_033238 | 2,439 | permissive | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_test_000665 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 93936aeeef64487285db360b5884e844e0662b8e | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def encode(root):
val = []
if not root:
val.append('None')
else:
val.append(str(root.val))
val.extend(... | the_stack_v2_python_sparse | amazon/python/serialize_deserialize_binary_search_tree_449.py | Xiaoyu-Xing/algorithms | train | 0 | |
55ede10b92f9b724637c40ed076a0f8eaf8d067c | [
"self = real_self.magic\nname_part_separator = ' '\nif lastname_first:\n name_part_separator = ', '\nauthors_string = self.formatted_authors_editorial()\nrezensent_string = get_formatted_names(u' / ', ' ', self.reviewAuthors, lastname_first=lastname_first)\nif rezensent_string:\n rezensent_string = '(%s)' % r... | <|body_start_0|>
self = real_self.magic
name_part_separator = ' '
if lastname_first:
name_part_separator = ', '
authors_string = self.formatted_authors_editorial()
rezensent_string = get_formatted_names(u' / ', ' ', self.reviewAuthors, lastname_first=lastname_first)
... | ReviewMonographNoMagic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReviewMonographNoMagic:
def getDecoratedTitle(real_self, lastname_first=False):
""">>> from mock import Mock >>> at_mock = Mock() >>> at_mock.customCitation = '' >>> at_mock.formatted_authors_editorial = lambda: "Patrick Gerken / Alexander Pilz" >>> at_mock.punctuated_title_and_subtitle ... | stack_v2_sparse_classes_36k_train_033239 | 15,700 | no_license | [
{
"docstring": ">>> from mock import Mock >>> at_mock = Mock() >>> at_mock.customCitation = '' >>> at_mock.formatted_authors_editorial = lambda: \"Patrick Gerken / Alexander Pilz\" >>> at_mock.punctuated_title_and_subtitle = \"Plone 4.0. Das Benutzerhandbuch\" >>> at_mock.reviewAuthors = [{'firstname' : 'Cillia... | 2 | null | Implement the Python class `ReviewMonographNoMagic` described below.
Class description:
Implement the ReviewMonographNoMagic class.
Method signatures and docstrings:
- def getDecoratedTitle(real_self, lastname_first=False): >>> from mock import Mock >>> at_mock = Mock() >>> at_mock.customCitation = '' >>> at_mock.for... | Implement the Python class `ReviewMonographNoMagic` described below.
Class description:
Implement the ReviewMonographNoMagic class.
Method signatures and docstrings:
- def getDecoratedTitle(real_self, lastname_first=False): >>> from mock import Mock >>> at_mock = Mock() >>> at_mock.customCitation = '' >>> at_mock.for... | acf6ca3c962bfcf50600739087973de3ba7ad124 | <|skeleton|>
class ReviewMonographNoMagic:
def getDecoratedTitle(real_self, lastname_first=False):
""">>> from mock import Mock >>> at_mock = Mock() >>> at_mock.customCitation = '' >>> at_mock.formatted_authors_editorial = lambda: "Patrick Gerken / Alexander Pilz" >>> at_mock.punctuated_title_and_subtitle ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReviewMonographNoMagic:
def getDecoratedTitle(real_self, lastname_first=False):
""">>> from mock import Mock >>> at_mock = Mock() >>> at_mock.customCitation = '' >>> at_mock.formatted_authors_editorial = lambda: "Patrick Gerken / Alexander Pilz" >>> at_mock.punctuated_title_and_subtitle = "Plone 4.0. ... | the_stack_v2_python_sparse | recensio/contenttypes/content/reviewmonograph.py | syslabcom/recensio.contenttypes | train | 0 | |
964585d49b57be43d4c28a36fb0ec7148be0dfbf | [
"user = request.user\ncompany = Company.objects.get(id=view.kwargs['company_pk'])\nrole = user.get_role_for_company(company)\nif view.action == 'list':\n return role.has_permission(RECEIVE_VACANCY)\nelif view.action == 'create' and user.is_activated_for_company(company):\n return role.has_permission(CREATE_VA... | <|body_start_0|>
user = request.user
company = Company.objects.get(id=view.kwargs['company_pk'])
role = user.get_role_for_company(company)
if view.action == 'list':
return role.has_permission(RECEIVE_VACANCY)
elif view.action == 'create' and user.is_activated_for_comp... | Permission class for VacancyViewSet. | VacancyPermission | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VacancyPermission:
"""Permission class for VacancyViewSet."""
def has_permission(self, request, view):
"""Return base entity permission."""
<|body_0|>
def has_object_permission(self, request, view, obj):
"""Return particular object permission."""
<|body_1... | stack_v2_sparse_classes_36k_train_033240 | 1,561 | no_license | [
{
"docstring": "Return base entity permission.",
"name": "has_permission",
"signature": "def has_permission(self, request, view)"
},
{
"docstring": "Return particular object permission.",
"name": "has_object_permission",
"signature": "def has_object_permission(self, request, view, obj)"
... | 2 | null | Implement the Python class `VacancyPermission` described below.
Class description:
Permission class for VacancyViewSet.
Method signatures and docstrings:
- def has_permission(self, request, view): Return base entity permission.
- def has_object_permission(self, request, view, obj): Return particular object permission... | Implement the Python class `VacancyPermission` described below.
Class description:
Permission class for VacancyViewSet.
Method signatures and docstrings:
- def has_permission(self, request, view): Return base entity permission.
- def has_object_permission(self, request, view, obj): Return particular object permission... | 252b0ebd77eefbcc945a0efc3068cc3421f46d5f | <|skeleton|>
class VacancyPermission:
"""Permission class for VacancyViewSet."""
def has_permission(self, request, view):
"""Return base entity permission."""
<|body_0|>
def has_object_permission(self, request, view, obj):
"""Return particular object permission."""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VacancyPermission:
"""Permission class for VacancyViewSet."""
def has_permission(self, request, view):
"""Return base entity permission."""
user = request.user
company = Company.objects.get(id=view.kwargs['company_pk'])
role = user.get_role_for_company(company)
if ... | the_stack_v2_python_sparse | app/vacancies/permissions.py | vsokoltsov/Interview360Server | train | 2 |
3787765c40e349748f7c34fd2247f31a3e33c505 | [
"self.queue = [None] * q_size\nself.head = 0\nself.tail = 0\nself.q_size = q_size",
"res = False\nif self.__size() == self.q_size - 1:\n print('Queue Full!')\nelse:\n self.queue[self.tail] = data\n self.tail = (self.tail + 1) % self.q_size\n res = True\nreturn res",
"data = False\nif self.__size() =... | <|body_start_0|>
self.queue = [None] * q_size
self.head = 0
self.tail = 0
self.q_size = q_size
<|end_body_0|>
<|body_start_1|>
res = False
if self.__size() == self.q_size - 1:
print('Queue Full!')
else:
self.queue[self.tail] = data
... | [implements a circular queue] | CQueue | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CQueue:
"""[implements a circular queue]"""
def __init__(self, q_size=32):
"""[Initializes the queue structure] Keyword Arguments: q_size {[Integer]} -- [the maximum size of the queue] (default: {32})"""
<|body_0|>
def enqueue(self, data):
"""[Insert an element i... | stack_v2_sparse_classes_36k_train_033241 | 4,027 | permissive | [
{
"docstring": "[Initializes the queue structure] Keyword Arguments: q_size {[Integer]} -- [the maximum size of the queue] (default: {32})",
"name": "__init__",
"signature": "def __init__(self, q_size=32)"
},
{
"docstring": "[Insert an element into the queue.] Decorators: synchro Synchronizes th... | 5 | stack_v2_sparse_classes_30k_train_014517 | Implement the Python class `CQueue` described below.
Class description:
[implements a circular queue]
Method signatures and docstrings:
- def __init__(self, q_size=32): [Initializes the queue structure] Keyword Arguments: q_size {[Integer]} -- [the maximum size of the queue] (default: {32})
- def enqueue(self, data):... | Implement the Python class `CQueue` described below.
Class description:
[implements a circular queue]
Method signatures and docstrings:
- def __init__(self, q_size=32): [Initializes the queue structure] Keyword Arguments: q_size {[Integer]} -- [the maximum size of the queue] (default: {32})
- def enqueue(self, data):... | 4a0029efab2fa15cdd26575f87d7fb02f570ac73 | <|skeleton|>
class CQueue:
"""[implements a circular queue]"""
def __init__(self, q_size=32):
"""[Initializes the queue structure] Keyword Arguments: q_size {[Integer]} -- [the maximum size of the queue] (default: {32})"""
<|body_0|>
def enqueue(self, data):
"""[Insert an element i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CQueue:
"""[implements a circular queue]"""
def __init__(self, q_size=32):
"""[Initializes the queue structure] Keyword Arguments: q_size {[Integer]} -- [the maximum size of the queue] (default: {32})"""
self.queue = [None] * q_size
self.head = 0
self.tail = 0
self... | the_stack_v2_python_sparse | data_structures/cqueue.py | devwarrior/python_coding | train | 0 |
753f5b230f4f020a079d35e99f32e32673ac2c21 | [
"entity = cls.__name__\nif not isinstance(properties, dict):\n raise TypeError(f'{str(entity)} properties {properties} are of type {type(properties)}, they should be a `dict`.')\nfor key, value in properties.items():\n if not isinstance(key, str):\n raise TypeError(f\"{str(entity)} property {key} : {va... | <|body_start_0|>
entity = cls.__name__
if not isinstance(properties, dict):
raise TypeError(f'{str(entity)} properties {properties} are of type {type(properties)}, they should be a `dict`.')
for key, value in properties.items():
if not isinstance(key, str):
... | The mixin for Container and Well entities used to mutate the entity instance ctx_properties and properties | EntityPropertiesMixin | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntityPropertiesMixin:
"""The mixin for Container and Well entities used to mutate the entity instance ctx_properties and properties"""
def validate_properties(cls, properties):
"""Validates that properties are valid"""
<|body_0|>
def fromDict(self, dict_: Dict):
... | stack_v2_sparse_classes_36k_train_033242 | 41,841 | permissive | [
{
"docstring": "Validates that properties are valid",
"name": "validate_properties",
"signature": "def validate_properties(cls, properties)"
},
{
"docstring": "Generates the EntityProperties mapping from a dictionary Parameters ---------- dict_ : dict Dictionary of properties to associate to a e... | 6 | stack_v2_sparse_classes_30k_train_016133 | Implement the Python class `EntityPropertiesMixin` described below.
Class description:
The mixin for Container and Well entities used to mutate the entity instance ctx_properties and properties
Method signatures and docstrings:
- def validate_properties(cls, properties): Validates that properties are valid
- def from... | Implement the Python class `EntityPropertiesMixin` described below.
Class description:
The mixin for Container and Well entities used to mutate the entity instance ctx_properties and properties
Method signatures and docstrings:
- def validate_properties(cls, properties): Validates that properties are valid
- def from... | 84f6d3fced521849657d21ae4cb9681f5897b957 | <|skeleton|>
class EntityPropertiesMixin:
"""The mixin for Container and Well entities used to mutate the entity instance ctx_properties and properties"""
def validate_properties(cls, properties):
"""Validates that properties are valid"""
<|body_0|>
def fromDict(self, dict_: Dict):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EntityPropertiesMixin:
"""The mixin for Container and Well entities used to mutate the entity instance ctx_properties and properties"""
def validate_properties(cls, properties):
"""Validates that properties are valid"""
entity = cls.__name__
if not isinstance(properties, dict):
... | the_stack_v2_python_sparse | venv/lib/python3.9/site-packages/autoprotocol/container.py | ClassWizard/PodLockParser | train | 2 |
06c04b422eee36009c6b9c7c408104f89dca00b3 | [
"if not ip4_prefix and (not ip6_prefix):\n raise ValueError('ip4 or ip6 must be provided')\nself.ip4 = None\nif ip4_prefix:\n self.ip4 = netaddr.IPNetwork(ip4_prefix)\nself.ip6 = None\nif ip6_prefix:\n self.ip6 = netaddr.IPNetwork(ip6_prefix)",
"if not self.ip4:\n raise ValueError('ip4 prefixes have n... | <|body_start_0|>
if not ip4_prefix and (not ip6_prefix):
raise ValueError('ip4 or ip6 must be provided')
self.ip4 = None
if ip4_prefix:
self.ip4 = netaddr.IPNetwork(ip4_prefix)
self.ip6 = None
if ip6_prefix:
self.ip6 = netaddr.IPNetwork(ip6_pre... | Convenience class to help generate IP4 and IP6 addresses for nodes within CORE. | IpPrefixes | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IpPrefixes:
"""Convenience class to help generate IP4 and IP6 addresses for nodes within CORE."""
def __init__(self, ip4_prefix: str=None, ip6_prefix: str=None) -> None:
"""Creates an IpPrefixes object. :param ip4_prefix: ip4 prefix to use for generation :param ip6_prefix: ip6 prefix... | stack_v2_sparse_classes_36k_train_033243 | 9,883 | permissive | [
{
"docstring": "Creates an IpPrefixes object. :param ip4_prefix: ip4 prefix to use for generation :param ip6_prefix: ip6 prefix to use for generation :raises ValueError: when both ip4 and ip6 prefixes have not been provided",
"name": "__init__",
"signature": "def __init__(self, ip4_prefix: str=None, ip6... | 5 | stack_v2_sparse_classes_30k_train_020526 | Implement the Python class `IpPrefixes` described below.
Class description:
Convenience class to help generate IP4 and IP6 addresses for nodes within CORE.
Method signatures and docstrings:
- def __init__(self, ip4_prefix: str=None, ip6_prefix: str=None) -> None: Creates an IpPrefixes object. :param ip4_prefix: ip4 p... | Implement the Python class `IpPrefixes` described below.
Class description:
Convenience class to help generate IP4 and IP6 addresses for nodes within CORE.
Method signatures and docstrings:
- def __init__(self, ip4_prefix: str=None, ip6_prefix: str=None) -> None: Creates an IpPrefixes object. :param ip4_prefix: ip4 p... | 20071eed2e73a2287aa385698dd604f4933ae7ff | <|skeleton|>
class IpPrefixes:
"""Convenience class to help generate IP4 and IP6 addresses for nodes within CORE."""
def __init__(self, ip4_prefix: str=None, ip6_prefix: str=None) -> None:
"""Creates an IpPrefixes object. :param ip4_prefix: ip4 prefix to use for generation :param ip6_prefix: ip6 prefix... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IpPrefixes:
"""Convenience class to help generate IP4 and IP6 addresses for nodes within CORE."""
def __init__(self, ip4_prefix: str=None, ip6_prefix: str=None) -> None:
"""Creates an IpPrefixes object. :param ip4_prefix: ip4 prefix to use for generation :param ip6_prefix: ip6 prefix to use for g... | the_stack_v2_python_sparse | daemon/core/emulator/data.py | coreemu/core | train | 606 |
85c11dac699aa07192c414452476308a76347796 | [
"if head is None:\n return None\nnew_head = self.reverseList(head.next)\nif new_head:\n tmp = new_head\n while tmp.next:\n tmp = tmp.next\n tmp.next = head\n head.next = None\nelse:\n new_head = head\nreturn new_head",
"if head is None or head.next is None:\n return head\np = self.reve... | <|body_start_0|>
if head is None:
return None
new_head = self.reverseList(head.next)
if new_head:
tmp = new_head
while tmp.next:
tmp = tmp.next
tmp.next = head
head.next = None
else:
new_head = head
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def reverseListV2(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
def reverseListV3(self, head):
""":type head: ListNode :rtype: Lis... | stack_v2_sparse_classes_36k_train_033244 | 1,364 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "reverseList",
"signature": "def reverseList(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "reverseListV2",
"signature": "def reverseListV2(self, head)"
},
{
"docstring": ":type head... | 3 | stack_v2_sparse_classes_30k_train_000316 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def reverseListV2(self, head): :type head: ListNode :rtype: ListNode
- def reverseListV3(self, head): :type h... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def reverseListV2(self, head): :type head: ListNode :rtype: ListNode
- def reverseListV3(self, head): :type h... | 266def94df8245f90ea5b6885fc472470b189e51 | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def reverseListV2(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
def reverseListV3(self, head):
""":type head: ListNode :rtype: Lis... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
if head is None:
return None
new_head = self.reverseList(head.next)
if new_head:
tmp = new_head
while tmp.next:
tmp = tmp.next
tmp.... | the_stack_v2_python_sparse | 206_Reverse_Linked_List.py | GuangyuZheng/leet_code_python | train | 2 | |
9d8cac394e870b1fe81e4412fb166cf5f24ccd1b | [
"outs = ()\nrois = rbbox2roi([proposals])\nif self.with_bbox:\n bbox_results = self._bbox_forward(x, rois)\n outs = outs + (bbox_results['cls_score'], bbox_results['bbox_pred'])\nreturn outs",
"if self.with_bbox:\n num_imgs = len(img_metas)\n if gt_bboxes_ignore is None:\n gt_bboxes_ignore = [N... | <|body_start_0|>
outs = ()
rois = rbbox2roi([proposals])
if self.with_bbox:
bbox_results = self._bbox_forward(x, rois)
outs = outs + (bbox_results['cls_score'], bbox_results['bbox_pred'])
return outs
<|end_body_0|>
<|body_start_1|>
if self.with_bbox:
... | Oriented RCNN roi head including one bbox head. | OrientedStandardRoIHead | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrientedStandardRoIHead:
"""Oriented RCNN roi head including one bbox head."""
def forward_dummy(self, x, proposals):
"""Dummy forward function. Args: x (list[Tensors]): list of multi-level img features. proposals (list[Tensors]): list of region proposals. Returns: list[Tensors]: lis... | stack_v2_sparse_classes_36k_train_033245 | 7,962 | permissive | [
{
"docstring": "Dummy forward function. Args: x (list[Tensors]): list of multi-level img features. proposals (list[Tensors]): list of region proposals. Returns: list[Tensors]: list of region of interest.",
"name": "forward_dummy",
"signature": "def forward_dummy(self, x, proposals)"
},
{
"docstr... | 4 | null | Implement the Python class `OrientedStandardRoIHead` described below.
Class description:
Oriented RCNN roi head including one bbox head.
Method signatures and docstrings:
- def forward_dummy(self, x, proposals): Dummy forward function. Args: x (list[Tensors]): list of multi-level img features. proposals (list[Tensors... | Implement the Python class `OrientedStandardRoIHead` described below.
Class description:
Oriented RCNN roi head including one bbox head.
Method signatures and docstrings:
- def forward_dummy(self, x, proposals): Dummy forward function. Args: x (list[Tensors]): list of multi-level img features. proposals (list[Tensors... | 9ea1aeeef2da8b2cd5161b72f4e33e1e8293dcb2 | <|skeleton|>
class OrientedStandardRoIHead:
"""Oriented RCNN roi head including one bbox head."""
def forward_dummy(self, x, proposals):
"""Dummy forward function. Args: x (list[Tensors]): list of multi-level img features. proposals (list[Tensors]): list of region proposals. Returns: list[Tensors]: lis... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OrientedStandardRoIHead:
"""Oriented RCNN roi head including one bbox head."""
def forward_dummy(self, x, proposals):
"""Dummy forward function. Args: x (list[Tensors]): list of multi-level img features. proposals (list[Tensors]): list of region proposals. Returns: list[Tensors]: list of region o... | the_stack_v2_python_sparse | mmrotate/models/roi_heads/oriented_standard_roi_head.py | open-mmlab/mmrotate | train | 1,473 |
99a5ff5ad3a28eaacfebd1e96fa0c50bddc9aec7 | [
"slow, fast = (head, head)\nwhile fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n if slow == fast:\n return True\nreturn False",
"node_list = list()\ncur = head\nwhile cur:\n if cur in node_list:\n return True\n node_list.append(cur)\n cur = cur.next\nreturn False"... | <|body_start_0|>
slow, fast = (head, head)
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
<|end_body_0|>
<|body_start_1|>
node_list = list()
cur = head
while c... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hasCycle(self, head):
""":type head: ListNode :rtype: bool"""
<|body_0|>
def hasCycle2(self, head):
""":type head: ListNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
slow, fast = (head, head)
while fast and f... | stack_v2_sparse_classes_36k_train_033246 | 1,672 | no_license | [
{
"docstring": ":type head: ListNode :rtype: bool",
"name": "hasCycle",
"signature": "def hasCycle(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: bool",
"name": "hasCycle2",
"signature": "def hasCycle2(self, head)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasCycle(self, head): :type head: ListNode :rtype: bool
- def hasCycle2(self, head): :type head: ListNode :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasCycle(self, head): :type head: ListNode :rtype: bool
- def hasCycle2(self, head): :type head: ListNode :rtype: bool
<|skeleton|>
class Solution:
def hasCycle(self, h... | 8987859c4c3faedf7159b5a6ec3155609689760e | <|skeleton|>
class Solution:
def hasCycle(self, head):
""":type head: ListNode :rtype: bool"""
<|body_0|>
def hasCycle2(self, head):
""":type head: ListNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def hasCycle(self, head):
""":type head: ListNode :rtype: bool"""
slow, fast = (head, head)
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
def hasCycle... | the_stack_v2_python_sparse | Python/Leetcodes/linked_list/141_Linked_List_Cycle.py | ccc013/DataStructe-Algorithms_Study | train | 15 | |
3e56e0bc6a88cfed99a3b9a024311f14daa90b10 | [
"super(Shrink_RDB, self).__init__()\nself.InChan = InChannel\nself.OutChan = OutChannel\nself.G = growRate\nself.C = nConvLayers\nif self.InChan != self.G:\n self.InConv = nn.Conv2d(self.InChan, self.G, 1, padding=0, stride=1)\nif self.OutChan != self.G and self.OutChan != self.InChan:\n self.OutConv = nn.Con... | <|body_start_0|>
super(Shrink_RDB, self).__init__()
self.InChan = InChannel
self.OutChan = OutChannel
self.G = growRate
self.C = nConvLayers
if self.InChan != self.G:
self.InConv = nn.Conv2d(self.InChan, self.G, 1, padding=0, stride=1)
if self.OutChan ... | Shrink residual dense block. | Shrink_RDB | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Shrink_RDB:
"""Shrink residual dense block."""
def __init__(self, InChannel, OutChannel, growRate, nConvLayers, kSize=3):
"""Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: channel number of output :type OutChannel: int :param growR... | stack_v2_sparse_classes_36k_train_033247 | 13,650 | permissive | [
{
"docstring": "Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: channel number of output :type OutChannel: int :param growRate: growth rate of block :type growRate: int :param nConvLayers: the number of convlution layer :type nConvLayers: int :param kSize: ker... | 2 | stack_v2_sparse_classes_30k_train_020731 | Implement the Python class `Shrink_RDB` described below.
Class description:
Shrink residual dense block.
Method signatures and docstrings:
- def __init__(self, InChannel, OutChannel, growRate, nConvLayers, kSize=3): Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: ch... | Implement the Python class `Shrink_RDB` described below.
Class description:
Shrink residual dense block.
Method signatures and docstrings:
- def __init__(self, InChannel, OutChannel, growRate, nConvLayers, kSize=3): Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: ch... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class Shrink_RDB:
"""Shrink residual dense block."""
def __init__(self, InChannel, OutChannel, growRate, nConvLayers, kSize=3):
"""Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: channel number of output :type OutChannel: int :param growR... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Shrink_RDB:
"""Shrink residual dense block."""
def __init__(self, InChannel, OutChannel, growRate, nConvLayers, kSize=3):
"""Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: channel number of output :type OutChannel: int :param growRate: growth r... | the_stack_v2_python_sparse | built-in/TensorFlow/Research/cv/image_classification/Darts_for_TensorFlow/automl/vega/search_space/networks/pytorch/esrbodys/erdb_esr.py | Huawei-Ascend/modelzoo | train | 1 |
18fbd2fd25c60e0dcfcf90fcab7a2a0d7434493b | [
"assert isspmatrix_csr(data)\nself.data = data\nself.entities = entities\nself.data_indices = None\nself.entity_indices = [None, None]",
"if self.data_indices is None:\n return self.data\nreturn self.data[self.data_indices]",
"idx = 0 if of == 'row' else 1\nif self.entity_indices[idx] is None:\n return se... | <|body_start_0|>
assert isspmatrix_csr(data)
self.data = data
self.entities = entities
self.data_indices = None
self.entity_indices = [None, None]
<|end_body_0|>
<|body_start_1|>
if self.data_indices is None:
return self.data
return self.data[self.dat... | Holds data and its respective indices | DataPtr | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataPtr:
"""Holds data and its respective indices"""
def __init__(self, data, entities):
"""Initialize a data pointer Args: data (csr_matrix): The target data matrix. entities (Iterator): An iterator (of 2 elements (ndarray)) containing the features of row, col entities."""
<... | stack_v2_sparse_classes_36k_train_033248 | 8,650 | permissive | [
{
"docstring": "Initialize a data pointer Args: data (csr_matrix): The target data matrix. entities (Iterator): An iterator (of 2 elements (ndarray)) containing the features of row, col entities.",
"name": "__init__",
"signature": "def __init__(self, data, entities)"
},
{
"docstring": "Returns: ... | 3 | stack_v2_sparse_classes_30k_test_000993 | Implement the Python class `DataPtr` described below.
Class description:
Holds data and its respective indices
Method signatures and docstrings:
- def __init__(self, data, entities): Initialize a data pointer Args: data (csr_matrix): The target data matrix. entities (Iterator): An iterator (of 2 elements (ndarray)) c... | Implement the Python class `DataPtr` described below.
Class description:
Holds data and its respective indices
Method signatures and docstrings:
- def __init__(self, data, entities): Initialize a data pointer Args: data (csr_matrix): The target data matrix. entities (Iterator): An iterator (of 2 elements (ndarray)) c... | 787ae309ec78a9b2b1f58931931cb117affc4ea9 | <|skeleton|>
class DataPtr:
"""Holds data and its respective indices"""
def __init__(self, data, entities):
"""Initialize a data pointer Args: data (csr_matrix): The target data matrix. entities (Iterator): An iterator (of 2 elements (ndarray)) containing the features of row, col entities."""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataPtr:
"""Holds data and its respective indices"""
def __init__(self, data, entities):
"""Initialize a data pointer Args: data (csr_matrix): The target data matrix. entities (Iterator): An iterator (of 2 elements (ndarray)) containing the features of row, col entities."""
assert isspmat... | the_stack_v2_python_sparse | recommenders/models/geoimc/geoimc_data.py | DaniBunny/recommenders | train | 1 |
468981121734cdde6d7848582369ab98f1ed04fd | [
"def wrapper(view_handler):\n self._add_op(op_name, section=section, fn=view_handler, **kw)\n return view_handler\nreturn wrapper",
"def wrapper(view_handler):\n self._add_page(op_name, section=section, fn=view_handler, **kw)\n return view_handler\nreturn wrapper",
"for name, obj in self.map.items()... | <|body_start_0|>
def wrapper(view_handler):
self._add_op(op_name, section=section, fn=view_handler, **kw)
return view_handler
return wrapper
<|end_body_0|>
<|body_start_1|>
def wrapper(view_handler):
self._add_page(op_name, section=section, fn=view_handler, *... | Subclass of Burla for integration with Pyramid. | PyramidBurla | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PyramidBurla:
"""Subclass of Burla for integration with Pyramid."""
def op(self, op_name: str, section='Miscellaneous', **kw):
"""Decorator to register an API operation. Decorate your view handlers with this to register an operation with Burla as well as with Pyramid."""
<|bo... | stack_v2_sparse_classes_36k_train_033249 | 5,034 | permissive | [
{
"docstring": "Decorator to register an API operation. Decorate your view handlers with this to register an operation with Burla as well as with Pyramid.",
"name": "op",
"signature": "def op(self, op_name: str, section='Miscellaneous', **kw)"
},
{
"docstring": "Decorator to register a page. Dec... | 3 | stack_v2_sparse_classes_30k_train_009987 | Implement the Python class `PyramidBurla` described below.
Class description:
Subclass of Burla for integration with Pyramid.
Method signatures and docstrings:
- def op(self, op_name: str, section='Miscellaneous', **kw): Decorator to register an API operation. Decorate your view handlers with this to register an oper... | Implement the Python class `PyramidBurla` described below.
Class description:
Subclass of Burla for integration with Pyramid.
Method signatures and docstrings:
- def op(self, op_name: str, section='Miscellaneous', **kw): Decorator to register an API operation. Decorate your view handlers with this to register an oper... | 63f6fbd3e768bf55d79ac96964aa3bf7702f3f9a | <|skeleton|>
class PyramidBurla:
"""Subclass of Burla for integration with Pyramid."""
def op(self, op_name: str, section='Miscellaneous', **kw):
"""Decorator to register an API operation. Decorate your view handlers with this to register an operation with Burla as well as with Pyramid."""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PyramidBurla:
"""Subclass of Burla for integration with Pyramid."""
def op(self, op_name: str, section='Miscellaneous', **kw):
"""Decorator to register an API operation. Decorate your view handlers with this to register an operation with Burla as well as with Pyramid."""
def wrapper(view_... | the_stack_v2_python_sparse | bag/web/pyramid/burla.py | nandoflorestan/bag | train | 24 |
4dc8b4ffd74e7820e31c62b863b4d643876ba8f5 | [
"assert scope in ('date', 'time', 'datetime')\nself._dtFormat = dtFormat\nself.srcLang = NAME_YAPPN_MAPPINGS[sourceLang]\nself.tgtLocale = targetLocale if targetLocale else re.sub('-', '_', CULTURE_CODES[targetLang][0])\nself._scope = scope\nself._fullmatch = fullmatch",
"dt = dateparser.parse(text)\nif dt:\n ... | <|body_start_0|>
assert scope in ('date', 'time', 'datetime')
self._dtFormat = dtFormat
self.srcLang = NAME_YAPPN_MAPPINGS[sourceLang]
self.tgtLocale = targetLocale if targetLocale else re.sub('-', '_', CULTURE_CODES[targetLang][0])
self._scope = scope
self._fullmatch = f... | Rule-based date/time translation using dateparser and Babel | DatetimeTranslator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatetimeTranslator:
"""Rule-based date/time translation using dateparser and Babel"""
def __init__(self, dtFormat, sourceLang, targetLang, targetLocale, scope, fullmatch=False):
"""Initialize a DatetimeTranslator instance Args: dtFormat (str): date/time format 'full', 'long', 'medium... | stack_v2_sparse_classes_36k_train_033250 | 21,856 | no_license | [
{
"docstring": "Initialize a DatetimeTranslator instance Args: dtFormat (str): date/time format 'full', 'long', 'medium', 'short', or a custom date/time pattern Refer to the Babel doc sourceLang (str): source language in full spelling, e.g., 'English' targetLang (str): target language in full spelling, e.g., 'F... | 3 | stack_v2_sparse_classes_30k_train_020032 | Implement the Python class `DatetimeTranslator` described below.
Class description:
Rule-based date/time translation using dateparser and Babel
Method signatures and docstrings:
- def __init__(self, dtFormat, sourceLang, targetLang, targetLocale, scope, fullmatch=False): Initialize a DatetimeTranslator instance Args:... | Implement the Python class `DatetimeTranslator` described below.
Class description:
Rule-based date/time translation using dateparser and Babel
Method signatures and docstrings:
- def __init__(self, dtFormat, sourceLang, targetLang, targetLocale, scope, fullmatch=False): Initialize a DatetimeTranslator instance Args:... | 3db60d54f076ea26d45cdbbe194d1cd357f8f1a3 | <|skeleton|>
class DatetimeTranslator:
"""Rule-based date/time translation using dateparser and Babel"""
def __init__(self, dtFormat, sourceLang, targetLang, targetLocale, scope, fullmatch=False):
"""Initialize a DatetimeTranslator instance Args: dtFormat (str): date/time format 'full', 'long', 'medium... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DatetimeTranslator:
"""Rule-based date/time translation using dateparser and Babel"""
def __init__(self, dtFormat, sourceLang, targetLang, targetLocale, scope, fullmatch=False):
"""Initialize a DatetimeTranslator instance Args: dtFormat (str): date/time format 'full', 'long', 'medium', 'short', o... | the_stack_v2_python_sparse | tb_utils/rules.py | EthannyDing/text_mining | train | 0 |
d8cd1b75cce7b03afbc0d6ad9782c27f1f2e1018 | [
"pre_head = LinkNode(-1)\nprev = pre_head\nwhile l1 and l2:\n if l1.val <= l2.val:\n prev.next = l1\n l1 = l1.next\n else:\n prev.next = l2\n l2 = l2.next\n prev = prev.next\nprev.next = l1 if l1 else l2\nreturn pre_head.next",
"if not l1:\n return l2\nelif not l2:\n ret... | <|body_start_0|>
pre_head = LinkNode(-1)
prev = pre_head
while l1 and l2:
if l1.val <= l2.val:
prev.next = l1
l1 = l1.next
else:
prev.next = l2
l2 = l2.next
prev = prev.next
prev.next = l1... | LinkedList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkedList:
def merge_(self, l1: 'LinkNode', l2: 'LinkNode'):
"""Approach: Iterative Time Complexity: Space Complexity: :param l1: :param l2: :return:"""
<|body_0|>
def merge(self, l1: 'LinkNode', l2: 'LinkNode'):
"""Approach: DFS Time Complexity: Space Complexity: :... | stack_v2_sparse_classes_36k_train_033251 | 1,594 | no_license | [
{
"docstring": "Approach: Iterative Time Complexity: Space Complexity: :param l1: :param l2: :return:",
"name": "merge_",
"signature": "def merge_(self, l1: 'LinkNode', l2: 'LinkNode')"
},
{
"docstring": "Approach: DFS Time Complexity: Space Complexity: :param l1: :param l2: :return:",
"name... | 2 | stack_v2_sparse_classes_30k_train_021518 | Implement the Python class `LinkedList` described below.
Class description:
Implement the LinkedList class.
Method signatures and docstrings:
- def merge_(self, l1: 'LinkNode', l2: 'LinkNode'): Approach: Iterative Time Complexity: Space Complexity: :param l1: :param l2: :return:
- def merge(self, l1: 'LinkNode', l2: ... | Implement the Python class `LinkedList` described below.
Class description:
Implement the LinkedList class.
Method signatures and docstrings:
- def merge_(self, l1: 'LinkNode', l2: 'LinkNode'): Approach: Iterative Time Complexity: Space Complexity: :param l1: :param l2: :return:
- def merge(self, l1: 'LinkNode', l2: ... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class LinkedList:
def merge_(self, l1: 'LinkNode', l2: 'LinkNode'):
"""Approach: Iterative Time Complexity: Space Complexity: :param l1: :param l2: :return:"""
<|body_0|>
def merge(self, l1: 'LinkNode', l2: 'LinkNode'):
"""Approach: DFS Time Complexity: Space Complexity: :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinkedList:
def merge_(self, l1: 'LinkNode', l2: 'LinkNode'):
"""Approach: Iterative Time Complexity: Space Complexity: :param l1: :param l2: :return:"""
pre_head = LinkNode(-1)
prev = pre_head
while l1 and l2:
if l1.val <= l2.val:
prev.next = l1
... | the_stack_v2_python_sparse | revisited__2021/linked_list/merge_two_sorted_list.py | Shiv2157k/leet_code | train | 1 | |
a783ef82d421c255cec6f0a3fd9218bd1b9f5503 | [
"self.aag_databases = aag_databases\nself.application_node = application_node\nself.databases = databases\nself.error_message = error_message\nself.unknown_host_name = unknown_host_name",
"if dictionary is None:\n return None\naag_databases = None\nif dictionary.get('aagDatabases') != None:\n aag_databases ... | <|body_start_0|>
self.aag_databases = aag_databases
self.application_node = application_node
self.databases = databases
self.error_message = error_message
self.unknown_host_name = unknown_host_name
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return... | Implementation of the 'SqlAagHostAndDatabases' model. Specifies AAGs and databases information on an SQL server. If AAGs exist on the server, specifies information about the AAG and databases in the group for each AAG found on the server. Attributes: aag_databases (list of AagAndDatabases): Specifies a list of AAGs and... | SqlAagHostAndDatabases | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SqlAagHostAndDatabases:
"""Implementation of the 'SqlAagHostAndDatabases' model. Specifies AAGs and databases information on an SQL server. If AAGs exist on the server, specifies information about the AAG and databases in the group for each AAG found on the server. Attributes: aag_databases (list... | stack_v2_sparse_classes_36k_train_033252 | 3,975 | permissive | [
{
"docstring": "Constructor for the SqlAagHostAndDatabases class",
"name": "__init__",
"signature": "def __init__(self, aag_databases=None, application_node=None, databases=None, error_message=None, unknown_host_name=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary A... | 2 | null | Implement the Python class `SqlAagHostAndDatabases` described below.
Class description:
Implementation of the 'SqlAagHostAndDatabases' model. Specifies AAGs and databases information on an SQL server. If AAGs exist on the server, specifies information about the AAG and databases in the group for each AAG found on the ... | Implement the Python class `SqlAagHostAndDatabases` described below.
Class description:
Implementation of the 'SqlAagHostAndDatabases' model. Specifies AAGs and databases information on an SQL server. If AAGs exist on the server, specifies information about the AAG and databases in the group for each AAG found on the ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class SqlAagHostAndDatabases:
"""Implementation of the 'SqlAagHostAndDatabases' model. Specifies AAGs and databases information on an SQL server. If AAGs exist on the server, specifies information about the AAG and databases in the group for each AAG found on the server. Attributes: aag_databases (list... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SqlAagHostAndDatabases:
"""Implementation of the 'SqlAagHostAndDatabases' model. Specifies AAGs and databases information on an SQL server. If AAGs exist on the server, specifies information about the AAG and databases in the group for each AAG found on the server. Attributes: aag_databases (list of AagAndDat... | the_stack_v2_python_sparse | cohesity_management_sdk/models/sql_aag_host_and_databases.py | cohesity/management-sdk-python | train | 24 |
3b39f3c879cbd63430ff7245031c96769f9e7fbd | [
"source = FileSource()\nsource.path = 'path/to/file.py'\nde = make_directory_entry('path/to', source)\nself.assertIsInstance(de, DirectoryListEntry)\nself.assertEqual(DirectoryEntryType.FILE, de.type)\nself.assertEqual('file.py', de.name)\nself.assertEqual(de.source, source)",
"source = FileSource()\nsource.path ... | <|body_start_0|>
source = FileSource()
source.path = 'path/to/file.py'
de = make_directory_entry('path/to', source)
self.assertIsInstance(de, DirectoryListEntry)
self.assertEqual(DirectoryEntryType.FILE, de.type)
self.assertEqual('file.py', de.name)
self.assertEqu... | Test the behavior of the `make_directory_entry` function. | MakeDirectoryEntryTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MakeDirectoryEntryTest:
"""Test the behavior of the `make_directory_entry` function."""
def test_make_file_directory_entry(self):
"""Test that if a file path is passed in to `make_directory_entry`, the filename (last path component) is parsed and the type is FILE."""
<|body_0... | stack_v2_sparse_classes_36k_train_033253 | 17,513 | permissive | [
{
"docstring": "Test that if a file path is passed in to `make_directory_entry`, the filename (last path component) is parsed and the type is FILE.",
"name": "test_make_file_directory_entry",
"signature": "def test_make_file_directory_entry(self)"
},
{
"docstring": "Test that if a directory path... | 2 | null | Implement the Python class `MakeDirectoryEntryTest` described below.
Class description:
Test the behavior of the `make_directory_entry` function.
Method signatures and docstrings:
- def test_make_file_directory_entry(self): Test that if a file path is passed in to `make_directory_entry`, the filename (last path compo... | Implement the Python class `MakeDirectoryEntryTest` described below.
Class description:
Test the behavior of the `make_directory_entry` function.
Method signatures and docstrings:
- def test_make_file_directory_entry(self): Test that if a file path is passed in to `make_directory_entry`, the filename (last path compo... | 47c6377ccbfe8576b35854053d726537e533e78c | <|skeleton|>
class MakeDirectoryEntryTest:
"""Test the behavior of the `make_directory_entry` function."""
def test_make_file_directory_entry(self):
"""Test that if a file path is passed in to `make_directory_entry`, the filename (last path component) is parsed and the type is FILE."""
<|body_0... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MakeDirectoryEntryTest:
"""Test the behavior of the `make_directory_entry` function."""
def test_make_file_directory_entry(self):
"""Test that if a file path is passed in to `make_directory_entry`, the filename (last path component) is parsed and the type is FILE."""
source = FileSource()... | the_stack_v2_python_sparse | director/projects/test_source_operations.py | gxf1986/hub | train | 0 |
c8be236df4be6b86d3f4197a11adb8103d6b6f9a | [
"try:\n return Part.objects.create(**validated_data)\nexcept (IntegrityError, ValidationError):\n raise PartSameNameExistError",
"try:\n result = super().update(instance, validated_data)\n return result\nexcept (IntegrityError, ValidationError):\n raise PartSameNameExistError"
] | <|body_start_0|>
try:
return Part.objects.create(**validated_data)
except (IntegrityError, ValidationError):
raise PartSameNameExistError
<|end_body_0|>
<|body_start_1|>
try:
result = super().update(instance, validated_data)
return result
... | PartSerializer. | PartSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PartSerializer:
"""PartSerializer."""
def create(self, validated_data):
"""create. Args: validated_data:"""
<|body_0|>
def update(self, instance, validated_data):
"""update. Args: instance: validated_data:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_033254 | 1,320 | permissive | [
{
"docstring": "create. Args: validated_data:",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "update. Args: instance: validated_data:",
"name": "update",
"signature": "def update(self, instance, validated_data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020826 | Implement the Python class `PartSerializer` described below.
Class description:
PartSerializer.
Method signatures and docstrings:
- def create(self, validated_data): create. Args: validated_data:
- def update(self, instance, validated_data): update. Args: instance: validated_data: | Implement the Python class `PartSerializer` described below.
Class description:
PartSerializer.
Method signatures and docstrings:
- def create(self, validated_data): create. Args: validated_data:
- def update(self, instance, validated_data): update. Args: instance: validated_data:
<|skeleton|>
class PartSerializer:
... | 1d2f42cbf9f21157c1e1abf044b26160dfed5b16 | <|skeleton|>
class PartSerializer:
"""PartSerializer."""
def create(self, validated_data):
"""create. Args: validated_data:"""
<|body_0|>
def update(self, instance, validated_data):
"""update. Args: instance: validated_data:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PartSerializer:
"""PartSerializer."""
def create(self, validated_data):
"""create. Args: validated_data:"""
try:
return Part.objects.create(**validated_data)
except (IntegrityError, ValidationError):
raise PartSameNameExistError
def update(self, instan... | the_stack_v2_python_sparse | factory-ai-vision/EdgeSolution/modules/WebModule/backend/vision_on_edge/azure_parts/api/serializers.py | Azure-Samples/azure-intelligent-edge-patterns | train | 193 |
52fe65d722c479f57c493d449f39cae664d2b8d7 | [
"user = request.user\nif user.is_anonymous():\n user = User.objects.get(display_name='AnonymousUser')\ndata = request.data\nproject = Project.objects.as_contributor(request.user, project_id)\nif not data.get('meta').get('status') == 'draft' and project.can_moderate(user):\n data['meta']['status'] = 'active'\n... | <|body_start_0|>
user = request.user
if user.is_anonymous():
user = User.objects.get(display_name='AnonymousUser')
data = request.data
project = Project.objects.as_contributor(request.user, project_id)
if not data.get('meta').get('status') == 'draft' and project.can_m... | Public API endpoint to add new contributions to a project /api/projects/:project_id/contributions | ProjectObservations | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectObservations:
"""Public API endpoint to add new contributions to a project /api/projects/:project_id/contributions"""
def post(self, request, project_id):
"""Adds a new contribution to a project Parameters ---------- request : rest_framework.request.Request Represents the requ... | stack_v2_sparse_classes_36k_train_033255 | 10,813 | permissive | [
{
"docstring": "Adds a new contribution to a project Parameters ---------- request : rest_framework.request.Request Represents the request project_id : int identifies the project in the data base Returns ------- rest_framework.response.Respone Contains the serialised contribution",
"name": "post",
"sign... | 2 | null | Implement the Python class `ProjectObservations` described below.
Class description:
Public API endpoint to add new contributions to a project /api/projects/:project_id/contributions
Method signatures and docstrings:
- def post(self, request, project_id): Adds a new contribution to a project Parameters ---------- req... | Implement the Python class `ProjectObservations` described below.
Class description:
Public API endpoint to add new contributions to a project /api/projects/:project_id/contributions
Method signatures and docstrings:
- def post(self, request, project_id): Adds a new contribution to a project Parameters ---------- req... | 16d31b5207de9f699fc01054baad1fe65ad1c3ca | <|skeleton|>
class ProjectObservations:
"""Public API endpoint to add new contributions to a project /api/projects/:project_id/contributions"""
def post(self, request, project_id):
"""Adds a new contribution to a project Parameters ---------- request : rest_framework.request.Request Represents the requ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectObservations:
"""Public API endpoint to add new contributions to a project /api/projects/:project_id/contributions"""
def post(self, request, project_id):
"""Adds a new contribution to a project Parameters ---------- request : rest_framework.request.Request Represents the request project_i... | the_stack_v2_python_sparse | geokey/contributions/views/observations.py | NeolithEra/geokey | train | 0 |
eaa39b8e4841917872a4766f649e2150785a6f66 | [
"dict_pos = {}\nfor i, v in enumerate(numbers):\n dict_pos[target - v] = i + 1\nfor i, v in enumerate(numbers):\n if v in dict_pos:\n return [i + 1, dict_pos[v]]",
"for i, v in enumerate(numbers):\n l, r = (i + 1, len(numbers) - 1)\n tmp = target - v\n while l <= r:\n mid = (l + r) //... | <|body_start_0|>
dict_pos = {}
for i, v in enumerate(numbers):
dict_pos[target - v] = i + 1
for i, v in enumerate(numbers):
if v in dict_pos:
return [i + 1, dict_pos[v]]
<|end_body_0|>
<|body_start_1|>
for i, v in enumerate(numbers):
l... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, numbers, target):
""":type numbers: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum_binarySearch(self, numbers, target):
""":type numbers: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k_train_033256 | 1,013 | no_license | [
{
"docstring": ":type numbers: List[int] :type target: int :rtype: List[int]",
"name": "twoSum",
"signature": "def twoSum(self, numbers, target)"
},
{
"docstring": ":type numbers: List[int] :type target: int :rtype: List[int]",
"name": "twoSum_binarySearch",
"signature": "def twoSum_bina... | 2 | stack_v2_sparse_classes_30k_train_004574 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, numbers, target): :type numbers: List[int] :type target: int :rtype: List[int]
- def twoSum_binarySearch(self, numbers, target): :type numbers: List[int] :type t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, numbers, target): :type numbers: List[int] :type target: int :rtype: List[int]
- def twoSum_binarySearch(self, numbers, target): :type numbers: List[int] :type t... | f3fc71f344cd758cfce77f16ab72992c99ab288e | <|skeleton|>
class Solution:
def twoSum(self, numbers, target):
""":type numbers: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum_binarySearch(self, numbers, target):
""":type numbers: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum(self, numbers, target):
""":type numbers: List[int] :type target: int :rtype: List[int]"""
dict_pos = {}
for i, v in enumerate(numbers):
dict_pos[target - v] = i + 1
for i, v in enumerate(numbers):
if v in dict_pos:
r... | the_stack_v2_python_sparse | 167_twoSumII.py | jennyChing/leetCode | train | 2 | |
7309c1a5226dcdfd7341a0e2d2b6bc5161404fc0 | [
"enterprise_client = EnterpriseApiClient(auth_token)\nenterprise_learner_data = enterprise_client.get_enterprise_learner(user)\nif not enterprise_learner_data:\n return None\nreturn {'enterprise_id': enterprise_learner_data['enterprise_customer']['uuid'], 'enterprise_groups': enterprise_learner_data['groups']}",... | <|body_start_0|>
enterprise_client = EnterpriseApiClient(auth_token)
enterprise_learner_data = enterprise_client.get_enterprise_learner(user)
if not enterprise_learner_data:
return None
return {'enterprise_id': enterprise_learner_data['enterprise_customer']['uuid'], 'enterpri... | Permission that checks to see if the request user is staff or is associated with the enterprise in the request. NOTE: This permission check may make a request to the LMS to get the enterprise association if it is not already in the session. This fetch should go away when JWT Scopes are fully implemented and the associa... | IsStaffOrEnterpriseUser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IsStaffOrEnterpriseUser:
"""Permission that checks to see if the request user is staff or is associated with the enterprise in the request. NOTE: This permission check may make a request to the LMS to get the enterprise association if it is not already in the session. This fetch should go away wh... | stack_v2_sparse_classes_36k_train_033257 | 4,847 | no_license | [
{
"docstring": "Get the enterprise learner model from the LMS for the given user. Returns: learner or None if unable to get or user is not associated with an enterprise",
"name": "get_user_enterprise_data",
"signature": "def get_user_enterprise_data(self, auth_token, user)"
},
{
"docstring": "Ve... | 2 | stack_v2_sparse_classes_30k_train_018686 | Implement the Python class `IsStaffOrEnterpriseUser` described below.
Class description:
Permission that checks to see if the request user is staff or is associated with the enterprise in the request. NOTE: This permission check may make a request to the LMS to get the enterprise association if it is not already in th... | Implement the Python class `IsStaffOrEnterpriseUser` described below.
Class description:
Permission that checks to see if the request user is staff or is associated with the enterprise in the request. NOTE: This permission check may make a request to the LMS to get the enterprise association if it is not already in th... | d16a25b035b2e810b8ab2b0a2ac032b216562e26 | <|skeleton|>
class IsStaffOrEnterpriseUser:
"""Permission that checks to see if the request user is staff or is associated with the enterprise in the request. NOTE: This permission check may make a request to the LMS to get the enterprise association if it is not already in the session. This fetch should go away wh... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IsStaffOrEnterpriseUser:
"""Permission that checks to see if the request user is staff or is associated with the enterprise in the request. NOTE: This permission check may make a request to the LMS to get the enterprise association if it is not already in the session. This fetch should go away when JWT Scopes... | the_stack_v2_python_sparse | edx/app/analytics_api/venvs/analytics_api/lib/python2.7/site-packages/enterprise_data/permissions.py | JosiahKennedy/openedx-branded | train | 0 |
04767d67247b6a4868355544badd686a6a52f49a | [
"_FgmQPBase.__init__(self, H, G, u_lb, u_ub)\nself.E = mtx(state_factor)\nself.mu = penalty_param\nself.nu, L = self._compute_extra_step_constant(H, self.mu, self.E)\nself.Linv = 1.0 / L\nself.HoL = H * self.Linv\nself.GoL = G * self.Linv",
"L = max(np.linalg.eigvalsh(H + mu * (E.T * E)))\nphi = min(np.linalg.eig... | <|body_start_0|>
_FgmQPBase.__init__(self, H, G, u_lb, u_ub)
self.E = mtx(state_factor)
self.mu = penalty_param
self.nu, L = self._compute_extra_step_constant(H, self.mu, self.E)
self.Linv = 1.0 / L
self.HoL = H * self.Linv
self.GoL = G * self.Linv
<|end_body_0|>
... | Compute data to solve a mix constrained MPC quadratic program. This subclass extends the FgmInputConstrQP.__init__ method by computing the appropriate constants related to the augmented Lagrangian method. | FgmStateConstrQP | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FgmStateConstrQP:
"""Compute data to solve a mix constrained MPC quadratic program. This subclass extends the FgmInputConstrQP.__init__ method by computing the appropriate constants related to the augmented Lagrangian method."""
def __init__(self, H, G, state_factor, u_lb, u_ub, penalty_para... | stack_v2_sparse_classes_36k_train_033258 | 4,276 | no_license | [
{
"docstring": "Setup the method self variables from the given inputs variables.",
"name": "__init__",
"signature": "def __init__(self, H, G, state_factor, u_lb, u_ub, penalty_param)"
},
{
"docstring": "Overloaded method. E: 2-side state constraint prediction matrix. Return a tuple with the FGM ... | 2 | stack_v2_sparse_classes_30k_train_006556 | Implement the Python class `FgmStateConstrQP` described below.
Class description:
Compute data to solve a mix constrained MPC quadratic program. This subclass extends the FgmInputConstrQP.__init__ method by computing the appropriate constants related to the augmented Lagrangian method.
Method signatures and docstring... | Implement the Python class `FgmStateConstrQP` described below.
Class description:
Compute data to solve a mix constrained MPC quadratic program. This subclass extends the FgmInputConstrQP.__init__ method by computing the appropriate constants related to the augmented Lagrangian method.
Method signatures and docstring... | 152657b46cbd5d3232d1a85b7a48b8ed1f6d1927 | <|skeleton|>
class FgmStateConstrQP:
"""Compute data to solve a mix constrained MPC quadratic program. This subclass extends the FgmInputConstrQP.__init__ method by computing the appropriate constants related to the augmented Lagrangian method."""
def __init__(self, H, G, state_factor, u_lb, u_ub, penalty_para... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FgmStateConstrQP:
"""Compute data to solve a mix constrained MPC quadratic program. This subclass extends the FgmInputConstrQP.__init__ method by computing the appropriate constants related to the augmented Lagrangian method."""
def __init__(self, H, G, state_factor, u_lb, u_ub, penalty_param):
"... | the_stack_v2_python_sparse | muAO-MPC-0.3.0/muaompc/_ltidt/fgmqp.py | JayFenchel/mas_thes | train | 0 |
92fff1cf6c4848520d1b0eab66d9d1e9a1d21fc4 | [
"super(bao236_lik, self).__init__()\nself.c_over_Hrd = 9.0\nself.sig_c_over_Hrd = 0.3\nself.D_A_over_rd = 10.8\nself.sig_D_A_over_rd = 0.4",
"pred = {'H_236': 70.0, 'D_A_236': 2000.0, 'r_d': 149.28, 'c': 299790.0}\nfor key, value in kwargs.iteritems():\n pred[key] = value\nself.c_over_Hrd_theo = pred['c'] / pr... | <|body_start_0|>
super(bao236_lik, self).__init__()
self.c_over_Hrd = 9.0
self.sig_c_over_Hrd = 0.3
self.D_A_over_rd = 10.8
self.sig_D_A_over_rd = 0.4
<|end_body_0|>
<|body_start_1|>
pred = {'H_236': 70.0, 'D_A_236': 2000.0, 'r_d': 149.28, 'c': 299790.0}
for key,... | get likelihood for bao236 given model predictions can use any units so long as they are consistent | bao236_lik | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class bao236_lik:
"""get likelihood for bao236 given model predictions can use any units so long as they are consistent"""
def __init__(self):
"""initialize with bao data for 2.36. can use any units so long as they are consistent"""
<|body_0|>
def __call__(self, **kwargs):
... | stack_v2_sparse_classes_36k_train_033259 | 1,652 | permissive | [
{
"docstring": "initialize with bao data for 2.36. can use any units so long as they are consistent",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "returns ln(likelihood) given H(2.36) and D_A(2.36) for the particular model. can use any units so long as they are consis... | 2 | stack_v2_sparse_classes_30k_train_015370 | Implement the Python class `bao236_lik` described below.
Class description:
get likelihood for bao236 given model predictions can use any units so long as they are consistent
Method signatures and docstrings:
- def __init__(self): initialize with bao data for 2.36. can use any units so long as they are consistent
- d... | Implement the Python class `bao236_lik` described below.
Class description:
get likelihood for bao236 given model predictions can use any units so long as they are consistent
Method signatures and docstrings:
- def __init__(self): initialize with bao data for 2.36. can use any units so long as they are consistent
- d... | 405852a076cda0c7f95447cf50c1a7e1f24d59f3 | <|skeleton|>
class bao236_lik:
"""get likelihood for bao236 given model predictions can use any units so long as they are consistent"""
def __init__(self):
"""initialize with bao data for 2.36. can use any units so long as they are consistent"""
<|body_0|>
def __call__(self, **kwargs):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class bao236_lik:
"""get likelihood for bao236 given model predictions can use any units so long as they are consistent"""
def __init__(self):
"""initialize with bao data for 2.36. can use any units so long as they are consistent"""
super(bao236_lik, self).__init__()
self.c_over_Hrd = 9... | the_stack_v2_python_sparse | cosmoslik/cosmoslik_plugins/likelihoods/bao236_lik.py | bfollinprm/Nquintessence | train | 0 |
2dfbb4ab5e12c31474a4df7723c36478a24a86f1 | [
"if ip_version not in (u'ip4', u'ip6'):\n raise ValueError(u'IP version is not in correct format')\ncmd = u'cop_whitelist_enable_disable'\nerr_msg = f\"Failed to add COP whitelist on interface {interface} on host {node[u'host']}\"\nargs = dict(sw_if_index=Topology.get_interface_sw_index(node, interface), fib_id=... | <|body_start_0|>
if ip_version not in (u'ip4', u'ip6'):
raise ValueError(u'IP version is not in correct format')
cmd = u'cop_whitelist_enable_disable'
err_msg = f"Failed to add COP whitelist on interface {interface} on host {node[u'host']}"
args = dict(sw_if_index=Topology.ge... | COP utilities. | Cop | [
"CC-BY-4.0",
"Apache-2.0",
"LicenseRef-scancode-dco-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cop:
"""COP utilities."""
def cop_add_whitelist_entry(node, interface, ip_version, fib_id, default_cop=0):
"""Add cop whitelisted entry. :param node: Node to add COP whitelist on. :param interface: Interface of the node where the COP is added. :param ip_version: IP version. 'ip4' and... | stack_v2_sparse_classes_36k_train_033260 | 3,282 | permissive | [
{
"docstring": "Add cop whitelisted entry. :param node: Node to add COP whitelist on. :param interface: Interface of the node where the COP is added. :param ip_version: IP version. 'ip4' and 'ip6' are valid values. :param fib_id: Specify the fib table ID. :param default_cop: 1 => enable non-ip4, non-ip6 filtrat... | 2 | stack_v2_sparse_classes_30k_train_008402 | Implement the Python class `Cop` described below.
Class description:
COP utilities.
Method signatures and docstrings:
- def cop_add_whitelist_entry(node, interface, ip_version, fib_id, default_cop=0): Add cop whitelisted entry. :param node: Node to add COP whitelist on. :param interface: Interface of the node where t... | Implement the Python class `Cop` described below.
Class description:
COP utilities.
Method signatures and docstrings:
- def cop_add_whitelist_entry(node, interface, ip_version, fib_id, default_cop=0): Add cop whitelisted entry. :param node: Node to add COP whitelist on. :param interface: Interface of the node where t... | 2156583b4e66f2c3c35903c854b1823b76a4e9a6 | <|skeleton|>
class Cop:
"""COP utilities."""
def cop_add_whitelist_entry(node, interface, ip_version, fib_id, default_cop=0):
"""Add cop whitelisted entry. :param node: Node to add COP whitelist on. :param interface: Interface of the node where the COP is added. :param ip_version: IP version. 'ip4' and... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Cop:
"""COP utilities."""
def cop_add_whitelist_entry(node, interface, ip_version, fib_id, default_cop=0):
"""Add cop whitelisted entry. :param node: Node to add COP whitelist on. :param interface: Interface of the node where the COP is added. :param ip_version: IP version. 'ip4' and 'ip6' are va... | the_stack_v2_python_sparse | resources/libraries/python/Cop.py | nidhyanandhan/csit | train | 0 |
19010bc22c79b4716d5467797d05bf2d7327b74e | [
"self.c = db.c\nself.connection = db.connection\nself.c.execute(\"CREATE TABLE IF NOT EXISTS 'payment_channel_spend' (payment_txid text unique, payment_tx text, amount integer, is_redeemed integer, deposit_txid text)\")",
"insert = 'INSERT INTO payment_channel_spend VALUES (?,?,?,?,?)'\nself.c.execute(insert, (st... | <|body_start_0|>
self.c = db.c
self.connection = db.connection
self.c.execute("CREATE TABLE IF NOT EXISTS 'payment_channel_spend' (payment_txid text unique, payment_tx text, amount integer, is_redeemed integer, deposit_txid text)")
<|end_body_0|>
<|body_start_1|>
insert = 'INSERT INTO p... | SQLite3 binding for the payment model. | PaymentSQLite3 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaymentSQLite3:
"""SQLite3 binding for the payment model."""
def __init__(self, db):
"""Instantiate SQLite3 for storing channel payment data."""
<|body_0|>
def create(self, deposit_txid, payment_tx, amount):
"""Create a payment entry."""
<|body_1|>
d... | stack_v2_sparse_classes_36k_train_033261 | 16,798 | permissive | [
{
"docstring": "Instantiate SQLite3 for storing channel payment data.",
"name": "__init__",
"signature": "def __init__(self, db)"
},
{
"docstring": "Create a payment entry.",
"name": "create",
"signature": "def create(self, deposit_txid, payment_tx, amount)"
},
{
"docstring": "Lo... | 4 | stack_v2_sparse_classes_30k_test_000511 | Implement the Python class `PaymentSQLite3` described below.
Class description:
SQLite3 binding for the payment model.
Method signatures and docstrings:
- def __init__(self, db): Instantiate SQLite3 for storing channel payment data.
- def create(self, deposit_txid, payment_tx, amount): Create a payment entry.
- def l... | Implement the Python class `PaymentSQLite3` described below.
Class description:
SQLite3 binding for the payment model.
Method signatures and docstrings:
- def __init__(self, db): Instantiate SQLite3 for storing channel payment data.
- def create(self, deposit_txid, payment_tx, amount): Create a payment entry.
- def l... | a5e99fccf11ed75420775ae3e924c9ce94f2e86d | <|skeleton|>
class PaymentSQLite3:
"""SQLite3 binding for the payment model."""
def __init__(self, db):
"""Instantiate SQLite3 for storing channel payment data."""
<|body_0|>
def create(self, deposit_txid, payment_tx, amount):
"""Create a payment entry."""
<|body_1|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PaymentSQLite3:
"""SQLite3 binding for the payment model."""
def __init__(self, db):
"""Instantiate SQLite3 for storing channel payment data."""
self.c = db.c
self.connection = db.connection
self.c.execute("CREATE TABLE IF NOT EXISTS 'payment_channel_spend' (payment_txid t... | the_stack_v2_python_sparse | two1/bitserv/models.py | shayanb/two1 | train | 4 |
aa26d3740c0821828ab50dfcf2fcfde33611e0af | [
"firing_rate = cell_statistics[0].astype(np.float32)\nn_poly = 4\noutputs = []\nfor cell_type_index in np.unique(cell_type):\n cells = cell_type == cell_type_index\n output = tf.zeros(np.sum(cells))\n a = tf.Variable(np.ones(n_poly).astype(np.float32), name='polynomial_coeffs_%d' % cell_type_index)\n fo... | <|body_start_0|>
firing_rate = cell_statistics[0].astype(np.float32)
n_poly = 4
outputs = []
for cell_type_index in np.unique(cell_type):
cells = cell_type == cell_type_index
output = tf.zeros(np.sum(cells))
a = tf.Variable(np.ones(n_poly).astype(np.fl... | Convolutional distance over local groups. | ConvolutionalProsthesisScore | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvolutionalProsthesisScore:
"""Convolutional distance over local groups."""
def _get_cell_weights(self, cell_type, cell_statistics):
"""Get weights for each cell using mean firing rate and cell type."""
<|body_0|>
def _embed_responses(self, response, map_cell_grid_tf, ... | stack_v2_sparse_classes_36k_train_033262 | 5,585 | permissive | [
{
"docstring": "Get weights for each cell using mean firing rate and cell type.",
"name": "_get_cell_weights",
"signature": "def _get_cell_weights(self, cell_type, cell_statistics)"
},
{
"docstring": "Embed a response vector into a two dimensional grid. Args : response : Tensor of shape (batch_s... | 2 | stack_v2_sparse_classes_30k_train_021682 | Implement the Python class `ConvolutionalProsthesisScore` described below.
Class description:
Convolutional distance over local groups.
Method signatures and docstrings:
- def _get_cell_weights(self, cell_type, cell_statistics): Get weights for each cell using mean firing rate and cell type.
- def _embed_responses(se... | Implement the Python class `ConvolutionalProsthesisScore` described below.
Class description:
Convolutional distance over local groups.
Method signatures and docstrings:
- def _get_cell_weights(self, cell_type, cell_statistics): Get weights for each cell using mean firing rate and cell type.
- def _embed_responses(se... | 0dea94bbd54f591d82d95169e33d40bb55b6be94 | <|skeleton|>
class ConvolutionalProsthesisScore:
"""Convolutional distance over local groups."""
def _get_cell_weights(self, cell_type, cell_statistics):
"""Get weights for each cell using mean firing rate and cell type."""
<|body_0|>
def _embed_responses(self, response, map_cell_grid_tf, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvolutionalProsthesisScore:
"""Convolutional distance over local groups."""
def _get_cell_weights(self, cell_type, cell_statistics):
"""Get weights for each cell using mean firing rate and cell type."""
firing_rate = cell_statistics[0].astype(np.float32)
n_poly = 4
outpu... | the_stack_v2_python_sparse | response_model/python/metric_learning/score_fcns/convolutional_prosthesis.py | googlearchive/rgc-models | train | 0 |
d5fe49199b1d21bf3d13cd40abae74fd31c192ee | [
"self.children = children\nself.parent = parent\nself.index = index",
"node = self\nancestor_list = []\nwhile node.parent is not None:\n ancestor_list.append(node.parent)\n node = node.parent\nreturn ancestor_list"
] | <|body_start_0|>
self.children = children
self.parent = parent
self.index = index
<|end_body_0|>
<|body_start_1|>
node = self
ancestor_list = []
while node.parent is not None:
ancestor_list.append(node.parent)
node = node.parent
return anc... | Fenwick Tree node. | FenwickNode | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FenwickNode:
"""Fenwick Tree node."""
def __init__(self, parent, children, index=None):
"""Fenwick Tree node. Single parent and multiple children. Args: parent: FenwickNode. A parent node. children: List. A list of children nodes (FenwickNode). index: Int. Node label."""
<|bo... | stack_v2_sparse_classes_36k_train_033263 | 5,001 | permissive | [
{
"docstring": "Fenwick Tree node. Single parent and multiple children. Args: parent: FenwickNode. A parent node. children: List. A list of children nodes (FenwickNode). index: Int. Node label.",
"name": "__init__",
"signature": "def __init__(self, parent, children, index=None)"
},
{
"docstring"... | 2 | null | Implement the Python class `FenwickNode` described below.
Class description:
Fenwick Tree node.
Method signatures and docstrings:
- def __init__(self, parent, children, index=None): Fenwick Tree node. Single parent and multiple children. Args: parent: FenwickNode. A parent node. children: List. A list of children nod... | Implement the Python class `FenwickNode` described below.
Class description:
Fenwick Tree node.
Method signatures and docstrings:
- def __init__(self, parent, children, index=None): Fenwick Tree node. Single parent and multiple children. Args: parent: FenwickNode. A parent node. children: List. A list of children nod... | 788481753c798a72c5cb3aa9f2aa9da3ce3190b0 | <|skeleton|>
class FenwickNode:
"""Fenwick Tree node."""
def __init__(self, parent, children, index=None):
"""Fenwick Tree node. Single parent and multiple children. Args: parent: FenwickNode. A parent node. children: List. A list of children nodes (FenwickNode). index: Int. Node label."""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FenwickNode:
"""Fenwick Tree node."""
def __init__(self, parent, children, index=None):
"""Fenwick Tree node. Single parent and multiple children. Args: parent: FenwickNode. A parent node. children: List. A list of children nodes (FenwickNode). index: Int. Node label."""
self.children = c... | the_stack_v2_python_sparse | src/openfermion/transforms/opconversions/fenwick_tree.py | quantumlib/OpenFermion | train | 1,481 |
a621a402dc4c2cb7621ccf361f7dab35276a9da0 | [
"super(VideoCrawler, self).__init__(*args, **kwargs)\nself.setVar('category', 'video')\nself.setTag('video', self.pathHolder().baseName())",
"if self.__ffprobeExecutable and name in ('width', 'height') and (name not in self.varNames()):\n self.__computeWidthHeight()\nreturn super(VideoCrawler, self).var(name)"... | <|body_start_0|>
super(VideoCrawler, self).__init__(*args, **kwargs)
self.setVar('category', 'video')
self.setTag('video', self.pathHolder().baseName())
<|end_body_0|>
<|body_start_1|>
if self.__ffprobeExecutable and name in ('width', 'height') and (name not in self.varNames()):
... | Abstracted video crawler. | VideoCrawler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VideoCrawler:
"""Abstracted video crawler."""
def __init__(self, *args, **kwargs):
"""Create a video crawler."""
<|body_0|>
def var(self, name):
"""Return var value using lazy loading implementation for width and height."""
<|body_1|>
def __computeWi... | stack_v2_sparse_classes_36k_train_033264 | 1,764 | permissive | [
{
"docstring": "Create a video crawler.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Return var value using lazy loading implementation for width and height.",
"name": "var",
"signature": "def var(self, name)"
},
{
"docstring": "Quer... | 3 | stack_v2_sparse_classes_30k_train_012937 | Implement the Python class `VideoCrawler` described below.
Class description:
Abstracted video crawler.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create a video crawler.
- def var(self, name): Return var value using lazy loading implementation for width and height.
- def __computeWidthH... | Implement the Python class `VideoCrawler` described below.
Class description:
Abstracted video crawler.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create a video crawler.
- def var(self, name): Return var value using lazy loading implementation for width and height.
- def __computeWidthH... | 046dbb0c1b4ff20ea5f2e1679f8d89f3089b6aa4 | <|skeleton|>
class VideoCrawler:
"""Abstracted video crawler."""
def __init__(self, *args, **kwargs):
"""Create a video crawler."""
<|body_0|>
def var(self, name):
"""Return var value using lazy loading implementation for width and height."""
<|body_1|>
def __computeWi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VideoCrawler:
"""Abstracted video crawler."""
def __init__(self, *args, **kwargs):
"""Create a video crawler."""
super(VideoCrawler, self).__init__(*args, **kwargs)
self.setVar('category', 'video')
self.setTag('video', self.pathHolder().baseName())
def var(self, name)... | the_stack_v2_python_sparse | src/lib/kombi/Crawler/Fs/Video/VideoCrawler.py | kombiHQ/kombi | train | 2 |
a40e36424bdf0dac7ef3b258ce27876cfa3de4de | [
"self.host = host\nself.integral_volume_names = integral_volume_names\nself.password = password\nself.port = port\nself.share_type = share_type\nself.use_https = use_https\nself.username = username",
"if dictionary is None:\n return None\nhost = dictionary.get('host')\nintegral_volume_names = dictionary.get('i... | <|body_start_0|>
self.host = host
self.integral_volume_names = integral_volume_names
self.password = password
self.port = port
self.share_type = share_type
self.use_https = use_https
self.username = username
<|end_body_0|>
<|body_start_1|>
if dictionary i... | Implementation of the 'QStarServerCredentials' model. Specifies the server credentials to connect to a QStar service to manage the media Vault. Attributes: host (string): Specifies the IP address or DNS name of the server where QStar service is running. integral_volume_names (list of string): Array of Integral Volume N... | QStarServerCredentials | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QStarServerCredentials:
"""Implementation of the 'QStarServerCredentials' model. Specifies the server credentials to connect to a QStar service to manage the media Vault. Attributes: host (string): Specifies the IP address or DNS name of the server where QStar service is running. integral_volume_... | stack_v2_sparse_classes_36k_train_033265 | 3,345 | permissive | [
{
"docstring": "Constructor for the QStarServerCredentials class",
"name": "__init__",
"signature": "def __init__(self, host=None, integral_volume_names=None, password=None, port=None, share_type=None, use_https=None, username=None)"
},
{
"docstring": "Creates an instance of this model from a di... | 2 | stack_v2_sparse_classes_30k_train_006435 | Implement the Python class `QStarServerCredentials` described below.
Class description:
Implementation of the 'QStarServerCredentials' model. Specifies the server credentials to connect to a QStar service to manage the media Vault. Attributes: host (string): Specifies the IP address or DNS name of the server where QSt... | Implement the Python class `QStarServerCredentials` described below.
Class description:
Implementation of the 'QStarServerCredentials' model. Specifies the server credentials to connect to a QStar service to manage the media Vault. Attributes: host (string): Specifies the IP address or DNS name of the server where QSt... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class QStarServerCredentials:
"""Implementation of the 'QStarServerCredentials' model. Specifies the server credentials to connect to a QStar service to manage the media Vault. Attributes: host (string): Specifies the IP address or DNS name of the server where QStar service is running. integral_volume_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QStarServerCredentials:
"""Implementation of the 'QStarServerCredentials' model. Specifies the server credentials to connect to a QStar service to manage the media Vault. Attributes: host (string): Specifies the IP address or DNS name of the server where QStar service is running. integral_volume_names (list o... | the_stack_v2_python_sparse | cohesity_management_sdk/models/q_star_server_credentials.py | cohesity/management-sdk-python | train | 24 |
0101cb4e170a8d168a24134fee231c0d44274d44 | [
"LOG.debug('Allocating vip with port id %s, subnet id %s, ip address %s for load balancer %s', loadbalancer[constants.VIP_PORT_ID], loadbalancer[constants.VIP_SUBNET_ID], loadbalancer[constants.VIP_ADDRESS], loadbalancer[constants.LOADBALANCER_ID])\nsession = db_apis.get_session()\nwith session.begin():\n db_lb ... | <|body_start_0|>
LOG.debug('Allocating vip with port id %s, subnet id %s, ip address %s for load balancer %s', loadbalancer[constants.VIP_PORT_ID], loadbalancer[constants.VIP_SUBNET_ID], loadbalancer[constants.VIP_ADDRESS], loadbalancer[constants.LOADBALANCER_ID])
session = db_apis.get_session()
... | Task to allocate a VIP. | AllocateVIP | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AllocateVIP:
"""Task to allocate a VIP."""
def execute(self, loadbalancer):
"""Allocate a vip to the loadbalancer."""
<|body_0|>
def revert(self, result, loadbalancer, *args, **kwargs):
"""Handle a failure to allocate vip."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_033266 | 44,034 | permissive | [
{
"docstring": "Allocate a vip to the loadbalancer.",
"name": "execute",
"signature": "def execute(self, loadbalancer)"
},
{
"docstring": "Handle a failure to allocate vip.",
"name": "revert",
"signature": "def revert(self, result, loadbalancer, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016429 | Implement the Python class `AllocateVIP` described below.
Class description:
Task to allocate a VIP.
Method signatures and docstrings:
- def execute(self, loadbalancer): Allocate a vip to the loadbalancer.
- def revert(self, result, loadbalancer, *args, **kwargs): Handle a failure to allocate vip. | Implement the Python class `AllocateVIP` described below.
Class description:
Task to allocate a VIP.
Method signatures and docstrings:
- def execute(self, loadbalancer): Allocate a vip to the loadbalancer.
- def revert(self, result, loadbalancer, *args, **kwargs): Handle a failure to allocate vip.
<|skeleton|>
class... | 0426285a41464a5015494584f109eed35a0d44db | <|skeleton|>
class AllocateVIP:
"""Task to allocate a VIP."""
def execute(self, loadbalancer):
"""Allocate a vip to the loadbalancer."""
<|body_0|>
def revert(self, result, loadbalancer, *args, **kwargs):
"""Handle a failure to allocate vip."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AllocateVIP:
"""Task to allocate a VIP."""
def execute(self, loadbalancer):
"""Allocate a vip to the loadbalancer."""
LOG.debug('Allocating vip with port id %s, subnet id %s, ip address %s for load balancer %s', loadbalancer[constants.VIP_PORT_ID], loadbalancer[constants.VIP_SUBNET_ID], l... | the_stack_v2_python_sparse | octavia/controller/worker/v2/tasks/network_tasks.py | openstack/octavia | train | 147 |
c9e7e3d5e8f606eb66e7deb9bbb78af1be35a30a | [
"super().__init__()\nself.input_file = input_file\nself.setname = setname\nself.output_gmt = output_gmt\nself.output_csv = output_csv\nself.name_column = name_column\nself.filter_column = filter_column\nself.alternative = alternative\nself.threshold = threshold\nself.descriptor = descriptor\nself.table = rc.ReadCsv... | <|body_start_0|>
super().__init__()
self.input_file = input_file
self.setname = setname
self.output_gmt = output_gmt
self.output_csv = output_csv
self.name_column = name_column
self.filter_column = filter_column
self.alternative = alternative
self.... | This Class converts a csv file to a gmt allowing to filter the elements using the values of one of the columns. The user can specify the column used to retrieve the name of the objects and the filter condition. The output can be either a gmt with the names of the genes that pass the filter or a csv with the whole filte... | CsvToGmt | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CsvToGmt:
"""This Class converts a csv file to a gmt allowing to filter the elements using the values of one of the columns. The user can specify the column used to retrieve the name of the objects and the filter condition. The output can be either a gmt with the names of the genes that pass the ... | stack_v2_sparse_classes_36k_train_033267 | 13,420 | permissive | [
{
"docstring": ":param input_file: str, the csv file :param setname: str, the name of the set :param output_gmt: str, output gmt name :param output_csv: str, output csv name :param name_column: str, column with the names :param filter_column: str, column with the values to be filtered :param alternative: str, a... | 4 | stack_v2_sparse_classes_30k_train_004414 | Implement the Python class `CsvToGmt` described below.
Class description:
This Class converts a csv file to a gmt allowing to filter the elements using the values of one of the columns. The user can specify the column used to retrieve the name of the objects and the filter condition. The output can be either a gmt wit... | Implement the Python class `CsvToGmt` described below.
Class description:
This Class converts a csv file to a gmt allowing to filter the elements using the values of one of the columns. The user can specify the column used to retrieve the name of the objects and the filter condition. The output can be either a gmt wit... | 62307f90af4c72c50aca4cbf8c61e924e69467be | <|skeleton|>
class CsvToGmt:
"""This Class converts a csv file to a gmt allowing to filter the elements using the values of one of the columns. The user can specify the column used to retrieve the name of the objects and the filter condition. The output can be either a gmt with the names of the genes that pass the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CsvToGmt:
"""This Class converts a csv file to a gmt allowing to filter the elements using the values of one of the columns. The user can specify the column used to retrieve the name of the objects and the filter condition. The output can be either a gmt with the names of the genes that pass the filter or a c... | the_stack_v2_python_sparse | pygna/converters.py | science4fun/pygna | train | 0 |
b3de0c282c39412e5c36a64fad99075745cebb9b | [
"self.gen_path = property_dict['main_path']\njsonpath = os.path.join(self.gen_path, 'organized.json')\nobj_props = Lab2Mat.load(jsonpath)\nself.filt_dir = obj_props['filt_dir']\nself.ch_list = list(range(len(obj_props['ch_list'])))\nobj_props.update({'rawpred_path': property_dict['rawpred_path']})\nself.rawpred_pat... | <|body_start_0|>
self.gen_path = property_dict['main_path']
jsonpath = os.path.join(self.gen_path, 'organized.json')
obj_props = Lab2Mat.load(jsonpath)
self.filt_dir = obj_props['filt_dir']
self.ch_list = list(range(len(obj_props['ch_list'])))
obj_props.update({'rawpred_p... | Class for batch seizure prediction | modelPredict | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class modelPredict:
"""Class for batch seizure prediction"""
def __init__(self, property_dict):
"""lab2mat(main_path) Parameters ---------- property_dict : Dict, contains essential info for data load and processing"""
<|body_0|>
def mainfunc(self):
"""mainfunc(self)"""... | stack_v2_sparse_classes_36k_train_033268 | 8,472 | permissive | [
{
"docstring": "lab2mat(main_path) Parameters ---------- property_dict : Dict, contains essential info for data load and processing",
"name": "__init__",
"signature": "def __init__(self, property_dict)"
},
{
"docstring": "mainfunc(self)",
"name": "mainfunc",
"signature": "def mainfunc(se... | 4 | stack_v2_sparse_classes_30k_train_019048 | Implement the Python class `modelPredict` described below.
Class description:
Class for batch seizure prediction
Method signatures and docstrings:
- def __init__(self, property_dict): lab2mat(main_path) Parameters ---------- property_dict : Dict, contains essential info for data load and processing
- def mainfunc(sel... | Implement the Python class `modelPredict` described below.
Class description:
Class for batch seizure prediction
Method signatures and docstrings:
- def __init__(self, property_dict): lab2mat(main_path) Parameters ---------- property_dict : Dict, contains essential info for data load and processing
- def mainfunc(sel... | fd238749a8b80af1bd0902f737bc9017c4e29756 | <|skeleton|>
class modelPredict:
"""Class for batch seizure prediction"""
def __init__(self, property_dict):
"""lab2mat(main_path) Parameters ---------- property_dict : Dict, contains essential info for data load and processing"""
<|body_0|>
def mainfunc(self):
"""mainfunc(self)"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class modelPredict:
"""Class for batch seizure prediction"""
def __init__(self, property_dict):
"""lab2mat(main_path) Parameters ---------- property_dict : Dict, contains essential info for data load and processing"""
self.gen_path = property_dict['main_path']
jsonpath = os.path.join(se... | the_stack_v2_python_sparse | data_preparation/get_predictions.py | bhargavaganti/logic_seizedetect | train | 0 |
108df8a2891c5b77ffd2ce86e83c5ece7dbd5c58 | [
"super().__init__(cost_func)\nself.support_for_bounds = True\nself._status = None\nself.search_space = None\nself.initialize = None\nself.results = None",
"if self.value_ranges is None or np.any(np.isinf(self.value_ranges)):\n raise MissingBoundsError('Gradient-Free-Optimizers requires finite bounds on all par... | <|body_start_0|>
super().__init__(cost_func)
self.support_for_bounds = True
self._status = None
self.search_space = None
self.initialize = None
self.results = None
<|end_body_0|>
<|body_start_1|>
if self.value_ranges is None or np.any(np.isinf(self.value_ranges))... | Controller for the Gradient Free Optimizers fitting software. | GradientFreeController | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GradientFreeController:
"""Controller for the Gradient Free Optimizers fitting software."""
def __init__(self, cost_func):
"""Initialises variables used for temporary storage. :param cost_func: Cost function object selected from options. :type cost_func: subclass of :class:`~fitbench... | stack_v2_sparse_classes_36k_train_033269 | 5,855 | permissive | [
{
"docstring": "Initialises variables used for temporary storage. :param cost_func: Cost function object selected from options. :type cost_func: subclass of :class:`~fitbenchmarking.cost_func.base_cost_func.CostFunc`",
"name": "__init__",
"signature": "def __init__(self, cost_func)"
},
{
"docstr... | 5 | stack_v2_sparse_classes_30k_train_004793 | Implement the Python class `GradientFreeController` described below.
Class description:
Controller for the Gradient Free Optimizers fitting software.
Method signatures and docstrings:
- def __init__(self, cost_func): Initialises variables used for temporary storage. :param cost_func: Cost function object selected fro... | Implement the Python class `GradientFreeController` described below.
Class description:
Controller for the Gradient Free Optimizers fitting software.
Method signatures and docstrings:
- def __init__(self, cost_func): Initialises variables used for temporary storage. :param cost_func: Cost function object selected fro... | 5ee7e66d963ebe9296c0a62c24b9616f6c65537e | <|skeleton|>
class GradientFreeController:
"""Controller for the Gradient Free Optimizers fitting software."""
def __init__(self, cost_func):
"""Initialises variables used for temporary storage. :param cost_func: Cost function object selected from options. :type cost_func: subclass of :class:`~fitbench... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GradientFreeController:
"""Controller for the Gradient Free Optimizers fitting software."""
def __init__(self, cost_func):
"""Initialises variables used for temporary storage. :param cost_func: Cost function object selected from options. :type cost_func: subclass of :class:`~fitbenchmarking.cost_... | the_stack_v2_python_sparse | fitbenchmarking/controllers/gradient_free_controller.py | fitbenchmarking/fitbenchmarking | train | 15 |
7dac66043669ca72e942387744bfaea4ca6557c0 | [
"self.input = '1921680'\nself.output = ['1.9.216.80', '1.92.16.80', '1.92.168.0', '19.2.16.80', '19.2.168.0', '19.21.6.80', '19.21.68.0', '19.216.8.0', '192.1.6.80', '192.1.68.0', '192.16.8.0']\nreturn (self.input, self.output)",
"input_str, output_arr = self.setUp()\noutput = validIPAddresses(input_str)\nself.as... | <|body_start_0|>
self.input = '1921680'
self.output = ['1.9.216.80', '1.92.16.80', '1.92.168.0', '19.2.16.80', '19.2.168.0', '19.21.6.80', '19.21.68.0', '19.216.8.0', '192.1.6.80', '192.1.68.0', '192.16.8.0']
return (self.input, self.output)
<|end_body_0|>
<|body_start_1|>
input_str, ou... | Class with unittests for Valid_IP_Addresses.py | test_Valid_IP_Addresses | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_Valid_IP_Addresses:
"""Class with unittests for Valid_IP_Addresses.py"""
def setUp(self):
"""Sets up input."""
<|body_0|>
def test_ExpectedOutput(self):
"""Checks if returned output is as expected."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_033270 | 1,249 | no_license | [
{
"docstring": "Sets up input.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Checks if returned output is as expected.",
"name": "test_ExpectedOutput",
"signature": "def test_ExpectedOutput(self)"
}
] | 2 | null | Implement the Python class `test_Valid_IP_Addresses` described below.
Class description:
Class with unittests for Valid_IP_Addresses.py
Method signatures and docstrings:
- def setUp(self): Sets up input.
- def test_ExpectedOutput(self): Checks if returned output is as expected. | Implement the Python class `test_Valid_IP_Addresses` described below.
Class description:
Class with unittests for Valid_IP_Addresses.py
Method signatures and docstrings:
- def setUp(self): Sets up input.
- def test_ExpectedOutput(self): Checks if returned output is as expected.
<|skeleton|>
class test_Valid_IP_Addre... | 3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f | <|skeleton|>
class test_Valid_IP_Addresses:
"""Class with unittests for Valid_IP_Addresses.py"""
def setUp(self):
"""Sets up input."""
<|body_0|>
def test_ExpectedOutput(self):
"""Checks if returned output is as expected."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class test_Valid_IP_Addresses:
"""Class with unittests for Valid_IP_Addresses.py"""
def setUp(self):
"""Sets up input."""
self.input = '1921680'
self.output = ['1.9.216.80', '1.92.16.80', '1.92.168.0', '19.2.16.80', '19.2.168.0', '19.21.6.80', '19.21.68.0', '19.216.8.0', '192.1.6.80', '... | the_stack_v2_python_sparse | AlgoExpert_algorithms/Medium/Valid_IP_Addresses/test_Valid_IP_Addresses.py | JakubKazimierski/PythonPortfolio | train | 9 |
3f43c8f6d08095bb6513e38db8d0828238a58008 | [
"super(STFTLoss, self).__init__()\nself.fft_size = fft_size\nself.hop_size = hop_size\nself.win_length = win_length\nself.window = getattr(torch, window)(win_length).cuda()\nself.amp_floor = 1e-05\nself.mse_loss = torch.nn.MSELoss()",
"x_stft = torch.stft(x, self.fft_size, self.hop_size, self.win_length, window=s... | <|body_start_0|>
super(STFTLoss, self).__init__()
self.fft_size = fft_size
self.hop_size = hop_size
self.win_length = win_length
self.window = getattr(torch, window)(win_length).cuda()
self.amp_floor = 1e-05
self.mse_loss = torch.nn.MSELoss()
<|end_body_0|>
<|bod... | STFT loss module. | STFTLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class STFTLoss:
"""STFT loss module."""
def __init__(self, fft_size, hop_size, win_length, window):
"""Initialize STFT loss module."""
<|body_0|>
def forward(self, x, y):
"""Calculate forward propagation. Args: x (Tensor): Predicted signal (B, T). y (Tensor): Groundtru... | stack_v2_sparse_classes_36k_train_033271 | 2,811 | permissive | [
{
"docstring": "Initialize STFT loss module.",
"name": "__init__",
"signature": "def __init__(self, fft_size, hop_size, win_length, window)"
},
{
"docstring": "Calculate forward propagation. Args: x (Tensor): Predicted signal (B, T). y (Tensor): Groundtruth signal (B, T). Returns: Tensor: Logari... | 2 | stack_v2_sparse_classes_30k_train_003564 | Implement the Python class `STFTLoss` described below.
Class description:
STFT loss module.
Method signatures and docstrings:
- def __init__(self, fft_size, hop_size, win_length, window): Initialize STFT loss module.
- def forward(self, x, y): Calculate forward propagation. Args: x (Tensor): Predicted signal (B, T). ... | Implement the Python class `STFTLoss` described below.
Class description:
STFT loss module.
Method signatures and docstrings:
- def __init__(self, fft_size, hop_size, win_length, window): Initialize STFT loss module.
- def forward(self, x, y): Calculate forward propagation. Args: x (Tensor): Predicted signal (B, T). ... | 67331ddb5d6a7227120818842c61b6e07de52ba7 | <|skeleton|>
class STFTLoss:
"""STFT loss module."""
def __init__(self, fft_size, hop_size, win_length, window):
"""Initialize STFT loss module."""
<|body_0|>
def forward(self, x, y):
"""Calculate forward propagation. Args: x (Tensor): Predicted signal (B, T). y (Tensor): Groundtru... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class STFTLoss:
"""STFT loss module."""
def __init__(self, fft_size, hop_size, win_length, window):
"""Initialize STFT loss module."""
super(STFTLoss, self).__init__()
self.fft_size = fft_size
self.hop_size = hop_size
self.win_length = win_length
self.window = ge... | the_stack_v2_python_sparse | usfgan/losses/stft_loss.py | hendrikTpl/UnifiedSourceFilterGAN | train | 0 |
465748b9029abc91d3b4b5fec00243c3c935fe96 | [
"self.resolver = resolver\nself.ctx = ctx\nself.dependency = dependency",
"try:\n path = self.resolver.resolve()\nexcept WurfError as e:\n self.ctx.logger.debug('Resolve failed in {}:'.format(self.resolver), exc_info=True)\n self.ctx.logger.debug(self.dependency)\n error_message = ''\n if 'current_... | <|body_start_0|>
self.resolver = resolver
self.ctx = ctx
self.dependency = dependency
<|end_body_0|>
<|body_start_1|>
try:
path = self.resolver.resolve()
except WurfError as e:
self.ctx.logger.debug('Resolve failed in {}:'.format(self.resolver), exc_info=... | Try to resolve. | TryResolver | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TryResolver:
"""Try to resolve."""
def __init__(self, resolver, ctx, dependency):
"""Construct an instance. :param resolver: A resolver instance"""
<|body_0|>
def resolve(self):
"""Resolve the dependency. :return: Path to resolved dependency as a string"""
... | stack_v2_sparse_classes_36k_train_033272 | 2,267 | permissive | [
{
"docstring": "Construct an instance. :param resolver: A resolver instance",
"name": "__init__",
"signature": "def __init__(self, resolver, ctx, dependency)"
},
{
"docstring": "Resolve the dependency. :return: Path to resolved dependency as a string",
"name": "resolve",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_011885 | Implement the Python class `TryResolver` described below.
Class description:
Try to resolve.
Method signatures and docstrings:
- def __init__(self, resolver, ctx, dependency): Construct an instance. :param resolver: A resolver instance
- def resolve(self): Resolve the dependency. :return: Path to resolved dependency ... | Implement the Python class `TryResolver` described below.
Class description:
Try to resolve.
Method signatures and docstrings:
- def __init__(self, resolver, ctx, dependency): Construct an instance. :param resolver: A resolver instance
- def resolve(self): Resolve the dependency. :return: Path to resolved dependency ... | ba94d46ce58ac7e936fc45acaca1168ae0d7780b | <|skeleton|>
class TryResolver:
"""Try to resolve."""
def __init__(self, resolver, ctx, dependency):
"""Construct an instance. :param resolver: A resolver instance"""
<|body_0|>
def resolve(self):
"""Resolve the dependency. :return: Path to resolved dependency as a string"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TryResolver:
"""Try to resolve."""
def __init__(self, resolver, ctx, dependency):
"""Construct an instance. :param resolver: A resolver instance"""
self.resolver = resolver
self.ctx = ctx
self.dependency = dependency
def resolve(self):
"""Resolve the dependenc... | the_stack_v2_python_sparse | src/wurf/try_resolver.py | steinwurf/waf | train | 15 |
0b0a299a2615580e74bd93e29d8c0ffeefdc7cfd | [
"serial = ''\n\ndef helper(nd):\n if nd == None:\n return 'None,'\n return str(nd.val) + ',' + helper(nd.left) + helper(nd.right)\nreturn helper(root)",
"lst = data.split(',')\n\ndef helper(lst):\n if lst[0] == 'None':\n lst.pop(0)\n return None\n root = TreeNode(lst[0])\n lst.... | <|body_start_0|>
serial = ''
def helper(nd):
if nd == None:
return 'None,'
return str(nd.val) + ',' + helper(nd.left) + helper(nd.right)
return helper(root)
<|end_body_0|>
<|body_start_1|>
lst = data.split(',')
def helper(lst):
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_033273 | 1,477 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_007511 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | d3e8669f932fc2e22711e8b7590d3365d020e189 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
serial = ''
def helper(nd):
if nd == None:
return 'None,'
return str(nd.val) + ',' + helper(nd.left) + helper(nd.right)
return he... | the_stack_v2_python_sparse | leetcode/297.py | liuweilin17/algorithm | train | 3 | |
0b32d1905a2ab4c74ce78c77a7fa7f90a4140f32 | [
"if Capability.SHELL not in capability:\n return\nfor fact in pwncat.victim.enumerate.iter(typ='system.user.password'):\n progress.update(task, step=str(fact.data))\n yield Technique(fact.data.user.name, self, fact.data, Capability.SHELL)",
"try:\n pwncat.victim.su(technique.user, technique.ident.pass... | <|body_start_0|>
if Capability.SHELL not in capability:
return
for fact in pwncat.victim.enumerate.iter(typ='system.user.password'):
progress.update(task, step=str(fact.data))
yield Technique(fact.data.user.name, self, fact.data, Capability.SHELL)
<|end_body_0|>
<|bo... | Enumerate passwords seen in the pam_sneaky log | Method | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Method:
"""Enumerate passwords seen in the pam_sneaky log"""
def enumerate(self, progress, task, capability: int=Capability.ALL) -> List[Technique]:
"""Enumerate capabilities for this method. :param capability: the requested capabilities :return: a list of techniques implemented by t... | stack_v2_sparse_classes_36k_train_033274 | 1,460 | no_license | [
{
"docstring": "Enumerate capabilities for this method. :param capability: the requested capabilities :return: a list of techniques implemented by this method",
"name": "enumerate",
"signature": "def enumerate(self, progress, task, capability: int=Capability.ALL) -> List[Technique]"
},
{
"docstr... | 2 | stack_v2_sparse_classes_30k_train_012735 | Implement the Python class `Method` described below.
Class description:
Enumerate passwords seen in the pam_sneaky log
Method signatures and docstrings:
- def enumerate(self, progress, task, capability: int=Capability.ALL) -> List[Technique]: Enumerate capabilities for this method. :param capability: the requested ca... | Implement the Python class `Method` described below.
Class description:
Enumerate passwords seen in the pam_sneaky log
Method signatures and docstrings:
- def enumerate(self, progress, task, capability: int=Capability.ALL) -> List[Technique]: Enumerate capabilities for this method. :param capability: the requested ca... | 30e084ab6e8c41fa2f0a43b557b308599eb0bdf3 | <|skeleton|>
class Method:
"""Enumerate passwords seen in the pam_sneaky log"""
def enumerate(self, progress, task, capability: int=Capability.ALL) -> List[Technique]:
"""Enumerate capabilities for this method. :param capability: the requested capabilities :return: a list of techniques implemented by t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Method:
"""Enumerate passwords seen in the pam_sneaky log"""
def enumerate(self, progress, task, capability: int=Capability.ALL) -> List[Technique]:
"""Enumerate capabilities for this method. :param capability: the requested capabilities :return: a list of techniques implemented by this method"""... | the_stack_v2_python_sparse | pwncat/privesc/facts/password.py | tilt41/pwncat | train | 1 |
1456f0a454731e47776e98d47bcd2c7403dbd3a0 | [
"if not x.is_decompressed:\n r = x.buffer\nelse:\n r = x.proto.SerializePartialToString()\nos.environ['JINA_GRPC_SEND_BYTES'] = str(len(r) + int(os.environ.get('JINA_GRPC_SEND_BYTES', 0)))\nreturn r",
"import os\nif x:\n os.environ['JINA_GRPC_RECV_BYTES'] = str(len(x) + int(os.environ.get('JINA_GRPC_RECV... | <|body_start_0|>
if not x.is_decompressed:
r = x.buffer
else:
r = x.proto.SerializePartialToString()
os.environ['JINA_GRPC_SEND_BYTES'] = str(len(r) + int(os.environ.get('JINA_GRPC_SEND_BYTES', 0)))
return r
<|end_body_0|>
<|body_start_1|>
import os
... | Placeholder that delegates the serialization and deserialization to the internal protobuf | SingleDocumentRequestProto | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleDocumentRequestProto:
"""Placeholder that delegates the serialization and deserialization to the internal protobuf"""
def SerializeToString(x: 'SingleDocumentRequest'):
"""# noqa: DAR101 # noqa: DAR102 # noqa: DAR201"""
<|body_0|>
def FromString(x: bytes):
... | stack_v2_sparse_classes_36k_train_033275 | 7,917 | permissive | [
{
"docstring": "# noqa: DAR101 # noqa: DAR102 # noqa: DAR201",
"name": "SerializeToString",
"signature": "def SerializeToString(x: 'SingleDocumentRequest')"
},
{
"docstring": "# noqa: DAR101 # noqa: DAR102 # noqa: DAR201",
"name": "FromString",
"signature": "def FromString(x: bytes)"
}... | 2 | null | Implement the Python class `SingleDocumentRequestProto` described below.
Class description:
Placeholder that delegates the serialization and deserialization to the internal protobuf
Method signatures and docstrings:
- def SerializeToString(x: 'SingleDocumentRequest'): # noqa: DAR101 # noqa: DAR102 # noqa: DAR201
- de... | Implement the Python class `SingleDocumentRequestProto` described below.
Class description:
Placeholder that delegates the serialization and deserialization to the internal protobuf
Method signatures and docstrings:
- def SerializeToString(x: 'SingleDocumentRequest'): # noqa: DAR101 # noqa: DAR102 # noqa: DAR201
- de... | 23c7b8c78fc4ad67d16d83fc0c9f0eae9e935e71 | <|skeleton|>
class SingleDocumentRequestProto:
"""Placeholder that delegates the serialization and deserialization to the internal protobuf"""
def SerializeToString(x: 'SingleDocumentRequest'):
"""# noqa: DAR101 # noqa: DAR102 # noqa: DAR201"""
<|body_0|>
def FromString(x: bytes):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SingleDocumentRequestProto:
"""Placeholder that delegates the serialization and deserialization to the internal protobuf"""
def SerializeToString(x: 'SingleDocumentRequest'):
"""# noqa: DAR101 # noqa: DAR102 # noqa: DAR201"""
if not x.is_decompressed:
r = x.buffer
else... | the_stack_v2_python_sparse | jina/proto/serializer.py | jina-ai/jina | train | 20,687 |
4732692f801f349451e42cb898a0bf1a7de7ade6 | [
"if item is not None and (not isinstance(item, Member)):\n opt, types = is_optional(extract_types(item))\n item = Instance(types, optional=opt)\nself.item = item\nself.set_default_value_mode(DefaultValue.Static, default)\nself.set_validate_mode(Validate.Tuple, item)",
"super(Tuple, self).set_name(name)\nif ... | <|body_start_0|>
if item is not None and (not isinstance(item, Member)):
opt, types = is_optional(extract_types(item))
item = Instance(types, optional=opt)
self.item = item
self.set_default_value_mode(DefaultValue.Static, default)
self.set_validate_mode(Validate.T... | A member which allows tuple values. If item validation is used, then assignment will create a copy of the original tuple before validating the items, since validation may change the item values. | Tuple | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tuple:
"""A member which allows tuple values. If item validation is used, then assignment will create a copy of the original tuple before validating the items, since validation may change the item values."""
def __init__(self, item=None, default=()):
"""Initialize a Tuple. Parameters... | stack_v2_sparse_classes_36k_train_033276 | 2,650 | permissive | [
{
"docstring": "Initialize a Tuple. Parameters ---------- item : Member, type, or tuple of types, optional A member to use for validating the types of items allowed in the tuple. This can also be a type object or a tuple of types, in which case it will be wrapped with an Instance member. If this is not given, n... | 4 | stack_v2_sparse_classes_30k_train_014469 | Implement the Python class `Tuple` described below.
Class description:
A member which allows tuple values. If item validation is used, then assignment will create a copy of the original tuple before validating the items, since validation may change the item values.
Method signatures and docstrings:
- def __init__(sel... | Implement the Python class `Tuple` described below.
Class description:
A member which allows tuple values. If item validation is used, then assignment will create a copy of the original tuple before validating the items, since validation may change the item values.
Method signatures and docstrings:
- def __init__(sel... | 761a52821d8c77b5718216256963682d11599c1e | <|skeleton|>
class Tuple:
"""A member which allows tuple values. If item validation is used, then assignment will create a copy of the original tuple before validating the items, since validation may change the item values."""
def __init__(self, item=None, default=()):
"""Initialize a Tuple. Parameters... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Tuple:
"""A member which allows tuple values. If item validation is used, then assignment will create a copy of the original tuple before validating the items, since validation may change the item values."""
def __init__(self, item=None, default=()):
"""Initialize a Tuple. Parameters ---------- i... | the_stack_v2_python_sparse | atom/tuple.py | nucleic/atom | train | 251 |
0a73713c41da4339c6e53495c366f8f5b837be17 | [
"self.directory = directory\nself.process = None\nself.host = 'localhost'\nself.port = find_free_port(host=self.host)\nself.address = (self.host, self.port)\nself.url = f'http://{self.host}:{self.port}/'",
"os.chdir(directory)\nserver = ThreadingHTTPServer(address, SimpleHTTPRequestHandler)\nserver.serve_forever(... | <|body_start_0|>
self.directory = directory
self.process = None
self.host = 'localhost'
self.port = find_free_port(host=self.host)
self.address = (self.host, self.port)
self.url = f'http://{self.host}:{self.port}/'
<|end_body_0|>
<|body_start_1|>
os.chdir(directo... | Simple HTTP server for testing. Serves files from a directory to http://locahost:port/filename | HttpServer | [
"MIT",
"BSD-2-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HttpServer:
"""Simple HTTP server for testing. Serves files from a directory to http://locahost:port/filename"""
def __init__(self, directory: str):
"""Initialises the server. :param directory: Directory to serve."""
<|body_0|>
def serve_(address, directory):
"""... | stack_v2_sparse_classes_36k_train_033277 | 34,496 | permissive | [
{
"docstring": "Initialises the server. :param directory: Directory to serve.",
"name": "__init__",
"signature": "def __init__(self, directory: str)"
},
{
"docstring": "Entry point for a new process to run HTTP server. :param address: Address (host, port) to bind server to. :param directory: Dir... | 5 | stack_v2_sparse_classes_30k_train_012058 | Implement the Python class `HttpServer` described below.
Class description:
Simple HTTP server for testing. Serves files from a directory to http://locahost:port/filename
Method signatures and docstrings:
- def __init__(self, directory: str): Initialises the server. :param directory: Directory to serve.
- def serve_(... | Implement the Python class `HttpServer` described below.
Class description:
Simple HTTP server for testing. Serves files from a directory to http://locahost:port/filename
Method signatures and docstrings:
- def __init__(self, directory: str): Initialises the server. :param directory: Directory to serve.
- def serve_(... | 64b62cba83110fea60e91506dff4a83ba9931ba9 | <|skeleton|>
class HttpServer:
"""Simple HTTP server for testing. Serves files from a directory to http://locahost:port/filename"""
def __init__(self, directory: str):
"""Initialises the server. :param directory: Directory to serve."""
<|body_0|>
def serve_(address, directory):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HttpServer:
"""Simple HTTP server for testing. Serves files from a directory to http://locahost:port/filename"""
def __init__(self, directory: str):
"""Initialises the server. :param directory: Directory to serve."""
self.directory = directory
self.process = None
self.host... | the_stack_v2_python_sparse | observatory-platform/observatory/platform/utils/test_utils.py | kieranroberts/observatory-platform | train | 0 |
5881273a1498425f88cc95d308f8a8992a76634c | [
"use_numba = engine == 'numba' and numba.numba_available\nif isinstance(prior, str):\n prior = self.prior_map[prior][int(use_numba)]\nif isinstance(prior, type):\n prior = prior(**prior_params)\nself.prior = prior\nif isinstance(obs_likelihood, str):\n obs_likelihood = self.likelihood_map[obs_likelihood]\n... | <|body_start_0|>
use_numba = engine == 'numba' and numba.numba_available
if isinstance(prior, str):
prior = self.prior_map[prior][int(use_numba)]
if isinstance(prior, type):
prior = prior(**prior_params)
self.prior = prior
if isinstance(obs_likelihood, str... | Bayesian offline changepoint detector This is an implementation of [Fear2006]_ based on the one from the `bayesian_changepoint_detection <https://github.com/hildensia/bayesian_changepoint_detection>`_ python package. | BayesOffline | [
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BayesOffline:
"""Bayesian offline changepoint detector This is an implementation of [Fear2006]_ based on the one from the `bayesian_changepoint_detection <https://github.com/hildensia/bayesian_changepoint_detection>`_ python package."""
def __init__(self, prior='const', obs_likelihood='gauss... | stack_v2_sparse_classes_36k_train_033278 | 21,057 | permissive | [
{
"docstring": "Parameters ---------- prior : {\"const\", \"geometric\", \"neg_binomial\"} or prior class, optional Prior probabiltiy. This can either be a string describing the prior or a type or instance of a class implementing the prior, as for example :py:class:`ConstPrior`, :py:class:`GeometricPrior`, or :... | 2 | stack_v2_sparse_classes_30k_train_010548 | Implement the Python class `BayesOffline` described below.
Class description:
Bayesian offline changepoint detector This is an implementation of [Fear2006]_ based on the one from the `bayesian_changepoint_detection <https://github.com/hildensia/bayesian_changepoint_detection>`_ python package.
Method signatures and d... | Implement the Python class `BayesOffline` described below.
Class description:
Bayesian offline changepoint detector This is an implementation of [Fear2006]_ based on the one from the `bayesian_changepoint_detection <https://github.com/hildensia/bayesian_changepoint_detection>`_ python package.
Method signatures and d... | 2f953e553f32118c3ad1f244481e5a0ac6c533f0 | <|skeleton|>
class BayesOffline:
"""Bayesian offline changepoint detector This is an implementation of [Fear2006]_ based on the one from the `bayesian_changepoint_detection <https://github.com/hildensia/bayesian_changepoint_detection>`_ python package."""
def __init__(self, prior='const', obs_likelihood='gauss... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BayesOffline:
"""Bayesian offline changepoint detector This is an implementation of [Fear2006]_ based on the one from the `bayesian_changepoint_detection <https://github.com/hildensia/bayesian_changepoint_detection>`_ python package."""
def __init__(self, prior='const', obs_likelihood='gauss', prior_para... | the_stack_v2_python_sparse | sdt/changepoint/bayes_offline.py | schuetzgroup/sdt-python | train | 31 |
b1bf98d5a2673a7878b261bdf63093cff0a8f234 | [
"obj = self.get_object()\nserializer = self.serializer_class(obj, data=request.data, partial=True, context={'request': request})\nreturn update(serializer)",
"cluster = self.get_object()\ncm.api.delete_cluster(cluster)\nreturn Response(status=status.HTTP_204_NO_CONTENT)"
] | <|body_start_0|>
obj = self.get_object()
serializer = self.serializer_class(obj, data=request.data, partial=True, context={'request': request})
return update(serializer)
<|end_body_0|>
<|body_start_1|>
cluster = self.get_object()
cm.api.delete_cluster(cluster)
return Res... | get: Show cluster | ClusterDetail | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterDetail:
"""get: Show cluster"""
def patch(self, request, *args, **kwargs):
"""Edit cluster"""
<|body_0|>
def delete(self, request, *args, **kwargs):
"""Remove cluster"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
obj = self.get_object()... | stack_v2_sparse_classes_36k_train_033279 | 32,530 | permissive | [
{
"docstring": "Edit cluster",
"name": "patch",
"signature": "def patch(self, request, *args, **kwargs)"
},
{
"docstring": "Remove cluster",
"name": "delete",
"signature": "def delete(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009335 | Implement the Python class `ClusterDetail` described below.
Class description:
get: Show cluster
Method signatures and docstrings:
- def patch(self, request, *args, **kwargs): Edit cluster
- def delete(self, request, *args, **kwargs): Remove cluster | Implement the Python class `ClusterDetail` described below.
Class description:
get: Show cluster
Method signatures and docstrings:
- def patch(self, request, *args, **kwargs): Edit cluster
- def delete(self, request, *args, **kwargs): Remove cluster
<|skeleton|>
class ClusterDetail:
"""get: Show cluster"""
... | e1c67e3041437ad9e17dccc6c95c5ac02184eddb | <|skeleton|>
class ClusterDetail:
"""get: Show cluster"""
def patch(self, request, *args, **kwargs):
"""Edit cluster"""
<|body_0|>
def delete(self, request, *args, **kwargs):
"""Remove cluster"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClusterDetail:
"""get: Show cluster"""
def patch(self, request, *args, **kwargs):
"""Edit cluster"""
obj = self.get_object()
serializer = self.serializer_class(obj, data=request.data, partial=True, context={'request': request})
return update(serializer)
def delete(sel... | the_stack_v2_python_sparse | api/cluster_views.py | amleshkov/adcm | train | 0 |
097673aa070bfc33a82922705b908788a97d3d69 | [
"with get_oss_fuzz_repo() as oss_fuzz_repo:\n repo_man = repo_manager.RepoManager(oss_fuzz_repo)\n repo_man.checkout_pr('refs/pull/3415/merge')\n diff = repo_man.get_git_diff()\n self.assertCountEqual(diff, ['README.md'])",
"with get_oss_fuzz_repo() as oss_fuzz_repo:\n repo_man = repo_manager.RepoM... | <|body_start_0|>
with get_oss_fuzz_repo() as oss_fuzz_repo:
repo_man = repo_manager.RepoManager(oss_fuzz_repo)
repo_man.checkout_pr('refs/pull/3415/merge')
diff = repo_man.get_git_diff()
self.assertCountEqual(diff, ['README.md'])
<|end_body_0|>
<|body_start_1|>
... | Does Integration tests on the checkout_pr method of RepoManager. | CheckoutPrIntegrationTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckoutPrIntegrationTest:
"""Does Integration tests on the checkout_pr method of RepoManager."""
def test_pull_request_exists(self):
"""Tests that a diff is returned when a valid PR is checked out."""
<|body_0|>
def test_checkout_invalid_pull_request(self):
"""T... | stack_v2_sparse_classes_36k_train_033280 | 8,172 | permissive | [
{
"docstring": "Tests that a diff is returned when a valid PR is checked out.",
"name": "test_pull_request_exists",
"signature": "def test_pull_request_exists(self)"
},
{
"docstring": "Tests that the git checkout invalid pull request fails.",
"name": "test_checkout_invalid_pull_request",
... | 2 | null | Implement the Python class `CheckoutPrIntegrationTest` described below.
Class description:
Does Integration tests on the checkout_pr method of RepoManager.
Method signatures and docstrings:
- def test_pull_request_exists(self): Tests that a diff is returned when a valid PR is checked out.
- def test_checkout_invalid_... | Implement the Python class `CheckoutPrIntegrationTest` described below.
Class description:
Does Integration tests on the checkout_pr method of RepoManager.
Method signatures and docstrings:
- def test_pull_request_exists(self): Tests that a diff is returned when a valid PR is checked out.
- def test_checkout_invalid_... | f0275421f84b8f80ee767fb9230134ac97cb687b | <|skeleton|>
class CheckoutPrIntegrationTest:
"""Does Integration tests on the checkout_pr method of RepoManager."""
def test_pull_request_exists(self):
"""Tests that a diff is returned when a valid PR is checked out."""
<|body_0|>
def test_checkout_invalid_pull_request(self):
"""T... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CheckoutPrIntegrationTest:
"""Does Integration tests on the checkout_pr method of RepoManager."""
def test_pull_request_exists(self):
"""Tests that a diff is returned when a valid PR is checked out."""
with get_oss_fuzz_repo() as oss_fuzz_repo:
repo_man = repo_manager.RepoMana... | the_stack_v2_python_sparse | infra/repo_manager_test.py | google/oss-fuzz | train | 9,438 |
1eb20c6e5880eb3fc94782bf89990504d748a0be | [
"self.subject = subject\nself.to_addresses = to_addresses\nif type(context) == dict:\n context = Context(context)\n self.html_content = Template(template).render(context)\nelse:\n self.html_content = template\nself.text_content = mark_safe(strip_tags(self.html_content))\nself.from_address = settings.EMAIL_... | <|body_start_0|>
self.subject = subject
self.to_addresses = to_addresses
if type(context) == dict:
context = Context(context)
self.html_content = Template(template).render(context)
else:
self.html_content = template
self.text_content = mark_saf... | Class for sending emails | Email | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Email:
"""Class for sending emails"""
def __init__(self, subject, to_addresses, template, context=None, from_address=None, cc=None, bcc=None):
"""Initializes an Email object :param subject: Subject of the email :param to_addresses: A list of email addresses :param template: A templat... | stack_v2_sparse_classes_36k_train_033281 | 2,061 | permissive | [
{
"docstring": "Initializes an Email object :param subject: Subject of the email :param to_addresses: A list of email addresses :param template: A template of the email body :param context: A dictionary to render the template variables :param from_address: Sender of the email (email address) :param cc: A list o... | 2 | stack_v2_sparse_classes_30k_train_013876 | Implement the Python class `Email` described below.
Class description:
Class for sending emails
Method signatures and docstrings:
- def __init__(self, subject, to_addresses, template, context=None, from_address=None, cc=None, bcc=None): Initializes an Email object :param subject: Subject of the email :param to_addres... | Implement the Python class `Email` described below.
Class description:
Class for sending emails
Method signatures and docstrings:
- def __init__(self, subject, to_addresses, template, context=None, from_address=None, cc=None, bcc=None): Initializes an Email object :param subject: Subject of the email :param to_addres... | 68ebdec8dd2fe7a4d1c6ad07783e86ea2056ae67 | <|skeleton|>
class Email:
"""Class for sending emails"""
def __init__(self, subject, to_addresses, template, context=None, from_address=None, cc=None, bcc=None):
"""Initializes an Email object :param subject: Subject of the email :param to_addresses: A list of email addresses :param template: A templat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Email:
"""Class for sending emails"""
def __init__(self, subject, to_addresses, template, context=None, from_address=None, cc=None, bcc=None):
"""Initializes an Email object :param subject: Subject of the email :param to_addresses: A list of email addresses :param template: A template of the emai... | the_stack_v2_python_sparse | accounts/mailer/email.py | ADACS-Australia/SS18B-PLasky | train | 1 |
2f873c90398b72884e171a15b29992a4901d405a | [
"verify_index_list(ilo)\nilo.empty_list_check()\nif not repository_exists(ilo.client, repository=repository):\n raise ActionError(f'Cannot snapshot indices to missing repository: {repository}')\nif not name:\n raise MissingArgument('No value for \"name\" provided.')\nself.index_list = ilo\nself.client = ilo.c... | <|body_start_0|>
verify_index_list(ilo)
ilo.empty_list_check()
if not repository_exists(ilo.client, repository=repository):
raise ActionError(f'Cannot snapshot indices to missing repository: {repository}')
if not name:
raise MissingArgument('No value for "name" pr... | Snapshot Action Class Read more about identically named settings at: :py:meth:`elasticsearch.client.SnapshotClient.create` | Snapshot | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Snapshot:
"""Snapshot Action Class Read more about identically named settings at: :py:meth:`elasticsearch.client.SnapshotClient.create`"""
def __init__(self, ilo, repository=None, name=None, ignore_unavailable=False, include_global_state=True, partial=False, wait_for_completion=True, wait_in... | stack_v2_sparse_classes_36k_train_033282 | 21,632 | permissive | [
{
"docstring": ":param ilo: An IndexList Object :param repository: Repository name. :param name: Snapshot name. :param ignore_unavailable: Ignore unavailable shards/indices. :param include_global_state: Store cluster global state with snapshot. :param partial: Do not fail if primary shard is unavailable. :param... | 5 | stack_v2_sparse_classes_30k_val_000845 | Implement the Python class `Snapshot` described below.
Class description:
Snapshot Action Class Read more about identically named settings at: :py:meth:`elasticsearch.client.SnapshotClient.create`
Method signatures and docstrings:
- def __init__(self, ilo, repository=None, name=None, ignore_unavailable=False, include... | Implement the Python class `Snapshot` described below.
Class description:
Snapshot Action Class Read more about identically named settings at: :py:meth:`elasticsearch.client.SnapshotClient.create`
Method signatures and docstrings:
- def __init__(self, ilo, repository=None, name=None, ignore_unavailable=False, include... | b41743a061ad790820affe7acee5f71abe819357 | <|skeleton|>
class Snapshot:
"""Snapshot Action Class Read more about identically named settings at: :py:meth:`elasticsearch.client.SnapshotClient.create`"""
def __init__(self, ilo, repository=None, name=None, ignore_unavailable=False, include_global_state=True, partial=False, wait_for_completion=True, wait_in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Snapshot:
"""Snapshot Action Class Read more about identically named settings at: :py:meth:`elasticsearch.client.SnapshotClient.create`"""
def __init__(self, ilo, repository=None, name=None, ignore_unavailable=False, include_global_state=True, partial=False, wait_for_completion=True, wait_interval=9, max... | the_stack_v2_python_sparse | curator/actions/snapshot.py | volatilemolotov/curator | train | 0 |
e5d1fbd725e3dcfa1fa4c667e06a871641547634 | [
"user = User.objects.create_user(username='some_username', password='some_password', email='some_email@gmail.com')\nProfile.objects.create_player(username='some_username')\ndata = {'username': 'some_username', 'password': 'some_password'}\nresponse = self.client.post(self.url, data)\nself.assertEqual(response.statu... | <|body_start_0|>
user = User.objects.create_user(username='some_username', password='some_password', email='some_email@gmail.com')
Profile.objects.create_player(username='some_username')
data = {'username': 'some_username', 'password': 'some_password'}
response = self.client.post(self.ur... | UserAuthenticationTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserAuthenticationTests:
def test_valid_user_auth(self):
"""Ensure we get token in case of correct credentials"""
<|body_0|>
def test_invalid_user_auth(self):
"""Ensure we do not get token in case of wrong credentials"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_36k_train_033283 | 13,549 | permissive | [
{
"docstring": "Ensure we get token in case of correct credentials",
"name": "test_valid_user_auth",
"signature": "def test_valid_user_auth(self)"
},
{
"docstring": "Ensure we do not get token in case of wrong credentials",
"name": "test_invalid_user_auth",
"signature": "def test_invalid... | 2 | stack_v2_sparse_classes_30k_train_013766 | Implement the Python class `UserAuthenticationTests` described below.
Class description:
Implement the UserAuthenticationTests class.
Method signatures and docstrings:
- def test_valid_user_auth(self): Ensure we get token in case of correct credentials
- def test_invalid_user_auth(self): Ensure we do not get token in... | Implement the Python class `UserAuthenticationTests` described below.
Class description:
Implement the UserAuthenticationTests class.
Method signatures and docstrings:
- def test_valid_user_auth(self): Ensure we get token in case of correct credentials
- def test_invalid_user_auth(self): Ensure we do not get token in... | 9fa31e01c8fc3496f92540081a8c078474d59c0f | <|skeleton|>
class UserAuthenticationTests:
def test_valid_user_auth(self):
"""Ensure we get token in case of correct credentials"""
<|body_0|>
def test_invalid_user_auth(self):
"""Ensure we do not get token in case of wrong credentials"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserAuthenticationTests:
def test_valid_user_auth(self):
"""Ensure we get token in case of correct credentials"""
user = User.objects.create_user(username='some_username', password='some_password', email='some_email@gmail.com')
Profile.objects.create_player(username='some_username')
... | the_stack_v2_python_sparse | player/tests.py | apoorvaeternity/DirectMe | train | 1 | |
be05ee74f5be5b29e91e0a7bf236e9a82e8df98a | [
"with git_utils.NewGitCheckout(repository=LOCAL_REPO) as checkout:\n filepath = os.path.join(checkout.root, REPO_FILE)\n self.assertTrue(os.path.exists(filepath), 'file %s should exist' % filepath)\nself.assertFalse(os.path.exists(filepath), 'file %s should not exist' % filepath)",
"with git_utils.NewGitChe... | <|body_start_0|>
with git_utils.NewGitCheckout(repository=LOCAL_REPO) as checkout:
filepath = os.path.join(checkout.root, REPO_FILE)
self.assertTrue(os.path.exists(filepath), 'file %s should exist' % filepath)
self.assertFalse(os.path.exists(filepath), 'file %s should not exist' ... | NewGitCheckoutTest | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewGitCheckoutTest:
def test_defaults(self):
"""Test NewGitCheckout created using default parameters."""
<|body_0|>
def test_remote(self):
"""Test NewGitCheckout with a remote repo. This makes requests across the network, so we may not want to run it very often..."""... | stack_v2_sparse_classes_36k_train_033284 | 4,015 | permissive | [
{
"docstring": "Test NewGitCheckout created using default parameters.",
"name": "test_defaults",
"signature": "def test_defaults(self)"
},
{
"docstring": "Test NewGitCheckout with a remote repo. This makes requests across the network, so we may not want to run it very often...",
"name": "tes... | 4 | stack_v2_sparse_classes_30k_train_019968 | Implement the Python class `NewGitCheckoutTest` described below.
Class description:
Implement the NewGitCheckoutTest class.
Method signatures and docstrings:
- def test_defaults(self): Test NewGitCheckout created using default parameters.
- def test_remote(self): Test NewGitCheckout with a remote repo. This makes req... | Implement the Python class `NewGitCheckoutTest` described below.
Class description:
Implement the NewGitCheckoutTest class.
Method signatures and docstrings:
- def test_defaults(self): Test NewGitCheckout created using default parameters.
- def test_remote(self): Test NewGitCheckout with a remote repo. This makes req... | 47dbb2ff9ae01305b190f409ccea00b3b4f0bc79 | <|skeleton|>
class NewGitCheckoutTest:
def test_defaults(self):
"""Test NewGitCheckout created using default parameters."""
<|body_0|>
def test_remote(self):
"""Test NewGitCheckout with a remote repo. This makes requests across the network, so we may not want to run it very often..."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NewGitCheckoutTest:
def test_defaults(self):
"""Test NewGitCheckout created using default parameters."""
with git_utils.NewGitCheckout(repository=LOCAL_REPO) as checkout:
filepath = os.path.join(checkout.root, REPO_FILE)
self.assertTrue(os.path.exists(filepath), 'file %... | the_stack_v2_python_sparse | externals/skia/common/py/utils/git_utils_manualtest.py | mono/linux-packaging-skiasharp | train | 1 | |
3e4df263d8590c3e383f063d4a4d066555a3cb44 | [
"tau_mat = np.zeros_like(self.connectivity)\nJ_mat = np.zeros_like(self.connectivity)\nfor col, mass_from in enumerate(self.masses):\n tau_mat[:, col] = mass_from.params[f'tau_s{mass_from.mass_type.lower()[0]}']\n for row, mass_to in enumerate(self.masses):\n J_mat[row, col] = mass_to.params[f'J{mass_t... | <|body_start_0|>
tau_mat = np.zeros_like(self.connectivity)
J_mat = np.zeros_like(self.connectivity)
for col, mass_from in enumerate(self.masses):
tau_mat[:, col] = mass_from.params[f'tau_s{mass_from.mass_type.lower()[0]}']
for row, mass_to in enumerate(self.masses):
... | Default ALN network node with 1 excitatory (featuring adaptive current) and 1 inhibitory population. | ALNNode | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ALNNode:
"""Default ALN network node with 1 excitatory (featuring adaptive current) and 1 inhibitory population."""
def _rescale_connectivity(self):
"""Rescale connection strengths for ALN. Should work also for ALN nodes with arbitrary number of masses of any type."""
<|body_... | stack_v2_sparse_classes_36k_train_033285 | 35,756 | permissive | [
{
"docstring": "Rescale connection strengths for ALN. Should work also for ALN nodes with arbitrary number of masses of any type.",
"name": "_rescale_connectivity",
"signature": "def _rescale_connectivity(self)"
},
{
"docstring": ":param exc_params: parameters for the excitatory mass :type exc_p... | 4 | stack_v2_sparse_classes_30k_train_005578 | Implement the Python class `ALNNode` described below.
Class description:
Default ALN network node with 1 excitatory (featuring adaptive current) and 1 inhibitory population.
Method signatures and docstrings:
- def _rescale_connectivity(self): Rescale connection strengths for ALN. Should work also for ALN nodes with a... | Implement the Python class `ALNNode` described below.
Class description:
Default ALN network node with 1 excitatory (featuring adaptive current) and 1 inhibitory population.
Method signatures and docstrings:
- def _rescale_connectivity(self): Rescale connection strengths for ALN. Should work also for ALN nodes with a... | bec8fbc5ffa7c3b45a266e21549cf392a6263136 | <|skeleton|>
class ALNNode:
"""Default ALN network node with 1 excitatory (featuring adaptive current) and 1 inhibitory population."""
def _rescale_connectivity(self):
"""Rescale connection strengths for ALN. Should work also for ALN nodes with arbitrary number of masses of any type."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ALNNode:
"""Default ALN network node with 1 excitatory (featuring adaptive current) and 1 inhibitory population."""
def _rescale_connectivity(self):
"""Rescale connection strengths for ALN. Should work also for ALN nodes with arbitrary number of masses of any type."""
tau_mat = np.zeros_l... | the_stack_v2_python_sparse | neurolib/models/multimodel/builder/aln.py | neurolib-dev/neurolib | train | 363 |
377d65b66bb116bae6f4b6858fd211df106ba5de | [
"username = self.cleaned_data.get('username')\nif not set(username).issubset('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'):\n raise forms.ValidationError(_('That username has invalid characters. The valid values are letters, numbers and underscore.'))\nif User.objects.filter(username__iexact... | <|body_start_0|>
username = self.cleaned_data.get('username')
if not set(username).issubset('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'):
raise forms.ValidationError(_('That username has invalid characters. The valid values are letters, numbers and underscore.'))
... | RegistrationForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrationForm:
def clean_username(self):
"""Verify that the username isn't already registered"""
<|body_0|>
def clean(self):
"""Verify that the 2 passwords fields are equal"""
<|body_1|>
def clean_email(self):
"""Verify that the email exists""... | stack_v2_sparse_classes_36k_train_033286 | 7,396 | no_license | [
{
"docstring": "Verify that the username isn't already registered",
"name": "clean_username",
"signature": "def clean_username(self)"
},
{
"docstring": "Verify that the 2 passwords fields are equal",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "Verify that t... | 3 | null | Implement the Python class `RegistrationForm` described below.
Class description:
Implement the RegistrationForm class.
Method signatures and docstrings:
- def clean_username(self): Verify that the username isn't already registered
- def clean(self): Verify that the 2 passwords fields are equal
- def clean_email(self... | Implement the Python class `RegistrationForm` described below.
Class description:
Implement the RegistrationForm class.
Method signatures and docstrings:
- def clean_username(self): Verify that the username isn't already registered
- def clean(self): Verify that the 2 passwords fields are equal
- def clean_email(self... | 90b2bb72c2bab9dfea0c0837971a625bc6880630 | <|skeleton|>
class RegistrationForm:
def clean_username(self):
"""Verify that the username isn't already registered"""
<|body_0|>
def clean(self):
"""Verify that the 2 passwords fields are equal"""
<|body_1|>
def clean_email(self):
"""Verify that the email exists""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegistrationForm:
def clean_username(self):
"""Verify that the username isn't already registered"""
username = self.cleaned_data.get('username')
if not set(username).issubset('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'):
raise forms.ValidationError(_('... | the_stack_v2_python_sparse | film20/userprofile/forms.py | manlan2/filmaster | train | 1 | |
f86d102d5d66e59c6f41a664a2ca48a3920d5eb0 | [
"if 1 == ver:\n return True\nelse:\n return False",
"if isinstance(data, SerializableObject) is False:\n raise UnsupportedTypeException()\ndataStream = ApplicationSerializer.ApplicationSerializer.serialize(data, writeMeta=True)\nDS = DigitalSignature(dataStream)\nDS.sign()\ndsStream = DS.serialize()\ncrc... | <|body_start_0|>
if 1 == ver:
return True
else:
return False
<|end_body_0|>
<|body_start_1|>
if isinstance(data, SerializableObject) is False:
raise UnsupportedTypeException()
dataStream = ApplicationSerializer.ApplicationSerializer.serialize(data, wr... | Description: An instance of this class is used to contruct/deconstruct messages sent to and received from the Lynx | MessageFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MessageFactory:
"""Description: An instance of this class is used to contruct/deconstruct messages sent to and received from the Lynx"""
def supportsMsgVersion(ver):
"""Description: This method validates the version information Arguments: ver (in, int) The version to validate Returns... | stack_v2_sparse_classes_36k_train_033287 | 3,196 | no_license | [
{
"docstring": "Description: This method validates the version information Arguments: ver (in, int) The version to validate Returns: bool True==valid version",
"name": "supportsMsgVersion",
"signature": "def supportsMsgVersion(ver)"
},
{
"docstring": "Description: This method serializes the data... | 3 | stack_v2_sparse_classes_30k_train_000329 | Implement the Python class `MessageFactory` described below.
Class description:
Description: An instance of this class is used to contruct/deconstruct messages sent to and received from the Lynx
Method signatures and docstrings:
- def supportsMsgVersion(ver): Description: This method validates the version information... | Implement the Python class `MessageFactory` described below.
Class description:
Description: An instance of this class is used to contruct/deconstruct messages sent to and received from the Lynx
Method signatures and docstrings:
- def supportsMsgVersion(ver): Description: This method validates the version information... | bdeeb78b58466ec8696d4fadb05051c1b06ef25e | <|skeleton|>
class MessageFactory:
"""Description: An instance of this class is used to contruct/deconstruct messages sent to and received from the Lynx"""
def supportsMsgVersion(ver):
"""Description: This method validates the version information Arguments: ver (in, int) The version to validate Returns... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MessageFactory:
"""Description: An instance of this class is used to contruct/deconstruct messages sent to and received from the Lynx"""
def supportsMsgVersion(ver):
"""Description: This method validates the version information Arguments: ver (in, int) The version to validate Returns: bool True==... | the_stack_v2_python_sparse | src/DataTypes/MessageFactory.py | philliptay/nuclear-detection | train | 0 |
3806dcfef52cf1767ec3ff04b9e719c0cc249530 | [
"super().__init__(config)\nself.param_name = param_name\nself.from_address = from_address\nself.to_address = to_address\nself.smtp_host = smtp_host\nself.smtp_port = smtp_port\nself.smtp_timeout = smtp_timeout\nwith smtplib.SMTP(self.smtp_host, self.smtp_port, timeout=self.smtp_timeout) as server:\n server.start... | <|body_start_0|>
super().__init__(config)
self.param_name = param_name
self.from_address = from_address
self.to_address = to_address
self.smtp_host = smtp_host
self.smtp_port = smtp_port
self.smtp_timeout = smtp_timeout
with smtplib.SMTP(self.smtp_host, se... | EventListener subclass that can be used to send e-mail notification about various events. | EmailListener | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailListener:
"""EventListener subclass that can be used to send e-mail notification about various events."""
def __init__(self, config, event, param_name, from_address, to_address, smtp_host, smtp_port, smtp_timeout=5):
""":param config: ConfigParser object containing information a... | stack_v2_sparse_classes_36k_train_033288 | 3,791 | permissive | [
{
"docstring": ":param config: ConfigParser object containing information about the fuzz session. :param event: The name of the event to send notification about. :param param_name: The name of the event's parameter containing the information to send. :param from_address: E-mail address to send notifications fro... | 2 | stack_v2_sparse_classes_30k_train_002737 | Implement the Python class `EmailListener` described below.
Class description:
EventListener subclass that can be used to send e-mail notification about various events.
Method signatures and docstrings:
- def __init__(self, config, event, param_name, from_address, to_address, smtp_host, smtp_port, smtp_timeout=5): :p... | Implement the Python class `EmailListener` described below.
Class description:
EventListener subclass that can be used to send e-mail notification about various events.
Method signatures and docstrings:
- def __init__(self, config, event, param_name, from_address, to_address, smtp_host, smtp_port, smtp_timeout=5): :p... | 06abd0da776e217192417b167e9ed8ae09909dab | <|skeleton|>
class EmailListener:
"""EventListener subclass that can be used to send e-mail notification about various events."""
def __init__(self, config, event, param_name, from_address, to_address, smtp_host, smtp_port, smtp_timeout=5):
""":param config: ConfigParser object containing information a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmailListener:
"""EventListener subclass that can be used to send e-mail notification about various events."""
def __init__(self, config, event, param_name, from_address, to_address, smtp_host, smtp_port, smtp_timeout=5):
""":param config: ConfigParser object containing information about the fuzz... | the_stack_v2_python_sparse | fuzzinator/listener/email_listener.py | renatahodovan/fuzzinator | train | 208 |
2d8c1873ca83573a9de3262aa0f07de49608b223 | [
"self._position = _format_LatLng(lat, lng, precision)\nself._text = text\ncolor = kwargs.get('color')\nself._color = _get_hex_color(color) if color is not None else None\nself._icon = _get_embeddable_image(_COLOR_ICON_PATH % 'clear')\nself._font_size = kwargs.get('font_size')",
"w.write('new google.maps.Marker({'... | <|body_start_0|>
self._position = _format_LatLng(lat, lng, precision)
self._text = text
color = kwargs.get('color')
self._color = _get_hex_color(color) if color is not None else None
self._icon = _get_embeddable_image(_COLOR_ICON_PATH % 'clear')
self._font_size = kwargs.g... | _Text | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Text:
def __init__(self, lat, lng, text, precision, **kwargs):
"""Args: lat (float): Latitude of the text label. lng (float): Longitude of the text label. text (str): Text to display. precision (int): Number of digits after the decimal to round to for lat/lng values. Optional: Args: col... | stack_v2_sparse_classes_36k_train_033289 | 1,692 | permissive | [
{
"docstring": "Args: lat (float): Latitude of the text label. lng (float): Longitude of the text label. text (str): Text to display. precision (int): Number of digits after the decimal to round to for lat/lng values. Optional: Args: color (str): Text color. Can be hex ('#00FFFF'), named ('cyan'), or matplotlib... | 2 | stack_v2_sparse_classes_30k_train_008076 | Implement the Python class `_Text` described below.
Class description:
Implement the _Text class.
Method signatures and docstrings:
- def __init__(self, lat, lng, text, precision, **kwargs): Args: lat (float): Latitude of the text label. lng (float): Longitude of the text label. text (str): Text to display. precision... | Implement the Python class `_Text` described below.
Class description:
Implement the _Text class.
Method signatures and docstrings:
- def __init__(self, lat, lng, text, precision, **kwargs): Args: lat (float): Latitude of the text label. lng (float): Longitude of the text label. text (str): Text to display. precision... | 8654a5a370b5ec309e1282c457eaf375c3dcb4bb | <|skeleton|>
class _Text:
def __init__(self, lat, lng, text, precision, **kwargs):
"""Args: lat (float): Latitude of the text label. lng (float): Longitude of the text label. text (str): Text to display. precision (int): Number of digits after the decimal to round to for lat/lng values. Optional: Args: col... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _Text:
def __init__(self, lat, lng, text, precision, **kwargs):
"""Args: lat (float): Latitude of the text label. lng (float): Longitude of the text label. text (str): Text to display. precision (int): Number of digits after the decimal to round to for lat/lng values. Optional: Args: color (str): Text... | the_stack_v2_python_sparse | gmplot/drawables/text.py | fishke22/gmplot | train | 0 | |
6a19eb1578045424d1fb592aaa645ad566ff610c | [
"if root is None:\n return True\nself.__dfs(root)\nreturn self.flag",
"if node is None:\n return 0\nleft = self.__dfs(node.left)\nright = self.__dfs(node.right)\nif abs(left - right) > 1:\n self.flag = 0\nreturn max(left, right) + 1"
] | <|body_start_0|>
if root is None:
return True
self.__dfs(root)
return self.flag
<|end_body_0|>
<|body_start_1|>
if node is None:
return 0
left = self.__dfs(node.left)
right = self.__dfs(node.right)
if abs(left - right) > 1:
sel... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isBalanced(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def __dfs(self, node):
"""返回以 root 为根的二叉树的高度,如果左右子树其中之一不是 AVL ,则返回 -1 :param node: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root is None:
... | stack_v2_sparse_classes_36k_train_033290 | 871 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isBalanced",
"signature": "def isBalanced(self, root)"
},
{
"docstring": "返回以 root 为根的二叉树的高度,如果左右子树其中之一不是 AVL ,则返回 -1 :param node: :return:",
"name": "__dfs",
"signature": "def __dfs(self, node)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009265 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isBalanced(self, root): :type root: TreeNode :rtype: bool
- def __dfs(self, node): 返回以 root 为根的二叉树的高度,如果左右子树其中之一不是 AVL ,则返回 -1 :param node: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isBalanced(self, root): :type root: TreeNode :rtype: bool
- def __dfs(self, node): 返回以 root 为根的二叉树的高度,如果左右子树其中之一不是 AVL ,则返回 -1 :param node: :return:
<|skeleton|>
class Solut... | 4c57462cbaa365b07341bb6ed20d21a4f0389f33 | <|skeleton|>
class Solution:
def isBalanced(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def __dfs(self, node):
"""返回以 root 为根的二叉树的高度,如果左右子树其中之一不是 AVL ,则返回 -1 :param node: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isBalanced(self, root):
""":type root: TreeNode :rtype: bool"""
if root is None:
return True
self.__dfs(root)
return self.flag
def __dfs(self, node):
"""返回以 root 为根的二叉树的高度,如果左右子树其中之一不是 AVL ,则返回 -1 :param node: :return:"""
if node i... | the_stack_v2_python_sparse | codes/python/55_2-平衡二叉树-1.py | lxyxl0216/sword-for-offer-solution | train | 0 | |
dc1bb1cec63d46f9e53281a8bdc2708d847f2f3e | [
"is_admin = False\nif api.user.is_logged_in():\n is_admin = api.user.get_user().get('admin', False)\nsettings = api.config.get_settings()\nif not is_admin:\n return jsonify({'enable_captcha': settings['captcha']['enable_captcha'], 'reCAPTCHA_public_key': settings['captcha']['reCAPTCHA_public_key'], 'email_ver... | <|body_start_0|>
is_admin = False
if api.user.is_logged_in():
is_admin = api.user.get_user().get('admin', False)
settings = api.config.get_settings()
if not is_admin:
return jsonify({'enable_captcha': settings['captcha']['enable_captcha'], 'reCAPTCHA_public_key': ... | Get or modify the current settings. | Settings | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Settings:
"""Get or modify the current settings."""
def get(self):
"""Get the current settings. Admins get everything, non-admins only get registration/login related params."""
<|body_0|>
def patch(self):
"""Update settings."""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_033291 | 1,854 | permissive | [
{
"docstring": "Get the current settings. Admins get everything, non-admins only get registration/login related params.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Update settings.",
"name": "patch",
"signature": "def patch(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000730 | Implement the Python class `Settings` described below.
Class description:
Get or modify the current settings.
Method signatures and docstrings:
- def get(self): Get the current settings. Admins get everything, non-admins only get registration/login related params.
- def patch(self): Update settings. | Implement the Python class `Settings` described below.
Class description:
Get or modify the current settings.
Method signatures and docstrings:
- def get(self): Get the current settings. Admins get everything, non-admins only get registration/login related params.
- def patch(self): Update settings.
<|skeleton|>
cla... | 468035038afe00c6e7842b7e68ec45355ee1a224 | <|skeleton|>
class Settings:
"""Get or modify the current settings."""
def get(self):
"""Get the current settings. Admins get everything, non-admins only get registration/login related params."""
<|body_0|>
def patch(self):
"""Update settings."""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Settings:
"""Get or modify the current settings."""
def get(self):
"""Get the current settings. Admins get everything, non-admins only get registration/login related params."""
is_admin = False
if api.user.is_logged_in():
is_admin = api.user.get_user().get('admin', Fal... | the_stack_v2_python_sparse | picoCTF-web/api/apps/v1/settings.py | zxc135781/picoCTF | train | 1 |
e7f2bdf4ed29a2a57c82c75843a286abf2086bd4 | [
"send_mock = self.PatchObject(alerts.SmtpServer, 'Send')\nalerts.SendEmail('mail', 'root@localhost')\nself.assertEqual(send_mock.call_count, 1)",
"send_mock = self.PatchObject(alerts.GmailServer, 'Send')\nalerts.SendEmail('mail', 'root@localhost', server=alerts.GmailServer(token_cache_file='fakefile'))\nself.asse... | <|body_start_0|>
send_mock = self.PatchObject(alerts.SmtpServer, 'Send')
alerts.SendEmail('mail', 'root@localhost')
self.assertEqual(send_mock.call_count, 1)
<|end_body_0|>
<|body_start_1|>
send_mock = self.PatchObject(alerts.GmailServer, 'Send')
alerts.SendEmail('mail', 'root@l... | Tests for SendEmail. | SendEmailTest | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SendEmailTest:
"""Tests for SendEmail."""
def testSmtp(self):
"""Smtp sanity check."""
<|body_0|>
def testGmail(self):
"""Gmail sanity check."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
send_mock = self.PatchObject(alerts.SmtpServer, 'Send')... | stack_v2_sparse_classes_36k_train_033292 | 6,312 | permissive | [
{
"docstring": "Smtp sanity check.",
"name": "testSmtp",
"signature": "def testSmtp(self)"
},
{
"docstring": "Gmail sanity check.",
"name": "testGmail",
"signature": "def testGmail(self)"
}
] | 2 | null | Implement the Python class `SendEmailTest` described below.
Class description:
Tests for SendEmail.
Method signatures and docstrings:
- def testSmtp(self): Smtp sanity check.
- def testGmail(self): Gmail sanity check. | Implement the Python class `SendEmailTest` described below.
Class description:
Tests for SendEmail.
Method signatures and docstrings:
- def testSmtp(self): Smtp sanity check.
- def testGmail(self): Gmail sanity check.
<|skeleton|>
class SendEmailTest:
"""Tests for SendEmail."""
def testSmtp(self):
"... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class SendEmailTest:
"""Tests for SendEmail."""
def testSmtp(self):
"""Smtp sanity check."""
<|body_0|>
def testGmail(self):
"""Gmail sanity check."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SendEmailTest:
"""Tests for SendEmail."""
def testSmtp(self):
"""Smtp sanity check."""
send_mock = self.PatchObject(alerts.SmtpServer, 'Send')
alerts.SendEmail('mail', 'root@localhost')
self.assertEqual(send_mock.call_count, 1)
def testGmail(self):
"""Gmail sa... | the_stack_v2_python_sparse | third_party/chromite/lib/alerts_unittest.py | metux/chromium-suckless | train | 5 |
838af8ab1f9b343943eea58f3354c3e2c5176188 | [
"if n == 1:\n return 0\ndp = [0] * (n + 1)\ndp[2] = 1\nfor i in range(3, n + 1):\n if i % 2:\n dp[i] = min(dp[(i + 1) // 2], dp[(i - 1) // 2]) + 2\n else:\n dp[i] = dp[i // 2] + 1\nreturn dp[n]",
"def help(n, mem):\n if n in mem:\n return mem[n]\n if n == 1:\n mem[n] = 0... | <|body_start_0|>
if n == 1:
return 0
dp = [0] * (n + 1)
dp[2] = 1
for i in range(3, n + 1):
if i % 2:
dp[i] = min(dp[(i + 1) // 2], dp[(i - 1) // 2]) + 2
else:
dp[i] = dp[i // 2] + 1
return dp[n]
<|end_body_0|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def integerReplacement1(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def integerReplacement(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n == 1:
return 0
dp = [0] * (n ... | stack_v2_sparse_classes_36k_train_033293 | 846 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "integerReplacement1",
"signature": "def integerReplacement1(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "integerReplacement",
"signature": "def integerReplacement(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019533 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def integerReplacement1(self, n): :type n: int :rtype: int
- def integerReplacement(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def integerReplacement1(self, n): :type n: int :rtype: int
- def integerReplacement(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def integerReplacement1(... | e5b018493bbd12edcdcd0434f35d9c358106d391 | <|skeleton|>
class Solution:
def integerReplacement1(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def integerReplacement(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def integerReplacement1(self, n):
""":type n: int :rtype: int"""
if n == 1:
return 0
dp = [0] * (n + 1)
dp[2] = 1
for i in range(3, n + 1):
if i % 2:
dp[i] = min(dp[(i + 1) // 2], dp[(i - 1) // 2]) + 2
else:
... | the_stack_v2_python_sparse | py/leetcode/397.py | wfeng1991/learnpy | train | 0 | |
45b4d46701426d54dd08ef770c37d36b38e616bc | [
"self._subject_tree = Tree(request.subject)\nself._resource_tree = Tree(request.resource)\nself._action_tree = Tree(request.action)\nself._context_tree = Tree(request.context)\nself._attribute_values_cache = {'subject': {}, 'resource': {}, 'action': {}, 'context': {}}",
"try:\n attribute_tree = getattr(self, '... | <|body_start_0|>
self._subject_tree = Tree(request.subject)
self._resource_tree = Tree(request.resource)
self._action_tree = Tree(request.action)
self._context_tree = Tree(request.context)
self._attribute_values_cache = {'subject': {}, 'resource': {}, 'action': {}, 'context': {}}... | Request attribute provider | RequestAttributeProvider | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequestAttributeProvider:
"""Request attribute provider"""
def __init__(self, request: AccessRequest):
"""Initialize attribute provider :param request: authorization request object"""
<|body_0|>
def get_attribute_value(self, ace, attribute_path, ctx):
"""Get valu... | stack_v2_sparse_classes_36k_train_033294 | 2,220 | permissive | [
{
"docstring": "Initialize attribute provider :param request: authorization request object",
"name": "__init__",
"signature": "def __init__(self, request: AccessRequest)"
},
{
"docstring": "Get value for given access control element and attribute path. :param ace: access control element :param a... | 2 | stack_v2_sparse_classes_30k_train_009442 | Implement the Python class `RequestAttributeProvider` described below.
Class description:
Request attribute provider
Method signatures and docstrings:
- def __init__(self, request: AccessRequest): Initialize attribute provider :param request: authorization request object
- def get_attribute_value(self, ace, attribute... | Implement the Python class `RequestAttributeProvider` described below.
Class description:
Request attribute provider
Method signatures and docstrings:
- def __init__(self, request: AccessRequest): Initialize attribute provider :param request: authorization request object
- def get_attribute_value(self, ace, attribute... | 8a44107a00f712bbb9c6cd3ecad155ef696cf035 | <|skeleton|>
class RequestAttributeProvider:
"""Request attribute provider"""
def __init__(self, request: AccessRequest):
"""Initialize attribute provider :param request: authorization request object"""
<|body_0|>
def get_attribute_value(self, ace, attribute_path, ctx):
"""Get valu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RequestAttributeProvider:
"""Request attribute provider"""
def __init__(self, request: AccessRequest):
"""Initialize attribute provider :param request: authorization request object"""
self._subject_tree = Tree(request.subject)
self._resource_tree = Tree(request.resource)
s... | the_stack_v2_python_sparse | py_abac/provider/request.py | phenobarbital/py-abac | train | 0 |
e26b70ca73c3d54d13874a1160c228955848705a | [
"body = super().to_dict()\nbody.update({'spec': {'replicas': replica_count}})\nLOGGER.info(f'Set deployment replicas: {replica_count}')\nreturn self.update(resource_dict=body)",
"LOGGER.info(f'Wait for {self.kind} {self.name} to be deployed: {deployed}')\nsamples = TimeoutSampler(wait_timeout=timeout, sleep=1, ex... | <|body_start_0|>
body = super().to_dict()
body.update({'spec': {'replicas': replica_count}})
LOGGER.info(f'Set deployment replicas: {replica_count}')
return self.update(resource_dict=body)
<|end_body_0|>
<|body_start_1|>
LOGGER.info(f'Wait for {self.kind} {self.name} to be deplo... | OpenShift Deployment object. | Deployment | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Deployment:
"""OpenShift Deployment object."""
def scale_replicas(self, replica_count=int):
"""Update replicas in deployment. Args: replica_count (int): Number of replicas. Returns: Deployment is updated successfully"""
<|body_0|>
def wait_for_replicas(self, deployed=Tru... | stack_v2_sparse_classes_36k_train_033295 | 1,905 | permissive | [
{
"docstring": "Update replicas in deployment. Args: replica_count (int): Number of replicas. Returns: Deployment is updated successfully",
"name": "scale_replicas",
"signature": "def scale_replicas(self, replica_count=int)"
},
{
"docstring": "Wait until all replicas are updated. Args: deployed ... | 2 | stack_v2_sparse_classes_30k_train_019331 | Implement the Python class `Deployment` described below.
Class description:
OpenShift Deployment object.
Method signatures and docstrings:
- def scale_replicas(self, replica_count=int): Update replicas in deployment. Args: replica_count (int): Number of replicas. Returns: Deployment is updated successfully
- def wait... | Implement the Python class `Deployment` described below.
Class description:
OpenShift Deployment object.
Method signatures and docstrings:
- def scale_replicas(self, replica_count=int): Update replicas in deployment. Args: replica_count (int): Number of replicas. Returns: Deployment is updated successfully
- def wait... | 01aa3234fc6333868222736d8f42e27943edb47a | <|skeleton|>
class Deployment:
"""OpenShift Deployment object."""
def scale_replicas(self, replica_count=int):
"""Update replicas in deployment. Args: replica_count (int): Number of replicas. Returns: Deployment is updated successfully"""
<|body_0|>
def wait_for_replicas(self, deployed=Tru... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Deployment:
"""OpenShift Deployment object."""
def scale_replicas(self, replica_count=int):
"""Update replicas in deployment. Args: replica_count (int): Number of replicas. Returns: Deployment is updated successfully"""
body = super().to_dict()
body.update({'spec': {'replicas': re... | the_stack_v2_python_sparse | ocp_resources/deployment.py | ibesso-rh/openshift-python-wrapper | train | 0 |
bc027b46af6c04f68164a900f5f4e51275a70936 | [
"self.num_steps_in_epoch = num_steps_in_epoch\nself.base_lr = base_lr\nself.num_epochs = num_epochs\nself.warmup_epochs = warmup_epochs\nself.warmup_lr = warmup_lr",
"num_steps_in_epoch = lr_scheduler_config.get('num_steps_in_epoch', 0)\nbase_lr = lr_scheduler_config.get('base_lr', 0.00034)\nnum_epochs = lr_sched... | <|body_start_0|>
self.num_steps_in_epoch = num_steps_in_epoch
self.base_lr = base_lr
self.num_epochs = num_epochs
self.warmup_epochs = warmup_epochs
self.warmup_lr = warmup_lr
<|end_body_0|>
<|body_start_1|>
num_steps_in_epoch = lr_scheduler_config.get('num_steps_in_epoc... | Storage class for LR Scheduler parameters | LRSchedulerParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRSchedulerParams:
"""Storage class for LR Scheduler parameters"""
def __init__(self, num_steps_in_epoch: float, base_lr: float=0.00034, num_epochs: float=0, warmup_epochs: float=0, warmup_lr: float=0):
"""Initializes storage class for learning rate scheduler parameters :param num_st... | stack_v2_sparse_classes_36k_train_033296 | 8,170 | permissive | [
{
"docstring": "Initializes storage class for learning rate scheduler parameters :param num_steps_in_epoch: :param base_lr: :param num_epochs: :param warmup_epochs: :param warmup_lr:",
"name": "__init__",
"signature": "def __init__(self, num_steps_in_epoch: float, base_lr: float=0.00034, num_epochs: flo... | 2 | null | Implement the Python class `LRSchedulerParams` described below.
Class description:
Storage class for LR Scheduler parameters
Method signatures and docstrings:
- def __init__(self, num_steps_in_epoch: float, base_lr: float=0.00034, num_epochs: float=0, warmup_epochs: float=0, warmup_lr: float=0): Initializes storage c... | Implement the Python class `LRSchedulerParams` described below.
Class description:
Storage class for LR Scheduler parameters
Method signatures and docstrings:
- def __init__(self, num_steps_in_epoch: float, base_lr: float=0.00034, num_epochs: float=0, warmup_epochs: float=0, warmup_lr: float=0): Initializes storage c... | c027c8b43c4865d46b8de01d8350dd338ec5a874 | <|skeleton|>
class LRSchedulerParams:
"""Storage class for LR Scheduler parameters"""
def __init__(self, num_steps_in_epoch: float, base_lr: float=0.00034, num_epochs: float=0, warmup_epochs: float=0, warmup_lr: float=0):
"""Initializes storage class for learning rate scheduler parameters :param num_st... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRSchedulerParams:
"""Storage class for LR Scheduler parameters"""
def __init__(self, num_steps_in_epoch: float, base_lr: float=0.00034, num_epochs: float=0, warmup_epochs: float=0, warmup_lr: float=0):
"""Initializes storage class for learning rate scheduler parameters :param num_steps_in_epoch:... | the_stack_v2_python_sparse | nncf/experimental/torch/nas/bootstrapNAS/training/lr_scheduler.py | openvinotoolkit/nncf | train | 558 |
41c564476a691882722d76ce95c4ce3b2ac89e15 | [
"args = get_topic_parser.parse_args()\n_id = args['_id']\npage_num = args['page_num']\nif _id:\n return marshal(get_topic_or_404(_id), topic_object_field)\nif not _id and page_num:\n topic_pagination = get_topics_pagination(page_num)\n return marshal(topic_pagination, topic_pagination_field)\nabort(400, me... | <|body_start_0|>
args = get_topic_parser.parse_args()
_id = args['_id']
page_num = args['page_num']
if _id:
return marshal(get_topic_or_404(_id), topic_object_field)
if not _id and page_num:
topic_pagination = get_topics_pagination(page_num)
re... | TopicApi | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopicApi:
def get(self):
"""Get topic/topics by:. 1. _id (topic_id) 2. NO PARAM (in pagination form)"""
<|body_0|>
def post(self):
"""Create a topic. Preserved for development."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
args = get_topic_parser.... | stack_v2_sparse_classes_36k_train_033297 | 1,585 | permissive | [
{
"docstring": "Get topic/topics by:. 1. _id (topic_id) 2. NO PARAM (in pagination form)",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Create a topic. Preserved for development.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008937 | Implement the Python class `TopicApi` described below.
Class description:
Implement the TopicApi class.
Method signatures and docstrings:
- def get(self): Get topic/topics by:. 1. _id (topic_id) 2. NO PARAM (in pagination form)
- def post(self): Create a topic. Preserved for development. | Implement the Python class `TopicApi` described below.
Class description:
Implement the TopicApi class.
Method signatures and docstrings:
- def get(self): Get topic/topics by:. 1. _id (topic_id) 2. NO PARAM (in pagination form)
- def post(self): Create a topic. Preserved for development.
<|skeleton|>
class TopicApi:... | 3fdd201e8b7854759b6f5113790d90adb9879b88 | <|skeleton|>
class TopicApi:
def get(self):
"""Get topic/topics by:. 1. _id (topic_id) 2. NO PARAM (in pagination form)"""
<|body_0|>
def post(self):
"""Create a topic. Preserved for development."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TopicApi:
def get(self):
"""Get topic/topics by:. 1. _id (topic_id) 2. NO PARAM (in pagination form)"""
args = get_topic_parser.parse_args()
_id = args['_id']
page_num = args['page_num']
if _id:
return marshal(get_topic_or_404(_id), topic_object_field)
... | the_stack_v2_python_sparse | server/api/v1/topic/main.py | TeamDDH/bbk-server | train | 3 | |
90b2bf0f7bfe08b823d4bd26384cb7a678416a2e | [
"config.LoadConfig()\ndocker_dir = GetDockerPath(evidence.mount_path)\ncontainers_info = None\nde_binary = utils.get_exe_path('de.py')\nif not de_binary:\n raise TurbiniaException('Cannot find de.py in path')\nif not path.exists(docker_dir):\n log.info('docker_dir does not exist')\n return containers_info\... | <|body_start_0|>
config.LoadConfig()
docker_dir = GetDockerPath(evidence.mount_path)
containers_info = None
de_binary = utils.get_exe_path('de.py')
if not de_binary:
raise TurbiniaException('Cannot find de.py in path')
if not path.exists(docker_dir):
... | Enumerates Docker containers on Linux | DockerContainersEnumerationTask | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DockerContainersEnumerationTask:
"""Enumerates Docker containers on Linux"""
def GetContainers(self, evidence):
"""Lists the containers from an input Evidence. We use subprocess to run the DockerExplorer script, instead of using the Python module, because we need to make sure all Doc... | stack_v2_sparse_classes_36k_train_033298 | 4,313 | permissive | [
{
"docstring": "Lists the containers from an input Evidence. We use subprocess to run the DockerExplorer script, instead of using the Python module, because we need to make sure all DockerExplorer code runs as root. Args: evidence (Evidence): the input Evidence. Returns: a list(dict) containing information abou... | 2 | stack_v2_sparse_classes_30k_train_014409 | Implement the Python class `DockerContainersEnumerationTask` described below.
Class description:
Enumerates Docker containers on Linux
Method signatures and docstrings:
- def GetContainers(self, evidence): Lists the containers from an input Evidence. We use subprocess to run the DockerExplorer script, instead of usin... | Implement the Python class `DockerContainersEnumerationTask` described below.
Class description:
Enumerates Docker containers on Linux
Method signatures and docstrings:
- def GetContainers(self, evidence): Lists the containers from an input Evidence. We use subprocess to run the DockerExplorer script, instead of usin... | a756f4c625cf3796fc82d160f3c794c7e2039437 | <|skeleton|>
class DockerContainersEnumerationTask:
"""Enumerates Docker containers on Linux"""
def GetContainers(self, evidence):
"""Lists the containers from an input Evidence. We use subprocess to run the DockerExplorer script, instead of using the Python module, because we need to make sure all Doc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DockerContainersEnumerationTask:
"""Enumerates Docker containers on Linux"""
def GetContainers(self, evidence):
"""Lists the containers from an input Evidence. We use subprocess to run the DockerExplorer script, instead of using the Python module, because we need to make sure all DockerExplorer c... | the_stack_v2_python_sparse | turbinia/workers/docker.py | joachimmetz/turbinia | train | 1 |
42e81f850e23353db4bc3ee92c002e5e4e95ec4f | [
"self.points.append(point)\na = float(2) / (self.set_size + 1)\nself.average = self.average + a * (point - self.average)\nreturn self.average",
"if self.time == 0:\n self.average = point\n return point\nelse:\n return self.add_successive_points(point)"
] | <|body_start_0|>
self.points.append(point)
a = float(2) / (self.set_size + 1)
self.average = self.average + a * (point - self.average)
return self.average
<|end_body_0|>
<|body_start_1|>
if self.time == 0:
self.average = point
return point
else:
... | Similar to the LWMA, but applies exponentially decreasing weighting factors to the data points, giving more importance to the latest data points. | Exponential | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Exponential:
"""Similar to the LWMA, but applies exponentially decreasing weighting factors to the data points, giving more importance to the latest data points."""
def add_successive_points(self, point):
"""Formula: EMA_t = EMA_{t-1} + a * (price_t - EMA_{t-1}) where a = 2 / (N+1)""... | stack_v2_sparse_classes_36k_train_033299 | 943 | no_license | [
{
"docstring": "Formula: EMA_t = EMA_{t-1} + a * (price_t - EMA_{t-1}) where a = 2 / (N+1)",
"name": "add_successive_points",
"signature": "def add_successive_points(self, point)"
},
{
"docstring": "Because N and t are not dependent on each other in this formula, we can let EMA_1 = price_1, then... | 2 | stack_v2_sparse_classes_30k_train_010244 | Implement the Python class `Exponential` described below.
Class description:
Similar to the LWMA, but applies exponentially decreasing weighting factors to the data points, giving more importance to the latest data points.
Method signatures and docstrings:
- def add_successive_points(self, point): Formula: EMA_t = EM... | Implement the Python class `Exponential` described below.
Class description:
Similar to the LWMA, but applies exponentially decreasing weighting factors to the data points, giving more importance to the latest data points.
Method signatures and docstrings:
- def add_successive_points(self, point): Formula: EMA_t = EM... | ec66a140c62a330f0166d303fbbd6adbf9cc426c | <|skeleton|>
class Exponential:
"""Similar to the LWMA, but applies exponentially decreasing weighting factors to the data points, giving more importance to the latest data points."""
def add_successive_points(self, point):
"""Formula: EMA_t = EMA_{t-1} + a * (price_t - EMA_{t-1}) where a = 2 / (N+1)""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Exponential:
"""Similar to the LWMA, but applies exponentially decreasing weighting factors to the data points, giving more importance to the latest data points."""
def add_successive_points(self, point):
"""Formula: EMA_t = EMA_{t-1} + a * (price_t - EMA_{t-1}) where a = 2 / (N+1)"""
sel... | the_stack_v2_python_sparse | CODE/client/averages/exponential_moving_average.py | lineker/mcgill-codejam-2012 | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.