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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
761d059bc51ee29c9b235411e3002479972c7202 | [
"adm = ProjectAdministration()\npart = adm.get_participation_by_id(participation_id)\nreturn part",
"adm = ProjectAdministration()\npart = adm.get_participation_by_id(participation_id)\nif part is not None:\n adm.delete_participation(part)\n return ('gelöscht', 200)\nelse:\n return ('There is no particip... | <|body_start_0|>
adm = ProjectAdministration()
part = adm.get_participation_by_id(participation_id)
return part
<|end_body_0|>
<|body_start_1|>
adm = ProjectAdministration()
part = adm.get_participation_by_id(participation_id)
if part is not None:
adm.delete_... | ParticipationOperations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParticipationOperations:
def get(self, participation_id):
"""Auslesen eines bestimmten Participation-Objektes, welches durch die participation_id in dem URI bestimmt wird."""
<|body_0|>
def delete(self, participation_id):
"""Löschen eines bestimmten Participation-Obj... | stack_v2_sparse_classes_36k_train_010600 | 44,493 | no_license | [
{
"docstring": "Auslesen eines bestimmten Participation-Objektes, welches durch die participation_id in dem URI bestimmt wird.",
"name": "get",
"signature": "def get(self, participation_id)"
},
{
"docstring": "Löschen eines bestimmten Participation-Objektes, welches durch die participation_id in... | 2 | stack_v2_sparse_classes_30k_train_012910 | Implement the Python class `ParticipationOperations` described below.
Class description:
Implement the ParticipationOperations class.
Method signatures and docstrings:
- def get(self, participation_id): Auslesen eines bestimmten Participation-Objektes, welches durch die participation_id in dem URI bestimmt wird.
- de... | Implement the Python class `ParticipationOperations` described below.
Class description:
Implement the ParticipationOperations class.
Method signatures and docstrings:
- def get(self, participation_id): Auslesen eines bestimmten Participation-Objektes, welches durch die participation_id in dem URI bestimmt wird.
- de... | 4b2826225525ae855e15e1174f5cf90466097021 | <|skeleton|>
class ParticipationOperations:
def get(self, participation_id):
"""Auslesen eines bestimmten Participation-Objektes, welches durch die participation_id in dem URI bestimmt wird."""
<|body_0|>
def delete(self, participation_id):
"""Löschen eines bestimmten Participation-Obj... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParticipationOperations:
def get(self, participation_id):
"""Auslesen eines bestimmten Participation-Objektes, welches durch die participation_id in dem URI bestimmt wird."""
adm = ProjectAdministration()
part = adm.get_participation_by_id(participation_id)
return part
def... | the_stack_v2_python_sparse | src/main.py | KieserChristian/SW_Praktikum_Gruppe1 | train | 0 | |
66617fa2583b9f290ef6cc0b8dfbc3de79e900a8 | [
"print('setUp')\nitem_code = 65467\ndescription = 'TV'\nmarket_price = 1000\nrental_price = 100\nbrand = 'Samsung'\nvoltage = 12\nself.test_app_item = electric_appliances_class.ElectricAppliance(item_code, description, market_price, rental_price, brand, voltage)\nself.test_app_dict = self.test_app_item.return_as_di... | <|body_start_0|>
print('setUp')
item_code = 65467
description = 'TV'
market_price = 1000
rental_price = 100
brand = 'Samsung'
voltage = 12
self.test_app_item = electric_appliances_class.ElectricAppliance(item_code, description, market_price, rental_price, ... | Perform tests on Electric Appliances module. | ElectricAppliancesTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElectricAppliancesTests:
"""Perform tests on Electric Appliances module."""
def setUp(self):
"""Define set up characteristics of electrical appliance tests."""
<|body_0|>
def test_app_creation(self):
"""Test creation of electrical appliance item."""
<|bod... | stack_v2_sparse_classes_36k_train_010601 | 10,660 | no_license | [
{
"docstring": "Define set up characteristics of electrical appliance tests.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test creation of electrical appliance item.",
"name": "test_app_creation",
"signature": "def test_app_creation(self)"
}
] | 2 | null | Implement the Python class `ElectricAppliancesTests` described below.
Class description:
Perform tests on Electric Appliances module.
Method signatures and docstrings:
- def setUp(self): Define set up characteristics of electrical appliance tests.
- def test_app_creation(self): Test creation of electrical appliance i... | Implement the Python class `ElectricAppliancesTests` described below.
Class description:
Perform tests on Electric Appliances module.
Method signatures and docstrings:
- def setUp(self): Define set up characteristics of electrical appliance tests.
- def test_app_creation(self): Test creation of electrical appliance i... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class ElectricAppliancesTests:
"""Perform tests on Electric Appliances module."""
def setUp(self):
"""Define set up characteristics of electrical appliance tests."""
<|body_0|>
def test_app_creation(self):
"""Test creation of electrical appliance item."""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ElectricAppliancesTests:
"""Perform tests on Electric Appliances module."""
def setUp(self):
"""Define set up characteristics of electrical appliance tests."""
print('setUp')
item_code = 65467
description = 'TV'
market_price = 1000
rental_price = 100
... | the_stack_v2_python_sparse | students/Reem_Alqaysi/Lesson_01/test_unit.py | JavaRod/SP_Python220B_2019 | train | 1 |
877752c66b8b5ccdd5658b49bd61b78652e65a86 | [
"query = dict()\nproject and query.update(project=project)\naction and query.update(action=action)\nobj = ProjectLog.objects.filter(**query).order_by('-updated')\ndataset = [dict()]\nreturn self.result_class(data=obj)(serialize=True)",
"obj = ProjectLog.objects.create(project=project, action=action, content=kwarg... | <|body_start_0|>
query = dict()
project and query.update(project=project)
action and query.update(action=action)
obj = ProjectLog.objects.filter(**query).order_by('-updated')
dataset = [dict()]
return self.result_class(data=obj)(serialize=True)
<|end_body_0|>
<|body_star... | ProjectLogViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectLogViewSet:
def list(self, request, project=None, action=None, **kwargs):
"""获取项目日志,如签证,工作日志,审核日志等"""
<|body_0|>
def create(self, request, project=None, action=None, attatchment=None, **kwargs):
"""新建项目日志 content: {date: '', content: ''}"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_010602 | 29,085 | no_license | [
{
"docstring": "获取项目日志,如签证,工作日志,审核日志等",
"name": "list",
"signature": "def list(self, request, project=None, action=None, **kwargs)"
},
{
"docstring": "新建项目日志 content: {date: '', content: ''}",
"name": "create",
"signature": "def create(self, request, project=None, action=None, attatchmen... | 2 | stack_v2_sparse_classes_30k_train_021505 | Implement the Python class `ProjectLogViewSet` described below.
Class description:
Implement the ProjectLogViewSet class.
Method signatures and docstrings:
- def list(self, request, project=None, action=None, **kwargs): 获取项目日志,如签证,工作日志,审核日志等
- def create(self, request, project=None, action=None, attatchment=None, **k... | Implement the Python class `ProjectLogViewSet` described below.
Class description:
Implement the ProjectLogViewSet class.
Method signatures and docstrings:
- def list(self, request, project=None, action=None, **kwargs): 获取项目日志,如签证,工作日志,审核日志等
- def create(self, request, project=None, action=None, attatchment=None, **k... | f5fe197a3624dd993e6f4cf8de547d1f45f40681 | <|skeleton|>
class ProjectLogViewSet:
def list(self, request, project=None, action=None, **kwargs):
"""获取项目日志,如签证,工作日志,审核日志等"""
<|body_0|>
def create(self, request, project=None, action=None, attatchment=None, **kwargs):
"""新建项目日志 content: {date: '', content: ''}"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectLogViewSet:
def list(self, request, project=None, action=None, **kwargs):
"""获取项目日志,如签证,工作日志,审核日志等"""
query = dict()
project and query.update(project=project)
action and query.update(action=action)
obj = ProjectLog.objects.filter(**query).order_by('-updated')
... | the_stack_v2_python_sparse | ssrd/users/views.py | BronzeKing/ssrd | train | 1 | |
c6426157475900316475f944e4a1ee54370bc402 | [
"item = Product(name='Product', available_stock='100', content='product content', price='30', image='img.jpg', num_of_ratings='5', average_rating='5')\nitem.save()\nuser = User.objects.create_user(username='username', email='myemail@test.com', password='password')\nuser.save()\nreview = Review(product=item, user=us... | <|body_start_0|>
item = Product(name='Product', available_stock='100', content='product content', price='30', image='img.jpg', num_of_ratings='5', average_rating='5')
item.save()
user = User.objects.create_user(username='username', email='myemail@test.com', password='password')
user.save... | test the review model | TestReviewModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestReviewModel:
"""test the review model"""
def test_review_model(self):
"""test the review model is working"""
<|body_0|>
def test_return_review_title_and_rating_as_a_string(self):
"""test the return string from the review model"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k_train_010603 | 1,894 | no_license | [
{
"docstring": "test the review model is working",
"name": "test_review_model",
"signature": "def test_review_model(self)"
},
{
"docstring": "test the return string from the review model",
"name": "test_return_review_title_and_rating_as_a_string",
"signature": "def test_return_review_tit... | 2 | stack_v2_sparse_classes_30k_train_002325 | Implement the Python class `TestReviewModel` described below.
Class description:
test the review model
Method signatures and docstrings:
- def test_review_model(self): test the review model is working
- def test_return_review_title_and_rating_as_a_string(self): test the return string from the review model | Implement the Python class `TestReviewModel` described below.
Class description:
test the review model
Method signatures and docstrings:
- def test_review_model(self): test the review model is working
- def test_return_review_title_and_rating_as_a_string(self): test the return string from the review model
<|skeleton... | a80148cb642cb09dac57cff18483be14fed67dfd | <|skeleton|>
class TestReviewModel:
"""test the review model"""
def test_review_model(self):
"""test the review model is working"""
<|body_0|>
def test_return_review_title_and_rating_as_a_string(self):
"""test the return string from the review model"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestReviewModel:
"""test the review model"""
def test_review_model(self):
"""test the review model is working"""
item = Product(name='Product', available_stock='100', content='product content', price='30', image='img.jpg', num_of_ratings='5', average_rating='5')
item.save()
... | the_stack_v2_python_sparse | review/test_models.py | sarahbarron/Stream-3-Project | train | 1 |
29891f0c7456a0b9d60f918d9da19ac9311e258f | [
"slist = list(s)\nsdict = {}\ncount = 1\nfor i in range(len(slist)):\n if slist[i] not in sdict.keys():\n sdict[slist[i]] = count\n else:\n sdict[slist[i]] = sdict[slist[i]] + 1\nfor i, v in sdict.items():\n if v == 1:\n return s.index(i)\nreturn -1",
"count = collections.Counter(s)\... | <|body_start_0|>
slist = list(s)
sdict = {}
count = 1
for i in range(len(slist)):
if slist[i] not in sdict.keys():
sdict[slist[i]] = count
else:
sdict[slist[i]] = sdict[slist[i]] + 1
for i, v in sdict.items():
if... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def firstUniqChar(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def firstUniqChar2(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
slist = list(s)
sdict = {}
count = 1
for... | stack_v2_sparse_classes_36k_train_010604 | 1,473 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "firstUniqChar",
"signature": "def firstUniqChar(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "firstUniqChar2",
"signature": "def firstUniqChar2(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstUniqChar(self, s): :type s: str :rtype: int
- def firstUniqChar2(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstUniqChar(self, s): :type s: str :rtype: int
- def firstUniqChar2(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def firstUniqChar(self, s):
... | 786075e0f9f61cf062703bc0b41cc3191d77f033 | <|skeleton|>
class Solution:
def firstUniqChar(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def firstUniqChar2(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def firstUniqChar(self, s):
""":type s: str :rtype: int"""
slist = list(s)
sdict = {}
count = 1
for i in range(len(slist)):
if slist[i] not in sdict.keys():
sdict[slist[i]] = count
else:
sdict[slist[i]] =... | the_stack_v2_python_sparse | firstUniqChar.py | Anirban2404/LeetCodePractice | train | 1 | |
c3c909f95f9855a9235c07a90ccc358272b38ca5 | [
"check_type(session, RestSession)\nsuper(EventsAPI, self).__init__()\nself._session = session\nself._object_factory = object_factory",
"check_type(resource, basestring, optional=True)\ncheck_type(type, basestring, optional=True)\ncheck_type(actorId, basestring, optional=True)\ncheck_type(_from, basestring, option... | <|body_start_0|>
check_type(session, RestSession)
super(EventsAPI, self).__init__()
self._session = session
self._object_factory = object_factory
<|end_body_0|>
<|body_start_1|>
check_type(resource, basestring, optional=True)
check_type(type, basestring, optional=True)
... | Webex Teams Events API. Wraps the Webex Teams Events API and exposes the API as native Python methods that return native Python objects. | EventsAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventsAPI:
"""Webex Teams Events API. Wraps the Webex Teams Events API and exposes the API as native Python methods that return native Python objects."""
def __init__(self, session, object_factory):
"""Initialize a new EventsAPI object with the provided RestSession. Args: session(Res... | stack_v2_sparse_classes_36k_train_010605 | 6,123 | permissive | [
{
"docstring": "Initialize a new EventsAPI object with the provided RestSession. Args: session(RestSession): The RESTful session object to be used for API calls to the Webex Teams service. Raises: TypeError: If the parameter types are incorrect.",
"name": "__init__",
"signature": "def __init__(self, ses... | 3 | stack_v2_sparse_classes_30k_train_019741 | Implement the Python class `EventsAPI` described below.
Class description:
Webex Teams Events API. Wraps the Webex Teams Events API and exposes the API as native Python methods that return native Python objects.
Method signatures and docstrings:
- def __init__(self, session, object_factory): Initialize a new EventsAP... | Implement the Python class `EventsAPI` described below.
Class description:
Webex Teams Events API. Wraps the Webex Teams Events API and exposes the API as native Python methods that return native Python objects.
Method signatures and docstrings:
- def __init__(self, session, object_factory): Initialize a new EventsAP... | d031aab82e3fa5ce7cf57b257fef8c9a4c63d71e | <|skeleton|>
class EventsAPI:
"""Webex Teams Events API. Wraps the Webex Teams Events API and exposes the API as native Python methods that return native Python objects."""
def __init__(self, session, object_factory):
"""Initialize a new EventsAPI object with the provided RestSession. Args: session(Res... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventsAPI:
"""Webex Teams Events API. Wraps the Webex Teams Events API and exposes the API as native Python methods that return native Python objects."""
def __init__(self, session, object_factory):
"""Initialize a new EventsAPI object with the provided RestSession. Args: session(RestSession): Th... | the_stack_v2_python_sparse | venv/lib/python3.9/site-packages/webexteamssdk/api/events.py | CiscoDevNet/meraki-code | train | 67 |
1d07ed7418691812f62f28ea45ae0091e1e901fa | [
"player_index = 6\ngame_roles = list(large_game_roles)\nnew_roles = list(large_game_roles)\nnew_roles[13], new_roles[6] = (new_roles[6], new_roles[13])\ndrunk = Drunk.awake_init(player_index, game_roles, large_game_roles)\nassert drunk.choice_ind == 13\nassert game_roles == new_roles\nassert drunk.statements == (St... | <|body_start_0|>
player_index = 6
game_roles = list(large_game_roles)
new_roles = list(large_game_roles)
new_roles[13], new_roles[6] = (new_roles[6], new_roles[13])
drunk = Drunk.awake_init(player_index, game_roles, large_game_roles)
assert drunk.choice_ind == 13
... | Tests for the Drunk player class. | TestDrunk | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDrunk:
"""Tests for the Drunk player class."""
def test_awake_init(large_game_roles: tuple[Role, ...]) -> None:
"""Should initialize a Drunk. Note that the player_index of the Drunk is not necessarily the index where the true Drunk is located."""
<|body_0|>
def test_... | stack_v2_sparse_classes_36k_train_010606 | 2,775 | permissive | [
{
"docstring": "Should initialize a Drunk. Note that the player_index of the Drunk is not necessarily the index where the true Drunk is located.",
"name": "test_awake_init",
"signature": "def test_awake_init(large_game_roles: tuple[Role, ...]) -> None"
},
{
"docstring": "Execute initialization a... | 3 | stack_v2_sparse_classes_30k_train_012164 | Implement the Python class `TestDrunk` described below.
Class description:
Tests for the Drunk player class.
Method signatures and docstrings:
- def test_awake_init(large_game_roles: tuple[Role, ...]) -> None: Should initialize a Drunk. Note that the player_index of the Drunk is not necessarily the index where the tr... | Implement the Python class `TestDrunk` described below.
Class description:
Tests for the Drunk player class.
Method signatures and docstrings:
- def test_awake_init(large_game_roles: tuple[Role, ...]) -> None: Should initialize a Drunk. Note that the player_index of the Drunk is not necessarily the index where the tr... | 6e91c2f24e72f9374c4f703bd966963ea6626e8e | <|skeleton|>
class TestDrunk:
"""Tests for the Drunk player class."""
def test_awake_init(large_game_roles: tuple[Role, ...]) -> None:
"""Should initialize a Drunk. Note that the player_index of the Drunk is not necessarily the index where the true Drunk is located."""
<|body_0|>
def test_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDrunk:
"""Tests for the Drunk player class."""
def test_awake_init(large_game_roles: tuple[Role, ...]) -> None:
"""Should initialize a Drunk. Note that the player_index of the Drunk is not necessarily the index where the true Drunk is located."""
player_index = 6
game_roles = ... | the_stack_v2_python_sparse | unit_test/roles/village/drunk_test.py | srijan-deepsource/wolfbot | train | 0 |
b619429225550e61792ce602d9b0aec879ed60d2 | [
"rval = []\nfor group in trans.sa_session.query(trans.app.model.Group).filter(trans.app.model.Group.table.c.deleted == false()):\n if trans.user_is_admin:\n item = group.to_dict(value_mapper={'id': trans.security.encode_id})\n encoded_id = trans.security.encode_id(group.id)\n item['url'] = u... | <|body_start_0|>
rval = []
for group in trans.sa_session.query(trans.app.model.Group).filter(trans.app.model.Group.table.c.deleted == false()):
if trans.user_is_admin:
item = group.to_dict(value_mapper={'id': trans.security.encode_id})
encoded_id = trans.secur... | GroupAPIController | [
"CC-BY-2.5",
"AFL-2.1",
"AFL-3.0",
"CC-BY-3.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupAPIController:
def index(self, trans, **kwd):
"""GET /api/groups Displays a collection (list) of groups."""
<|body_0|>
def create(self, trans, payload, **kwd):
"""POST /api/groups Creates a new group."""
<|body_1|>
def show(self, trans, id, **kwd):
... | stack_v2_sparse_classes_36k_train_010607 | 5,197 | permissive | [
{
"docstring": "GET /api/groups Displays a collection (list) of groups.",
"name": "index",
"signature": "def index(self, trans, **kwd)"
},
{
"docstring": "POST /api/groups Creates a new group.",
"name": "create",
"signature": "def create(self, trans, payload, **kwd)"
},
{
"docstr... | 4 | stack_v2_sparse_classes_30k_test_000465 | Implement the Python class `GroupAPIController` described below.
Class description:
Implement the GroupAPIController class.
Method signatures and docstrings:
- def index(self, trans, **kwd): GET /api/groups Displays a collection (list) of groups.
- def create(self, trans, payload, **kwd): POST /api/groups Creates a n... | Implement the Python class `GroupAPIController` described below.
Class description:
Implement the GroupAPIController class.
Method signatures and docstrings:
- def index(self, trans, **kwd): GET /api/groups Displays a collection (list) of groups.
- def create(self, trans, payload, **kwd): POST /api/groups Creates a n... | d194520fdfe08e48c0b3d0d2299cd2adcb8f5952 | <|skeleton|>
class GroupAPIController:
def index(self, trans, **kwd):
"""GET /api/groups Displays a collection (list) of groups."""
<|body_0|>
def create(self, trans, payload, **kwd):
"""POST /api/groups Creates a new group."""
<|body_1|>
def show(self, trans, id, **kwd):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupAPIController:
def index(self, trans, **kwd):
"""GET /api/groups Displays a collection (list) of groups."""
rval = []
for group in trans.sa_session.query(trans.app.model.Group).filter(trans.app.model.Group.table.c.deleted == false()):
if trans.user_is_admin:
... | the_stack_v2_python_sparse | lib/galaxy/webapps/galaxy/api/groups.py | bwlang/galaxy | train | 0 | |
35ad139801b4ae29320f6c0b287e09d05015d609 | [
"params = base.get_params(None, locals())\nurl = '{0}/readme'.format(self.parent.get_url())\nreturn (http.Request('GET', url, params), parsers.parse_json)",
"params = base.get_params(('ref',), locals())\nurl = self.get_url()\nif path:\n url = '{0}/{1}'.format(url, path)\nreturn (http.Request('GET', url, params... | <|body_start_0|>
params = base.get_params(None, locals())
url = '{0}/readme'.format(self.parent.get_url())
return (http.Request('GET', url, params), parsers.parse_json)
<|end_body_0|>
<|body_start_1|>
params = base.get_params(('ref',), locals())
url = self.get_url()
if p... | RepoContents | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RepoContents:
def readme(self, ref=None):
"""This method returns the preferred README for a repository. :var ref: Optional string name of the commit/branch/tag. Defaults to master. :vartype ref: str"""
<|body_0|>
def get(self, path=None, ref=None):
"""This method ret... | stack_v2_sparse_classes_36k_train_010608 | 1,918 | permissive | [
{
"docstring": "This method returns the preferred README for a repository. :var ref: Optional string name of the commit/branch/tag. Defaults to master. :vartype ref: str",
"name": "readme",
"signature": "def readme(self, ref=None)"
},
{
"docstring": "This method returns the contents of any file ... | 3 | null | Implement the Python class `RepoContents` described below.
Class description:
Implement the RepoContents class.
Method signatures and docstrings:
- def readme(self, ref=None): This method returns the preferred README for a repository. :var ref: Optional string name of the commit/branch/tag. Defaults to master. :varty... | Implement the Python class `RepoContents` described below.
Class description:
Implement the RepoContents class.
Method signatures and docstrings:
- def readme(self, ref=None): This method returns the preferred README for a repository. :var ref: Optional string name of the commit/branch/tag. Defaults to master. :varty... | 25caa745a104c8dc209584fa359294c65dbf88bb | <|skeleton|>
class RepoContents:
def readme(self, ref=None):
"""This method returns the preferred README for a repository. :var ref: Optional string name of the commit/branch/tag. Defaults to master. :vartype ref: str"""
<|body_0|>
def get(self, path=None, ref=None):
"""This method ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RepoContents:
def readme(self, ref=None):
"""This method returns the preferred README for a repository. :var ref: Optional string name of the commit/branch/tag. Defaults to master. :vartype ref: str"""
params = base.get_params(None, locals())
url = '{0}/readme'.format(self.parent.get_u... | the_stack_v2_python_sparse | libsaas/services/github/repocontents.py | piplcom/libsaas | train | 1 | |
dd3ac79be386e38761c765435f89204ca907fa54 | [
"self.rand_generator = np.random.RandomState(env_info.get('seed'))\nself.num_states = env_info['num_states']\nself.start_state = env_info['start_state']\nself.left_terminal_state = env_info['left_terminal_state']\nself.right_terminal_state = env_info['right_terminal_state']",
"reward = 0.0\nobservation = self.sta... | <|body_start_0|>
self.rand_generator = np.random.RandomState(env_info.get('seed'))
self.num_states = env_info['num_states']
self.start_state = env_info['start_state']
self.left_terminal_state = env_info['left_terminal_state']
self.right_terminal_state = env_info['right_terminal_s... | RandomWalkEnvironment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomWalkEnvironment:
def env_init(self, env_info={}):
"""Setup for the environment called when the experiment first starts. Set parameters needed to setup the 500-state random walk environment. Assume env_info dict contains: { num_states: 500, start_state: 250, left_terminal_state: 0, ... | stack_v2_sparse_classes_36k_train_010609 | 3,929 | no_license | [
{
"docstring": "Setup for the environment called when the experiment first starts. Set parameters needed to setup the 500-state random walk environment. Assume env_info dict contains: { num_states: 500, start_state: 250, left_terminal_state: 0, right_terminal_state: 501, seed: int }",
"name": "env_init",
... | 3 | stack_v2_sparse_classes_30k_train_005608 | Implement the Python class `RandomWalkEnvironment` described below.
Class description:
Implement the RandomWalkEnvironment class.
Method signatures and docstrings:
- def env_init(self, env_info={}): Setup for the environment called when the experiment first starts. Set parameters needed to setup the 500-state random ... | Implement the Python class `RandomWalkEnvironment` described below.
Class description:
Implement the RandomWalkEnvironment class.
Method signatures and docstrings:
- def env_init(self, env_info={}): Setup for the environment called when the experiment first starts. Set parameters needed to setup the 500-state random ... | 4ae8c176acbb5b2d78ff08379a856c4afefea8f8 | <|skeleton|>
class RandomWalkEnvironment:
def env_init(self, env_info={}):
"""Setup for the environment called when the experiment first starts. Set parameters needed to setup the 500-state random walk environment. Assume env_info dict contains: { num_states: 500, start_state: 250, left_terminal_state: 0, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomWalkEnvironment:
def env_init(self, env_info={}):
"""Setup for the environment called when the experiment first starts. Set parameters needed to setup the 500-state random walk environment. Assume env_info dict contains: { num_states: 500, start_state: 250, left_terminal_state: 0, right_terminal... | the_stack_v2_python_sparse | Reinforcement_Learning - University of Alberta/003_Prediction_and_Control_with_Function_Approximation/week_2/assignment/randomwalk_environment.py | bhunkeler/DataScienceCoursera | train | 52 | |
25864eb74e296efc76a83fc1a505f0f74294dd38 | [
"with benchmark('Generate a list of all reserved attribute names'):\n if not cls._reserved_names.get(definition_type):\n definition_map = {model._inflector.table_singular: model for model in ggrc.models.all_models.all_models}\n definition_map.update({model._inflector.model_singular: model for model... | <|body_start_0|>
with benchmark('Generate a list of all reserved attribute names'):
if not cls._reserved_names.get(definition_type):
definition_map = {model._inflector.table_singular: model for model in ggrc.models.all_models.all_models}
definition_map.update({model._... | Adds methods needed for attribute name vaidation | AttributeValidator | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttributeValidator:
"""Adds methods needed for attribute name vaidation"""
def _get_reserved_names(cls, definition_type):
"""Get a list of all attribute names in all objects. On first call this function computes all possible names that can be used by any model and stores them in a st... | stack_v2_sparse_classes_36k_train_010610 | 2,376 | permissive | [
{
"docstring": "Get a list of all attribute names in all objects. On first call this function computes all possible names that can be used by any model and stores them in a static frozen set. All later calls just get this set. Returns: frozen set containing all reserved attribute names for the current object.",... | 2 | stack_v2_sparse_classes_30k_train_018717 | Implement the Python class `AttributeValidator` described below.
Class description:
Adds methods needed for attribute name vaidation
Method signatures and docstrings:
- def _get_reserved_names(cls, definition_type): Get a list of all attribute names in all objects. On first call this function computes all possible na... | Implement the Python class `AttributeValidator` described below.
Class description:
Adds methods needed for attribute name vaidation
Method signatures and docstrings:
- def _get_reserved_names(cls, definition_type): Get a list of all attribute names in all objects. On first call this function computes all possible na... | 9bdc0fc6ca9e252f4919db682d80e360d5581eb4 | <|skeleton|>
class AttributeValidator:
"""Adds methods needed for attribute name vaidation"""
def _get_reserved_names(cls, definition_type):
"""Get a list of all attribute names in all objects. On first call this function computes all possible names that can be used by any model and stores them in a st... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AttributeValidator:
"""Adds methods needed for attribute name vaidation"""
def _get_reserved_names(cls, definition_type):
"""Get a list of all attribute names in all objects. On first call this function computes all possible names that can be used by any model and stores them in a static frozen s... | the_stack_v2_python_sparse | src/ggrc/models/mixins/attributevalidator.py | HLD/ggrc-core | train | 0 |
6100f1a09996674b67a958a7026ada368ae699fb | [
"nn.Module.__init__(self)\nself.P = P\nself.eta = eta\nself.eps = eps",
"dist = torch.sum((input - torch.matmul(self.P, input.transpose(0, 1)).transpose(0, 1)) ** 2, dim=1)\nlosses = torch.where(semi_target == 0, dist, self.eta * (dist + self.eps) ** semi_target.float())\nloss = torch.mean(losses)\nreturn loss"
] | <|body_start_0|>
nn.Module.__init__(self)
self.P = P
self.eta = eta
self.eps = eps
<|end_body_0|>
<|body_start_1|>
dist = torch.sum((input - torch.matmul(self.P, input.transpose(0, 1)).transpose(0, 1)) ** 2, dim=1)
losses = torch.where(semi_target == 0, dist, self.eta * ... | Implementation of the DeepSAD loss proposed by Lukas Ruff et al. (2019) but with the distance of the point projected to the subspace of training samples rather than the hypersphere. It follows the mathematical derivation proposed by Arnout Devos et al. (2019). | DeepSADLossSubspace | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeepSADLossSubspace:
"""Implementation of the DeepSAD loss proposed by Lukas Ruff et al. (2019) but with the distance of the point projected to the subspace of training samples rather than the hypersphere. It follows the mathematical derivation proposed by Arnout Devos et al. (2019)."""
def ... | stack_v2_sparse_classes_36k_train_010611 | 18,386 | permissive | [
{
"docstring": "Constructor of the DeepSAD loss Subspace. ---------- INPUT |---- P (torch.Tensor) The projection matrix to the subspace of normal | sample. P is a MxM matrix where M is the embedding dimension. |---- eta (float) control the importance given to known or unknonw | samples. 1.0 gives equal weights,... | 2 | stack_v2_sparse_classes_30k_train_014497 | Implement the Python class `DeepSADLossSubspace` described below.
Class description:
Implementation of the DeepSAD loss proposed by Lukas Ruff et al. (2019) but with the distance of the point projected to the subspace of training samples rather than the hypersphere. It follows the mathematical derivation proposed by A... | Implement the Python class `DeepSADLossSubspace` described below.
Class description:
Implementation of the DeepSAD loss proposed by Lukas Ruff et al. (2019) but with the distance of the point projected to the subspace of training samples rather than the hypersphere. It follows the mathematical derivation proposed by A... | 850b6195d6290a50eee865b4d5a66f5db5260e8f | <|skeleton|>
class DeepSADLossSubspace:
"""Implementation of the DeepSAD loss proposed by Lukas Ruff et al. (2019) but with the distance of the point projected to the subspace of training samples rather than the hypersphere. It follows the mathematical derivation proposed by Arnout Devos et al. (2019)."""
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeepSADLossSubspace:
"""Implementation of the DeepSAD loss proposed by Lukas Ruff et al. (2019) but with the distance of the point projected to the subspace of training samples rather than the hypersphere. It follows the mathematical derivation proposed by Arnout Devos et al. (2019)."""
def __init__(self... | the_stack_v2_python_sparse | Code/src/models/optim/CustomLosses.py | antoine-spahr/X-ray-Anomaly-Detection | train | 3 |
5ef840f2946b740b62640f7d4a3f3f8b92c2effd | [
"lowercase = 'abcdefghijklmnopqrstuvwxyz'\nres = [s.index(letter) for letter in lowercase if s.count(letter) == 1]\nif len(res):\n print(min(res))\n return min(res)\nreturn -1",
"d = {}\nfor i in range(len(s)):\n if s[i] not in d:\n d[s[i]] = i\n else:\n d[s[i]] += len(s)\nif len(s) and ... | <|body_start_0|>
lowercase = 'abcdefghijklmnopqrstuvwxyz'
res = [s.index(letter) for letter in lowercase if s.count(letter) == 1]
if len(res):
print(min(res))
return min(res)
return -1
<|end_body_0|>
<|body_start_1|>
d = {}
for i in range(len(s)):... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def first_uniqchar(self, s):
""":type s: str :rtype:int"""
<|body_0|>
def first_uniqchar_2(self, s):
""":type s: str :rtype:int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
lowercase = 'abcdefghijklmnopqrstuvwxyz'
res = [s.index... | stack_v2_sparse_classes_36k_train_010612 | 1,225 | no_license | [
{
"docstring": ":type s: str :rtype:int",
"name": "first_uniqchar",
"signature": "def first_uniqchar(self, s)"
},
{
"docstring": ":type s: str :rtype:int",
"name": "first_uniqchar_2",
"signature": "def first_uniqchar_2(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def first_uniqchar(self, s): :type s: str :rtype:int
- def first_uniqchar_2(self, s): :type s: str :rtype:int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def first_uniqchar(self, s): :type s: str :rtype:int
- def first_uniqchar_2(self, s): :type s: str :rtype:int
<|skeleton|>
class Solution:
def first_uniqchar(self, s):
... | 4f2802d4773eddd2a2e06e61c51463056886b730 | <|skeleton|>
class Solution:
def first_uniqchar(self, s):
""":type s: str :rtype:int"""
<|body_0|>
def first_uniqchar_2(self, s):
""":type s: str :rtype:int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def first_uniqchar(self, s):
""":type s: str :rtype:int"""
lowercase = 'abcdefghijklmnopqrstuvwxyz'
res = [s.index(letter) for letter in lowercase if s.count(letter) == 1]
if len(res):
print(min(res))
return min(res)
return -1
def ... | the_stack_v2_python_sparse | leetcode/14_firstUniqChar.py | Yara7L/python_algorithm | train | 0 | |
121ecbfeb94bfc8efbd3d2bd59e3a61b82c3fa5a | [
"self.zone = [(rr.rname, QTYPE[rr.rtype], rr) for rr in RR.fromZone(zone)]\nself.glob = glob\nself.eq = 'matchGlob' if glob else '__eq__'",
"reply = request.reply()\nqname = request.q.qname\nqtype = QTYPE[request.q.qtype]\nfor name, rtype, rr in self.zone:\n if getattr(qname, self.eq)(name) and (qtype == rtype... | <|body_start_0|>
self.zone = [(rr.rname, QTYPE[rr.rtype], rr) for rr in RR.fromZone(zone)]
self.glob = glob
self.eq = 'matchGlob' if glob else '__eq__'
<|end_body_0|>
<|body_start_1|>
reply = request.reply()
qname = request.q.qname
qtype = QTYPE[request.q.qtype]
... | Simple fixed zone file resolver. | ZoneResolver | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZoneResolver:
"""Simple fixed zone file resolver."""
def __init__(self, zone, glob=False):
"""Initialise resolver from zone file. Stores RRs as a list of (label,type,rr) tuples If 'glob' is True use glob match against zone file"""
<|body_0|>
def resolve(self, request, ha... | stack_v2_sparse_classes_36k_train_010613 | 4,374 | permissive | [
{
"docstring": "Initialise resolver from zone file. Stores RRs as a list of (label,type,rr) tuples If 'glob' is True use glob match against zone file",
"name": "__init__",
"signature": "def __init__(self, zone, glob=False)"
},
{
"docstring": "Respond to DNS request - parameters are request packe... | 2 | stack_v2_sparse_classes_30k_train_001521 | Implement the Python class `ZoneResolver` described below.
Class description:
Simple fixed zone file resolver.
Method signatures and docstrings:
- def __init__(self, zone, glob=False): Initialise resolver from zone file. Stores RRs as a list of (label,type,rr) tuples If 'glob' is True use glob match against zone file... | Implement the Python class `ZoneResolver` described below.
Class description:
Simple fixed zone file resolver.
Method signatures and docstrings:
- def __init__(self, zone, glob=False): Initialise resolver from zone file. Stores RRs as a list of (label,type,rr) tuples If 'glob' is True use glob match against zone file... | 541f58da464296001109f9cfbb879256957b3819 | <|skeleton|>
class ZoneResolver:
"""Simple fixed zone file resolver."""
def __init__(self, zone, glob=False):
"""Initialise resolver from zone file. Stores RRs as a list of (label,type,rr) tuples If 'glob' is True use glob match against zone file"""
<|body_0|>
def resolve(self, request, ha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZoneResolver:
"""Simple fixed zone file resolver."""
def __init__(self, zone, glob=False):
"""Initialise resolver from zone file. Stores RRs as a list of (label,type,rr) tuples If 'glob' is True use glob match against zone file"""
self.zone = [(rr.rname, QTYPE[rr.rtype], rr) for rr in RR.... | the_stack_v2_python_sparse | code/default/lib/noarch/dnslib/zoneresolver.py | XX-net/XX-Net | train | 40,250 |
c2e676d578e2d52051c77b321cd658b615f49fbb | [
"self.net = net\nself.v_net = copy.deepcopy(net)\nself.w_momentum = w_momentum\nself.w_weight_decay = w_weight_decay",
"loss = self.net.loss(trn_X, trn_y)\ngradients = torch.autograd.grad(loss, self.net.weights())\nwith torch.no_grad():\n for w, vw, g in zip(self.net.weights(), self.v_net.weights(), gradients)... | <|body_start_0|>
self.net = net
self.v_net = copy.deepcopy(net)
self.w_momentum = w_momentum
self.w_weight_decay = w_weight_decay
<|end_body_0|>
<|body_start_1|>
loss = self.net.loss(trn_X, trn_y)
gradients = torch.autograd.grad(loss, self.net.weights())
with tor... | Compute gradients of alphas | Architect | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Architect:
"""Compute gradients of alphas"""
def __init__(self, net, w_momentum, w_weight_decay):
"""Args: net w_momentum: weights momentum"""
<|body_0|>
def virtual_step(self, trn_X, trn_y, xi, w_optim):
"""Compute unrolled weight w' (virtual step) Step process:... | stack_v2_sparse_classes_36k_train_010614 | 17,019 | permissive | [
{
"docstring": "Args: net w_momentum: weights momentum",
"name": "__init__",
"signature": "def __init__(self, net, w_momentum, w_weight_decay)"
},
{
"docstring": "Compute unrolled weight w' (virtual step) Step process: 1) forward 2) calc loss 3) compute gradient (by backprop) 4) update gradient ... | 4 | stack_v2_sparse_classes_30k_train_018295 | Implement the Python class `Architect` described below.
Class description:
Compute gradients of alphas
Method signatures and docstrings:
- def __init__(self, net, w_momentum, w_weight_decay): Args: net w_momentum: weights momentum
- def virtual_step(self, trn_X, trn_y, xi, w_optim): Compute unrolled weight w' (virtua... | Implement the Python class `Architect` described below.
Class description:
Compute gradients of alphas
Method signatures and docstrings:
- def __init__(self, net, w_momentum, w_weight_decay): Args: net w_momentum: weights momentum
- def virtual_step(self, trn_X, trn_y, xi, w_optim): Compute unrolled weight w' (virtua... | cc3d5cadfb4f755b4b4004dc368a102cdc68e6f6 | <|skeleton|>
class Architect:
"""Compute gradients of alphas"""
def __init__(self, net, w_momentum, w_weight_decay):
"""Args: net w_momentum: weights momentum"""
<|body_0|>
def virtual_step(self, trn_X, trn_y, xi, w_optim):
"""Compute unrolled weight w' (virtual step) Step process:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Architect:
"""Compute gradients of alphas"""
def __init__(self, net, w_momentum, w_weight_decay):
"""Args: net w_momentum: weights momentum"""
self.net = net
self.v_net = copy.deepcopy(net)
self.w_momentum = w_momentum
self.w_weight_decay = w_weight_decay
def ... | the_stack_v2_python_sparse | xnas/search_algorithm/pdarts.py | WOODchen7/XNAS | train | 0 |
9b913e2751c385eb1749ce9fe767bd54886f8c39 | [
"self.expert_count = np.random.randint(0, 1000, size=len(self.capacity) * self.n_worker)\nself.out = limit_by_capacity(self.expert_count, self.capacity, self.n_worker)\nself.expert_count = self.expert_count.astype('int64')\nself.capacity = self.capacity.astype('int64')\nself.place = paddle.CUDAPlace(0)",
"self.ca... | <|body_start_0|>
self.expert_count = np.random.randint(0, 1000, size=len(self.capacity) * self.n_worker)
self.out = limit_by_capacity(self.expert_count, self.capacity, self.n_worker)
self.expert_count = self.expert_count.astype('int64')
self.capacity = self.capacity.astype('int64')
... | TestLimitByCapacityAPI | TestLimitByCapacityAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestLimitByCapacityAPI:
"""TestLimitByCapacityAPI"""
def init_test_case(self):
"""init_test_case"""
<|body_0|>
def setUp(self):
"""setUp"""
<|body_1|>
def test_MoE_limit_by_capacity_static(self):
"""test_MoE_limit_by_capacity_static"""
... | stack_v2_sparse_classes_36k_train_010615 | 3,920 | no_license | [
{
"docstring": "init_test_case",
"name": "init_test_case",
"signature": "def init_test_case(self)"
},
{
"docstring": "setUp",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "test_MoE_limit_by_capacity_static",
"name": "test_MoE_limit_by_capacity_static",
... | 4 | null | Implement the Python class `TestLimitByCapacityAPI` described below.
Class description:
TestLimitByCapacityAPI
Method signatures and docstrings:
- def init_test_case(self): init_test_case
- def setUp(self): setUp
- def test_MoE_limit_by_capacity_static(self): test_MoE_limit_by_capacity_static
- def test_MoE_limit_by_... | Implement the Python class `TestLimitByCapacityAPI` described below.
Class description:
TestLimitByCapacityAPI
Method signatures and docstrings:
- def init_test_case(self): init_test_case
- def setUp(self): setUp
- def test_MoE_limit_by_capacity_static(self): test_MoE_limit_by_capacity_static
- def test_MoE_limit_by_... | bd3790ce72a2a26611b5eda3901651b5a809348f | <|skeleton|>
class TestLimitByCapacityAPI:
"""TestLimitByCapacityAPI"""
def init_test_case(self):
"""init_test_case"""
<|body_0|>
def setUp(self):
"""setUp"""
<|body_1|>
def test_MoE_limit_by_capacity_static(self):
"""test_MoE_limit_by_capacity_static"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestLimitByCapacityAPI:
"""TestLimitByCapacityAPI"""
def init_test_case(self):
"""init_test_case"""
self.expert_count = np.random.randint(0, 1000, size=len(self.capacity) * self.n_worker)
self.out = limit_by_capacity(self.expert_count, self.capacity, self.n_worker)
self.ex... | the_stack_v2_python_sparse | distributed/CE_API/case/dist_MoE_limit_by_capacity.py | PaddlePaddle/PaddleTest | train | 42 |
3f9fdf7919f98171dfd68d7dc8854cd3f16cbe93 | [
"req_data, _ = init_views(request)\ndata = ExecutionLog.query_log_list(**req_data['data'])\nreturn Response(data)",
"req_data, _ = init_views(request)\ntry:\n log = ExecutionLog.create_log(**req_data['data'])\n data = {'id': log.pk}\nexcept Exception as e:\n logger.error(f'create_log error:{str(e)}')\n ... | <|body_start_0|>
req_data, _ = init_views(request)
data = ExecutionLog.query_log_list(**req_data['data'])
return Response(data)
<|end_body_0|>
<|body_start_1|>
req_data, _ = init_views(request)
try:
log = ExecutionLog.create_log(**req_data['data'])
data =... | 日志操作 | ExecutionLogViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExecutionLogViewSet:
"""日志操作"""
def describe_logs(self, request):
"""获取日志"""
<|body_0|>
def create_log(self, request):
"""创建日志"""
<|body_1|>
def update_log(self, request):
"""更新日志"""
<|body_2|>
def describe_records(self, request)... | stack_v2_sparse_classes_36k_train_010616 | 4,019 | permissive | [
{
"docstring": "获取日志",
"name": "describe_logs",
"signature": "def describe_logs(self, request)"
},
{
"docstring": "创建日志",
"name": "create_log",
"signature": "def create_log(self, request)"
},
{
"docstring": "更新日志",
"name": "update_log",
"signature": "def update_log(self, ... | 4 | null | Implement the Python class `ExecutionLogViewSet` described below.
Class description:
日志操作
Method signatures and docstrings:
- def describe_logs(self, request): 获取日志
- def create_log(self, request): 创建日志
- def update_log(self, request): 更新日志
- def describe_records(self, request): 获取平台执行记录 | Implement the Python class `ExecutionLogViewSet` described below.
Class description:
日志操作
Method signatures and docstrings:
- def describe_logs(self, request): 获取日志
- def create_log(self, request): 创建日志
- def update_log(self, request): 更新日志
- def describe_records(self, request): 获取平台执行记录
<|skeleton|>
class Execution... | da37fb2197142eae32158cdb5c2b658100133fff | <|skeleton|>
class ExecutionLogViewSet:
"""日志操作"""
def describe_logs(self, request):
"""获取日志"""
<|body_0|>
def create_log(self, request):
"""创建日志"""
<|body_1|>
def update_log(self, request):
"""更新日志"""
<|body_2|>
def describe_records(self, request)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExecutionLogViewSet:
"""日志操作"""
def describe_logs(self, request):
"""获取日志"""
req_data, _ = init_views(request)
data = ExecutionLog.query_log_list(**req_data['data'])
return Response(data)
def create_log(self, request):
"""创建日志"""
req_data, _ = init_vie... | the_stack_v2_python_sparse | module_intent/views/log_views.py | cz-qq/bk-chatbot | train | 0 |
2fff44aeceecc4448a2cc5c15d2a44f1a1e5be9d | [
"produto = get_a_product('id', id)\nif not produto:\n api.abort(404)\nelse:\n return produto",
"produto = get_a_product('id', id)\ndata = request.json\nif not produto:\n api.abort(404, 'Produto não Encontrado.')\nif not data:\n api.abort(400, 'Payload vazio.')\nif data.get('fornecedor_id', 0) != 0:\n ... | <|body_start_0|>
produto = get_a_product('id', id)
if not produto:
api.abort(404)
else:
return produto
<|end_body_0|>
<|body_start_1|>
produto = get_a_product('id', id)
data = request.json
if not produto:
api.abort(404, 'Produto não En... | ProdutoID | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProdutoID:
def get(self, id):
"""Obtem informações de um produto com base no seu id"""
<|body_0|>
def patch(self, id):
"""Atualiza um produto Obs: para inativar, coloque 'ativo': false"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
produto = get_a_... | stack_v2_sparse_classes_36k_train_010617 | 3,686 | no_license | [
{
"docstring": "Obtem informações de um produto com base no seu id",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "Atualiza um produto Obs: para inativar, coloque 'ativo': false",
"name": "patch",
"signature": "def patch(self, id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019572 | Implement the Python class `ProdutoID` described below.
Class description:
Implement the ProdutoID class.
Method signatures and docstrings:
- def get(self, id): Obtem informações de um produto com base no seu id
- def patch(self, id): Atualiza um produto Obs: para inativar, coloque 'ativo': false | Implement the Python class `ProdutoID` described below.
Class description:
Implement the ProdutoID class.
Method signatures and docstrings:
- def get(self, id): Obtem informações de um produto com base no seu id
- def patch(self, id): Atualiza um produto Obs: para inativar, coloque 'ativo': false
<|skeleton|>
class ... | a86fcb085af8567a661d47876f8b9f13d7b062a9 | <|skeleton|>
class ProdutoID:
def get(self, id):
"""Obtem informações de um produto com base no seu id"""
<|body_0|>
def patch(self, id):
"""Atualiza um produto Obs: para inativar, coloque 'ativo': false"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProdutoID:
def get(self, id):
"""Obtem informações de um produto com base no seu id"""
produto = get_a_product('id', id)
if not produto:
api.abort(404)
else:
return produto
def patch(self, id):
"""Atualiza um produto Obs: para inativar, colo... | the_stack_v2_python_sparse | backend/app/main/controller/produto_controller.py | AnderSilva/ozomali | train | 1 | |
c48de70ab2a8c8a796ada413eb127a27af0c09e4 | [
"reader = build.io.RombuildLogBinarySizeReader(os.path.join(os.environ['TEST_DATA'], 'data/build/io/test_rom.log'))\nreader_iter = iter(reader)\nbinary, size, rom_type = reader_iter.next()\nassert binary == '\\\\epoc32\\\\release\\\\ARMV5\\\\urel\\\\__ekern.exe'\nassert size == 221788\nassert rom_type == 'rom'\nbin... | <|body_start_0|>
reader = build.io.RombuildLogBinarySizeReader(os.path.join(os.environ['TEST_DATA'], 'data/build/io/test_rom.log'))
reader_iter = iter(reader)
binary, size, rom_type = reader_iter.next()
assert binary == '\\epoc32\\release\\ARMV5\\urel\\__ekern.exe'
assert size ==... | Test reading Symbian ROM build logs for extracting binaries and their sizes. | RombuildLogBinarySizeReaderTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RombuildLogBinarySizeReaderTest:
"""Test reading Symbian ROM build logs for extracting binaries and their sizes."""
def test_rom_log_parsing(self):
"""Basic ROM log binary size parsing."""
<|body_0|>
def test_rofs_log_parsing(self):
"""Basic ROFS log binary size ... | stack_v2_sparse_classes_36k_train_010618 | 3,517 | no_license | [
{
"docstring": "Basic ROM log binary size parsing.",
"name": "test_rom_log_parsing",
"signature": "def test_rom_log_parsing(self)"
},
{
"docstring": "Basic ROFS log binary size parsing.",
"name": "test_rofs_log_parsing",
"signature": "def test_rofs_log_parsing(self)"
}
] | 2 | null | Implement the Python class `RombuildLogBinarySizeReaderTest` described below.
Class description:
Test reading Symbian ROM build logs for extracting binaries and their sizes.
Method signatures and docstrings:
- def test_rom_log_parsing(self): Basic ROM log binary size parsing.
- def test_rofs_log_parsing(self): Basic ... | Implement the Python class `RombuildLogBinarySizeReaderTest` described below.
Class description:
Test reading Symbian ROM build logs for extracting binaries and their sizes.
Method signatures and docstrings:
- def test_rom_log_parsing(self): Basic ROM log binary size parsing.
- def test_rofs_log_parsing(self): Basic ... | f458a4ce83f74d603362fe6b71eaa647ccc62fee | <|skeleton|>
class RombuildLogBinarySizeReaderTest:
"""Test reading Symbian ROM build logs for extracting binaries and their sizes."""
def test_rom_log_parsing(self):
"""Basic ROM log binary size parsing."""
<|body_0|>
def test_rofs_log_parsing(self):
"""Basic ROFS log binary size ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RombuildLogBinarySizeReaderTest:
"""Test reading Symbian ROM build logs for extracting binaries and their sizes."""
def test_rom_log_parsing(self):
"""Basic ROM log binary size parsing."""
reader = build.io.RombuildLogBinarySizeReader(os.path.join(os.environ['TEST_DATA'], 'data/build/io/t... | the_stack_v2_python_sparse | buildframework/helium/sf/python/pythoncore/lib/pythoncoretests/test_build_io.py | anagovitsyn/oss.FCL.sftools.dev.build | train | 0 |
a9747852ad7e169afc32b526da3bb5c13aa403a9 | [
"if not grads_splits or grads_splits[0] is None:\n return None\nif isinstance(grads_splits[0], ops.IndexedSlices):\n tensor_values, tensor_indices = zip(*[(t.values, t.indices) for t in grads_splits])\n dense_shape = grads_splits[0].dense_shape\n accumulated_values = array_ops.concat(tensor_values, axis... | <|body_start_0|>
if not grads_splits or grads_splits[0] is None:
return None
if isinstance(grads_splits[0], ops.IndexedSlices):
tensor_values, tensor_indices = zip(*[(t.values, t.indices) for t in grads_splits])
dense_shape = grads_splits[0].dense_shape
ac... | Class to apply pipeline in optimizer. | PipelinedOptimizer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PipelinedOptimizer:
"""Class to apply pipeline in optimizer."""
def _accumulate_grads(self, grads_splits):
"""Accumulate and compute gradients. Args: grads_splits: List of `Tensor` or list of list of tensors the same size as `ys` and holding the gradients computed for each y in `ys`.... | stack_v2_sparse_classes_36k_train_010619 | 8,904 | permissive | [
{
"docstring": "Accumulate and compute gradients. Args: grads_splits: List of `Tensor` or list of list of tensors the same size as `ys` and holding the gradients computed for each y in `ys`. Returns: Accumulated gradients.",
"name": "_accumulate_grads",
"signature": "def _accumulate_grads(self, grads_sp... | 2 | null | Implement the Python class `PipelinedOptimizer` described below.
Class description:
Class to apply pipeline in optimizer.
Method signatures and docstrings:
- def _accumulate_grads(self, grads_splits): Accumulate and compute gradients. Args: grads_splits: List of `Tensor` or list of list of tensors the same size as `y... | Implement the Python class `PipelinedOptimizer` described below.
Class description:
Class to apply pipeline in optimizer.
Method signatures and docstrings:
- def _accumulate_grads(self, grads_splits): Accumulate and compute gradients. Args: grads_splits: List of `Tensor` or list of list of tensors the same size as `y... | 4486ba138515a1dbdb6f7d542d7ad23a27476524 | <|skeleton|>
class PipelinedOptimizer:
"""Class to apply pipeline in optimizer."""
def _accumulate_grads(self, grads_splits):
"""Accumulate and compute gradients. Args: grads_splits: List of `Tensor` or list of list of tensors the same size as `ys` and holding the gradients computed for each y in `ys`.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PipelinedOptimizer:
"""Class to apply pipeline in optimizer."""
def _accumulate_grads(self, grads_splits):
"""Accumulate and compute gradients. Args: grads_splits: List of `Tensor` or list of list of tensors the same size as `ys` and holding the gradients computed for each y in `ys`. Returns: Acc... | the_stack_v2_python_sparse | hybridbackend/tensorflow/pipeline/pipeline_lib.py | DeepRec-AI/HybridBackend | train | 10 |
7dedab78759d8415f084868b70514a3c0dfd694e | [
"wordDict = set(wordDict)\nn = len(s)\n\n@lru_cache(None)\ndef dfs(i):\n if i == n:\n return True\n for j in range(i + 1, n + 1):\n if s[i:j] in wordDict:\n if dfs(j):\n return True\n return False\nreturn dfs(0)",
"n = len(s)\nif len(s) == 0:\n return False\nwor... | <|body_start_0|>
wordDict = set(wordDict)
n = len(s)
@lru_cache(None)
def dfs(i):
if i == n:
return True
for j in range(i + 1, n + 1):
if s[i:j] in wordDict:
if dfs(j):
return True
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordBreak(self, s: str, wordDict) -> bool:
"""DFS + Memorization"""
<|body_0|>
def wordBreak(self, s: str, wordDict) -> bool:
"""Down Top DP, Time: O(m + n^2), Space: O(n+m), n: len(s), m: len(wordDict)"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_36k_train_010620 | 1,753 | no_license | [
{
"docstring": "DFS + Memorization",
"name": "wordBreak",
"signature": "def wordBreak(self, s: str, wordDict) -> bool"
},
{
"docstring": "Down Top DP, Time: O(m + n^2), Space: O(n+m), n: len(s), m: len(wordDict)",
"name": "wordBreak",
"signature": "def wordBreak(self, s: str, wordDict) -... | 2 | stack_v2_sparse_classes_30k_train_012181 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(self, s: str, wordDict) -> bool: DFS + Memorization
- def wordBreak(self, s: str, wordDict) -> bool: Down Top DP, Time: O(m + n^2), Space: O(n+m), n: len(s), m: len... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(self, s: str, wordDict) -> bool: DFS + Memorization
- def wordBreak(self, s: str, wordDict) -> bool: Down Top DP, Time: O(m + n^2), Space: O(n+m), n: len(s), m: len... | 72136e3487d239f5b37e2d6393e034262a6bf599 | <|skeleton|>
class Solution:
def wordBreak(self, s: str, wordDict) -> bool:
"""DFS + Memorization"""
<|body_0|>
def wordBreak(self, s: str, wordDict) -> bool:
"""Down Top DP, Time: O(m + n^2), Space: O(n+m), n: len(s), m: len(wordDict)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def wordBreak(self, s: str, wordDict) -> bool:
"""DFS + Memorization"""
wordDict = set(wordDict)
n = len(s)
@lru_cache(None)
def dfs(i):
if i == n:
return True
for j in range(i + 1, n + 1):
if s[i:j] in ... | the_stack_v2_python_sparse | python/139-Word Break.py | cwza/leetcode | train | 0 | |
9a7f7a6c373410856d4dd6b27b8889e4f655f76f | [
"head = self.reverseListIterative(head)\nif n == 1:\n return self.reverseListIterative(head.next)\nprev, cur = (None, head)\nfor i in range(n - 1):\n prev = cur\n cur = cur.next\nprev.next = cur.next\nreturn self.reverseListIterative(head)",
"prev = None\nwhile head:\n cur = head\n head = head.next... | <|body_start_0|>
head = self.reverseListIterative(head)
if n == 1:
return self.reverseListIterative(head.next)
prev, cur = (None, head)
for i in range(n - 1):
prev = cur
cur = cur.next
prev.next = cur.next
return self.reverseListIterati... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeNthFromEnd(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_0|>
def reverseListIterative(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
head = ... | stack_v2_sparse_classes_36k_train_010621 | 1,071 | no_license | [
{
"docstring": ":type head: ListNode :type n: int :rtype: ListNode",
"name": "removeNthFromEnd",
"signature": "def removeNthFromEnd(self, head, n)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "reverseListIterative",
"signature": "def reverseListIterative(self, head... | 2 | stack_v2_sparse_classes_30k_train_014399 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd(self, head, n): :type head: ListNode :type n: int :rtype: ListNode
- def reverseListIterative(self, head): :type head: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd(self, head, n): :type head: ListNode :type n: int :rtype: ListNode
- def reverseListIterative(self, head): :type head: ListNode :rtype: ListNode
<|skeleton|... | 7fa5a3f25aaaa3db751c08305bc73bacfc8432f3 | <|skeleton|>
class Solution:
def removeNthFromEnd(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_0|>
def reverseListIterative(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def removeNthFromEnd(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
head = self.reverseListIterative(head)
if n == 1:
return self.reverseListIterative(head.next)
prev, cur = (None, head)
for i in range(n - 1):
... | the_stack_v2_python_sparse | Python/remove-nth-from-end.py | WangsirCode/leetcode | train | 0 | |
cd3ebe8a1672414df0f42b883ec3709cd46ca958 | [
"email = self.cleaned_data['email']\nself.users_cache = User.objects.filter(email__iexact=email, is_active=True)\nif not len(self.users_cache):\n raise forms.ValidationError(self.error_messages['unknown'])\nif any((user.password == UNUSABLE_PASSWORD for user in self.users_cache)):\n raise forms.ValidationErro... | <|body_start_0|>
email = self.cleaned_data['email']
self.users_cache = User.objects.filter(email__iexact=email, is_active=True)
if not len(self.users_cache):
raise forms.ValidationError(self.error_messages['unknown'])
if any((user.password == UNUSABLE_PASSWORD for user in sel... | PasswordResetForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PasswordResetForm:
def clean_email(self):
"""Validates that an active user exists with the given email address."""
<|body_0|>
def save(self, domain_override=None, subject_template_name='registration/password_reset_subject.txt', email_template_name='registration/password_rese... | stack_v2_sparse_classes_36k_train_010622 | 8,177 | no_license | [
{
"docstring": "Validates that an active user exists with the given email address.",
"name": "clean_email",
"signature": "def clean_email(self)"
},
{
"docstring": "Generates a one-use only link for resetting password and sends to the user.",
"name": "save",
"signature": "def save(self, d... | 2 | stack_v2_sparse_classes_30k_train_016079 | Implement the Python class `PasswordResetForm` described below.
Class description:
Implement the PasswordResetForm class.
Method signatures and docstrings:
- def clean_email(self): Validates that an active user exists with the given email address.
- def save(self, domain_override=None, subject_template_name='registra... | Implement the Python class `PasswordResetForm` described below.
Class description:
Implement the PasswordResetForm class.
Method signatures and docstrings:
- def clean_email(self): Validates that an active user exists with the given email address.
- def save(self, domain_override=None, subject_template_name='registra... | 5650fbe59f8dfef836503b8092080f06dd214c2c | <|skeleton|>
class PasswordResetForm:
def clean_email(self):
"""Validates that an active user exists with the given email address."""
<|body_0|>
def save(self, domain_override=None, subject_template_name='registration/password_reset_subject.txt', email_template_name='registration/password_rese... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PasswordResetForm:
def clean_email(self):
"""Validates that an active user exists with the given email address."""
email = self.cleaned_data['email']
self.users_cache = User.objects.filter(email__iexact=email, is_active=True)
if not len(self.users_cache):
raise form... | the_stack_v2_python_sparse | apps/user_profile/forms.py | biznixcn/WR | train | 0 | |
c5993e3b091914994612ba76aee13b6bd3a73d8b | [
"self.assertIsNotNone(model_utils.get_weight_parameter(MaskConv2d(32, 32, 3)))\nweight_groups = model_utils.get_weight_parameter(GroupConv2d(32, 64, 3, groups=2))\nself.assertIsNotNone(weight_groups)\nself.assertIsInstance(weight_groups, torch.Tensor)\nself.assertEqual(weight_groups.shape[0], 64)\nself.assertEqual(... | <|body_start_0|>
self.assertIsNotNone(model_utils.get_weight_parameter(MaskConv2d(32, 32, 3)))
weight_groups = model_utils.get_weight_parameter(GroupConv2d(32, 64, 3, groups=2))
self.assertIsNotNone(weight_groups)
self.assertIsInstance(weight_groups, torch.Tensor)
self.assertEqua... | TestModelUtils | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestModelUtils:
def test_get_weight_parameter(self):
"""Check whether parameters can be get from Module."""
<|body_0|>
def test_get_group_allocation(self):
"""Test GSP based group allocation."""
<|body_1|>
def test_is_gsp_satisfied(self):
"""Test... | stack_v2_sparse_classes_36k_train_010623 | 3,864 | permissive | [
{
"docstring": "Check whether parameters can be get from Module.",
"name": "test_get_weight_parameter",
"signature": "def test_get_weight_parameter(self)"
},
{
"docstring": "Test GSP based group allocation.",
"name": "test_get_group_allocation",
"signature": "def test_get_group_allocatio... | 5 | stack_v2_sparse_classes_30k_test_000332 | Implement the Python class `TestModelUtils` described below.
Class description:
Implement the TestModelUtils class.
Method signatures and docstrings:
- def test_get_weight_parameter(self): Check whether parameters can be get from Module.
- def test_get_group_allocation(self): Test GSP based group allocation.
- def te... | Implement the Python class `TestModelUtils` described below.
Class description:
Implement the TestModelUtils class.
Method signatures and docstrings:
- def test_get_weight_parameter(self): Check whether parameters can be get from Module.
- def test_get_group_allocation(self): Test GSP based group allocation.
- def te... | f81c417d3754102c902bd153809130e12607bd7d | <|skeleton|>
class TestModelUtils:
def test_get_weight_parameter(self):
"""Check whether parameters can be get from Module."""
<|body_0|>
def test_get_group_allocation(self):
"""Test GSP based group allocation."""
<|body_1|>
def test_is_gsp_satisfied(self):
"""Test... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestModelUtils:
def test_get_weight_parameter(self):
"""Check whether parameters can be get from Module."""
self.assertIsNotNone(model_utils.get_weight_parameter(MaskConv2d(32, 32, 3)))
weight_groups = model_utils.get_weight_parameter(GroupConv2d(32, 64, 3, groups=2))
self.asse... | the_stack_v2_python_sparse | gumi/model_utils_test.py | kumasento/gconv-prune | train | 10 | |
46b238e212e14c1bc720874bdfe8c685667a8479 | [
"if not points:\n return 0\npoints = sorted(points, key=lambda x: x[1])\nend = float('-inf')\nres = 0\nfor s, e in points:\n if s > end:\n end = e\n res += 1\nreturn res",
"if not points:\n return 0\npoints = sorted(points, key=lambda x: (x[0], x[1]))\nres = 0\nstart = points[0][0]\nend = p... | <|body_start_0|>
if not points:
return 0
points = sorted(points, key=lambda x: x[1])
end = float('-inf')
res = 0
for s, e in points:
if s > end:
end = e
res += 1
return res
<|end_body_0|>
<|body_start_1|>
if... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMinArrowShots(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_0|>
def force_findMinArrowShots(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not ... | stack_v2_sparse_classes_36k_train_010624 | 2,436 | no_license | [
{
"docstring": ":type points: List[List[int]] :rtype: int",
"name": "findMinArrowShots",
"signature": "def findMinArrowShots(self, points)"
},
{
"docstring": ":type points: List[List[int]] :rtype: int",
"name": "force_findMinArrowShots",
"signature": "def force_findMinArrowShots(self, po... | 2 | stack_v2_sparse_classes_30k_train_004012 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMinArrowShots(self, points): :type points: List[List[int]] :rtype: int
- def force_findMinArrowShots(self, points): :type points: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMinArrowShots(self, points): :type points: List[List[int]] :rtype: int
- def force_findMinArrowShots(self, points): :type points: List[List[int]] :rtype: int
<|skeleton|... | 8595b04cf5a024c2cd8a97f750d890a818568401 | <|skeleton|>
class Solution:
def findMinArrowShots(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_0|>
def force_findMinArrowShots(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findMinArrowShots(self, points):
""":type points: List[List[int]] :rtype: int"""
if not points:
return 0
points = sorted(points, key=lambda x: x[1])
end = float('-inf')
res = 0
for s, e in points:
if s > end:
... | the_stack_v2_python_sparse | python/452.minimum-number-of-arrows-to-burst-balloons.py | tainenko/Leetcode2019 | train | 5 | |
15738df061286b930ffd74a960dab282029e65a7 | [
"self = object.__new__(cls)\nself.name = cls.DEFAULT_NAME\nself.value = value\nself.max_per_guild = 1\nself.metadata_type = AutoModerationRuleTriggerMetadataBase\nreturn self",
"self.value = value\nself.name = name\nself.max_per_guild = max_per_guild\nself.metadata_type = metadata_type\nself.INSTANCES[value] = se... | <|body_start_0|>
self = object.__new__(cls)
self.name = cls.DEFAULT_NAME
self.value = value
self.max_per_guild = 1
self.metadata_type = AutoModerationRuleTriggerMetadataBase
return self
<|end_body_0|>
<|body_start_1|>
self.value = value
self.name = name
... | Represents an auto moderation rule's trigger type. Attributes ---------- value : `int` The Discord side identifier value of the auto moderation trigger type. name : `str` The default name of the auto moderation trigger type. max_per_guild : `int` The maximal amount of rules of this type per guild. metadata_type : `Auto... | AutoModerationRuleTriggerType | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoModerationRuleTriggerType:
"""Represents an auto moderation rule's trigger type. Attributes ---------- value : `int` The Discord side identifier value of the auto moderation trigger type. name : `str` The default name of the auto moderation trigger type. max_per_guild : `int` The maximal amou... | stack_v2_sparse_classes_36k_train_010625 | 7,201 | permissive | [
{
"docstring": "Creates a new auto moderation trigger type with the given value. Parameters ---------- value : `int` The auto moderation trigger type's identifier value. Returns ------- self : ``AutoModerationRuleTriggerType`` The created instance.",
"name": "_from_value",
"signature": "def _from_value(... | 2 | stack_v2_sparse_classes_30k_train_013276 | Implement the Python class `AutoModerationRuleTriggerType` described below.
Class description:
Represents an auto moderation rule's trigger type. Attributes ---------- value : `int` The Discord side identifier value of the auto moderation trigger type. name : `str` The default name of the auto moderation trigger type.... | Implement the Python class `AutoModerationRuleTriggerType` described below.
Class description:
Represents an auto moderation rule's trigger type. Attributes ---------- value : `int` The Discord side identifier value of the auto moderation trigger type. name : `str` The default name of the auto moderation trigger type.... | 53f24fdb38459dc5a4fd04f11bdbfee8295b76a4 | <|skeleton|>
class AutoModerationRuleTriggerType:
"""Represents an auto moderation rule's trigger type. Attributes ---------- value : `int` The Discord side identifier value of the auto moderation trigger type. name : `str` The default name of the auto moderation trigger type. max_per_guild : `int` The maximal amou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutoModerationRuleTriggerType:
"""Represents an auto moderation rule's trigger type. Attributes ---------- value : `int` The Discord side identifier value of the auto moderation trigger type. name : `str` The default name of the auto moderation trigger type. max_per_guild : `int` The maximal amount of rules o... | the_stack_v2_python_sparse | hata/discord/auto_moderation/rule/preinstanced.py | HuyaneMatsu/hata | train | 3 |
8f40f2ae3520c650f145df22a4fb6f7571ccb74b | [
"if not email:\n raise ValueError('Users must have an email address')\nuser = self.model(email=self.normalize_email(email))\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(email, password=password)\nuser.is_superuser = True\nuser.save(using=self._db)\nreturn user... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email))
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<|body_start_1|>
user = self.create_user(... | ParticipantManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParticipantManager:
def create_user(self, email, password=None):
"""Creates and saves a User with the given email and password."""
<|body_0|>
def create_superuser(self, email, password):
"""Creates and saves a superuser with the given email and password."""
<... | stack_v2_sparse_classes_36k_train_010626 | 9,725 | no_license | [
{
"docstring": "Creates and saves a User with the given email and password.",
"name": "create_user",
"signature": "def create_user(self, email, password=None)"
},
{
"docstring": "Creates and saves a superuser with the given email and password.",
"name": "create_superuser",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_004207 | Implement the Python class `ParticipantManager` described below.
Class description:
Implement the ParticipantManager class.
Method signatures and docstrings:
- def create_user(self, email, password=None): Creates and saves a User with the given email and password.
- def create_superuser(self, email, password): Create... | Implement the Python class `ParticipantManager` described below.
Class description:
Implement the ParticipantManager class.
Method signatures and docstrings:
- def create_user(self, email, password=None): Creates and saves a User with the given email and password.
- def create_superuser(self, email, password): Create... | 440316ae1dea4feff5b6a9ac6f40c19382022d91 | <|skeleton|>
class ParticipantManager:
def create_user(self, email, password=None):
"""Creates and saves a User with the given email and password."""
<|body_0|>
def create_superuser(self, email, password):
"""Creates and saves a superuser with the given email and password."""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParticipantManager:
def create_user(self, email, password=None):
"""Creates and saves a User with the given email and password."""
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email))
user.set_passwo... | the_stack_v2_python_sparse | wsgi/zosiaproject/users/models.py | kamarkiewicz/zosiaproject | train | 0 | |
6b99b0387df1979e24cec71c4d056222197229ec | [
"filters = {}\nif not is_master(HitsService.DB, session['id']):\n user = get_user(HitsService.DB, {'_id': ObjectId(session['id'])})\n user_list = [user['_id']]\n if 'subordinates' in user:\n user_list = user_list + user['subordinates']\n user_list.append(None)\n filters = {'user_id': {'$in... | <|body_start_0|>
filters = {}
if not is_master(HitsService.DB, session['id']):
user = get_user(HitsService.DB, {'_id': ObjectId(session['id'])})
user_list = [user['_id']]
if 'subordinates' in user:
user_list = user_list + user['subordinates']
... | User service functions | HitsService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HitsService:
"""User service functions"""
def list(session):
"""Return all available hits according the user :param session: Current user session :return: list of hits"""
<|body_0|>
def fetch_hit(session, hit_id):
"""Fetch hit information according current sessio... | stack_v2_sparse_classes_36k_train_010627 | 5,575 | no_license | [
{
"docstring": "Return all available hits according the user :param session: Current user session :return: list of hits",
"name": "list",
"signature": "def list(session)"
},
{
"docstring": "Fetch hit information according current session :param session: current user session :param hit_id: Hit id... | 5 | stack_v2_sparse_classes_30k_train_019313 | Implement the Python class `HitsService` described below.
Class description:
User service functions
Method signatures and docstrings:
- def list(session): Return all available hits according the user :param session: Current user session :return: list of hits
- def fetch_hit(session, hit_id): Fetch hit information acc... | Implement the Python class `HitsService` described below.
Class description:
User service functions
Method signatures and docstrings:
- def list(session): Return all available hits according the user :param session: Current user session :return: list of hits
- def fetch_hit(session, hit_id): Fetch hit information acc... | a8ba08084c3a1191b83d91ae460269139ba20fa2 | <|skeleton|>
class HitsService:
"""User service functions"""
def list(session):
"""Return all available hits according the user :param session: Current user session :return: list of hits"""
<|body_0|>
def fetch_hit(session, hit_id):
"""Fetch hit information according current sessio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HitsService:
"""User service functions"""
def list(session):
"""Return all available hits according the user :param session: Current user session :return: list of hits"""
filters = {}
if not is_master(HitsService.DB, session['id']):
user = get_user(HitsService.DB, {'_i... | the_stack_v2_python_sparse | src/services/hits.py | danteay/hitmen | train | 0 |
ccfd8957910071eadad2aa6d3c7dd8158a5f81d8 | [
"logging.Handler.__init__(self)\nself.recordQueue = Queue.Queue(250)\nself.logRelay = LogRelayThread(self.recordQueue)\nself.logRelay.setName('LogRelay')\nself.logRelay.start()",
"try:\n if record is not None:\n self.recordQueue.put_nowait(record)\nexcept Exception:\n pass"
] | <|body_start_0|>
logging.Handler.__init__(self)
self.recordQueue = Queue.Queue(250)
self.logRelay = LogRelayThread(self.recordQueue)
self.logRelay.setName('LogRelay')
self.logRelay.start()
<|end_body_0|>
<|body_start_1|>
try:
if record is not None:
... | The mms remote log handler | MmsRemoteHandler | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MmsRemoteHandler:
"""The mms remote log handler"""
def __init__(self):
"""Construct a new object"""
<|body_0|>
def emit(self, record):
"""Send the record to the remote servers"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
logging.Handler.__ini... | stack_v2_sparse_classes_36k_train_010628 | 3,623 | permissive | [
{
"docstring": "Construct a new object",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Send the record to the remote servers",
"name": "emit",
"signature": "def emit(self, record)"
}
] | 2 | null | Implement the Python class `MmsRemoteHandler` described below.
Class description:
The mms remote log handler
Method signatures and docstrings:
- def __init__(self): Construct a new object
- def emit(self, record): Send the record to the remote servers | Implement the Python class `MmsRemoteHandler` described below.
Class description:
The mms remote log handler
Method signatures and docstrings:
- def __init__(self): Construct a new object
- def emit(self, record): Send the record to the remote servers
<|skeleton|>
class MmsRemoteHandler:
"""The mms remote log ha... | cef29f01658c845564a5044b48b4cf19efcaa4d6 | <|skeleton|>
class MmsRemoteHandler:
"""The mms remote log handler"""
def __init__(self):
"""Construct a new object"""
<|body_0|>
def emit(self, record):
"""Send the record to the remote servers"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MmsRemoteHandler:
"""The mms remote log handler"""
def __init__(self):
"""Construct a new object"""
logging.Handler.__init__(self)
self.recordQueue = Queue.Queue(250)
self.logRelay = LogRelayThread(self.recordQueue)
self.logRelay.setName('LogRelay')
self.lo... | the_stack_v2_python_sparse | vendor/mms-agent/logConfig.py | quanganhdo/NewsBlur | train | 1 |
b7ef0f092461b72c68b2e8a3e9693318fe743727 | [
"if not root:\n return '#'\ndeq = deque([root])\nresult = ['#']\nwhile deq:\n node = deq.popleft()\n if node:\n result.append(str(node.val))\n deq.append(node.left)\n deq.append(node.right)\n else:\n result.append('#')\nreturn result",
"if data == '#':\n return None\ndeq... | <|body_start_0|>
if not root:
return '#'
deq = deque([root])
result = ['#']
while deq:
node = deq.popleft()
if node:
result.append(str(node.val))
deq.append(node.left)
deq.append(node.right)
e... | 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_010629 | 1,406 | 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_018637 | 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:... | a0d466f94325f657f180f7a46e4f173ebe7de2b2 | <|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"""
if not root:
return '#'
deq = deque([root])
result = ['#']
while deq:
node = deq.popleft()
if node:
result.app... | the_stack_v2_python_sparse | 트리/트리_LeetCode_297.py | Yoo-su/python-algorithm | train | 0 | |
c761f8ab15f8d65a354acc1814cd3da652318a6b | [
"data = label_file_line.split(' ')\ndata[1:] = [float(x) for x in data[1:]]\nself.type = data[0]\nself.truncation = data[1]\nself.occlusion = int(data[2])\nself.alpha = data[3]\nself.xmin = data[4]\nself.ymin = data[5]\nself.xmax = data[6]\nself.ymax = data[7]\nself.box2d = np.array([self.xmin, self.ymin, self.xmax... | <|body_start_0|>
data = label_file_line.split(' ')
data[1:] = [float(x) for x in data[1:]]
self.type = data[0]
self.truncation = data[1]
self.occlusion = int(data[2])
self.alpha = data[3]
self.xmin = data[4]
self.ymin = data[5]
self.xmax = data[6]
... | 3d object label | Object3d | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Object3d:
"""3d object label"""
def __init__(self, label_file_line):
"""type: 'Car', 'Van', 'Truck', 'Pedestrian', 'Person_sitting', 'Cyclist', 'Tram', 'Misc' or 'DontCare' truncated: Float, 0: non-truncated or 1: truncated truncated which refers to the object leaving image boundarie... | stack_v2_sparse_classes_36k_train_010630 | 23,592 | no_license | [
{
"docstring": "type: 'Car', 'Van', 'Truck', 'Pedestrian', 'Person_sitting', 'Cyclist', 'Tram', 'Misc' or 'DontCare' truncated: Float, 0: non-truncated or 1: truncated truncated which refers to the object leaving image boundaries occluded: Integer (0, 1, 2, 3) indicating occlusion state: 0 = fully visible, 1 = ... | 2 | stack_v2_sparse_classes_30k_train_001120 | Implement the Python class `Object3d` described below.
Class description:
3d object label
Method signatures and docstrings:
- def __init__(self, label_file_line): type: 'Car', 'Van', 'Truck', 'Pedestrian', 'Person_sitting', 'Cyclist', 'Tram', 'Misc' or 'DontCare' truncated: Float, 0: non-truncated or 1: truncated tru... | Implement the Python class `Object3d` described below.
Class description:
3d object label
Method signatures and docstrings:
- def __init__(self, label_file_line): type: 'Car', 'Van', 'Truck', 'Pedestrian', 'Person_sitting', 'Cyclist', 'Tram', 'Misc' or 'DontCare' truncated: Float, 0: non-truncated or 1: truncated tru... | 0c28c3cd18e367fb72745ec95d8bd5c994a494ba | <|skeleton|>
class Object3d:
"""3d object label"""
def __init__(self, label_file_line):
"""type: 'Car', 'Van', 'Truck', 'Pedestrian', 'Person_sitting', 'Cyclist', 'Tram', 'Misc' or 'DontCare' truncated: Float, 0: non-truncated or 1: truncated truncated which refers to the object leaving image boundarie... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Object3d:
"""3d object label"""
def __init__(self, label_file_line):
"""type: 'Car', 'Van', 'Truck', 'Pedestrian', 'Person_sitting', 'Cyclist', 'Tram', 'Misc' or 'DontCare' truncated: Float, 0: non-truncated or 1: truncated truncated which refers to the object leaving image boundaries occluded: I... | the_stack_v2_python_sparse | visualize_kitti/utils/kitti_util.py | enginBozkurt/visualisation-perception-3D | train | 0 |
23e4b14a5f6f34cc9d5b2970f6740700684a6ec2 | [
"if 'model' in blend_coord and model_id_attr is None:\n raise ValueError('model_id_attr required to blend over {}'.format(blend_coord))\nif 'model' not in blend_coord and (model_id_attr is not None and record_run_attr is None):\n warnings.warn('model_id_attr not required for blending over {} - will be ignored... | <|body_start_0|>
if 'model' in blend_coord and model_id_attr is None:
raise ValueError('model_id_attr required to blend over {}'.format(blend_coord))
if 'model' not in blend_coord and (model_id_attr is not None and record_run_attr is None):
warnings.warn('model_id_attr not requir... | Prepares cubes for cycle and grid blending | MergeCubesForWeightedBlending | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MergeCubesForWeightedBlending:
"""Prepares cubes for cycle and grid blending"""
def __init__(self, blend_coord: str, weighting_coord: Optional[str]=None, model_id_attr: Optional[str]=None, record_run_attr: Optional[str]=None) -> None:
"""Initialise the class Args: blend_coord: Name o... | stack_v2_sparse_classes_36k_train_010631 | 30,444 | permissive | [
{
"docstring": "Initialise the class Args: blend_coord: Name of coordinate over which blending will be performed. For multi-model blending this is flexible to any string containing \"model\". For all other coordinates this is prescriptive: cube.coord(blend_coord) must return an iris.coords.Coord instance for al... | 5 | stack_v2_sparse_classes_30k_train_012827 | Implement the Python class `MergeCubesForWeightedBlending` described below.
Class description:
Prepares cubes for cycle and grid blending
Method signatures and docstrings:
- def __init__(self, blend_coord: str, weighting_coord: Optional[str]=None, model_id_attr: Optional[str]=None, record_run_attr: Optional[str]=None... | Implement the Python class `MergeCubesForWeightedBlending` described below.
Class description:
Prepares cubes for cycle and grid blending
Method signatures and docstrings:
- def __init__(self, blend_coord: str, weighting_coord: Optional[str]=None, model_id_attr: Optional[str]=None, record_run_attr: Optional[str]=None... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class MergeCubesForWeightedBlending:
"""Prepares cubes for cycle and grid blending"""
def __init__(self, blend_coord: str, weighting_coord: Optional[str]=None, model_id_attr: Optional[str]=None, record_run_attr: Optional[str]=None) -> None:
"""Initialise the class Args: blend_coord: Name o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MergeCubesForWeightedBlending:
"""Prepares cubes for cycle and grid blending"""
def __init__(self, blend_coord: str, weighting_coord: Optional[str]=None, model_id_attr: Optional[str]=None, record_run_attr: Optional[str]=None) -> None:
"""Initialise the class Args: blend_coord: Name of coordinate ... | the_stack_v2_python_sparse | improver/blending/weighted_blend.py | metoppv/improver | train | 101 |
e2e1a9346f6aa62136a126aceeccc60576b8fc57 | [
"refDir = 'reference_files'\nx1 = x1\ncolor = color\nself.namesRef = namesRef\nLi_files = []\nmag_to_flux_files = []\nself.SNR = SNR\nself.dt_range = dt_range\nself.mag_range = mag_range\nfor name in namesRef:\n self.Li_files = ['{}/Li_{}_{}_{}.npy'.format(refDir, name, x1, color)]\n self.mag_to_flux_files = ... | <|body_start_0|>
refDir = 'reference_files'
x1 = x1
color = color
self.namesRef = namesRef
Li_files = []
mag_to_flux_files = []
self.SNR = SNR
self.dt_range = dt_range
self.mag_range = mag_range
for name in namesRef:
self.Li_fil... | Summary | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Summary:
def __init__(self, x1=-2.0, color=0.2, namesRef=['SNCosmo'], SNR=dict(zip('griz', [30.0, 40.0, 30.0, 20.0])), dt_range=[0.5, 30.0], mag_range=[21.0, 25.5]):
"""class to load metric data and estimate medians Parameters ---------------- x1: float, opt SN x1 (default: -2.0) color: ... | stack_v2_sparse_classes_36k_train_010632 | 7,601 | permissive | [
{
"docstring": "class to load metric data and estimate medians Parameters ---------------- x1: float, opt SN x1 (default: -2.0) color: float, opt SN color (default: 0.2) namesRef: list(str) list of reference names for reference LC (default: ['SNCosmo']) SNR: dict, opt SNR cut per band (default: dict(zip('griz',... | 3 | null | Implement the Python class `Summary` described below.
Class description:
Implement the Summary class.
Method signatures and docstrings:
- def __init__(self, x1=-2.0, color=0.2, namesRef=['SNCosmo'], SNR=dict(zip('griz', [30.0, 40.0, 30.0, 20.0])), dt_range=[0.5, 30.0], mag_range=[21.0, 25.5]): class to load metric da... | Implement the Python class `Summary` described below.
Class description:
Implement the Summary class.
Method signatures and docstrings:
- def __init__(self, x1=-2.0, color=0.2, namesRef=['SNCosmo'], SNR=dict(zip('griz', [30.0, 40.0, 30.0, 20.0])), dt_range=[0.5, 30.0], mag_range=[21.0, 25.5]): class to load metric da... | d42c7490ba5ff8c52f62e70a20c922172a6baff1 | <|skeleton|>
class Summary:
def __init__(self, x1=-2.0, color=0.2, namesRef=['SNCosmo'], SNR=dict(zip('griz', [30.0, 40.0, 30.0, 20.0])), dt_range=[0.5, 30.0], mag_range=[21.0, 25.5]):
"""class to load metric data and estimate medians Parameters ---------------- x1: float, opt SN x1 (default: -2.0) color: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Summary:
def __init__(self, x1=-2.0, color=0.2, namesRef=['SNCosmo'], SNR=dict(zip('griz', [30.0, 40.0, 30.0, 20.0])), dt_range=[0.5, 30.0], mag_range=[21.0, 25.5]):
"""class to load metric data and estimate medians Parameters ---------------- x1: float, opt SN x1 (default: -2.0) color: float, opt SN ... | the_stack_v2_python_sparse | plot_scripts/metrics/plot_summary.py | LSSTDESC/sn_pipe | train | 1 | |
b2f95b6ef25783caa94625309358c670a063f39b | [
"self._file = io.BytesIO(data)\nself._max_offset = len(data)\nself.audio_format = audio_format\nself._duration = len(data) / float(audio_format.bytes_per_second)",
"offset = int(timestamp * self.audio_format.bytes_per_second)\nif self.audio_format.bytes_per_sample == 2:\n offset &= 4294967294\nelif self.audio_... | <|body_start_0|>
self._file = io.BytesIO(data)
self._max_offset = len(data)
self.audio_format = audio_format
self._duration = len(data) / float(audio_format.bytes_per_second)
<|end_body_0|>
<|body_start_1|>
offset = int(timestamp * self.audio_format.bytes_per_second)
if ... | Helper class for default implementation of :class:`.StaticSource`. Do not use directly. This class is used internally by pyglet. Args: data (AudioData): The audio data. audio_format (AudioFormat): The audio format. | StaticMemorySource | [
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StaticMemorySource:
"""Helper class for default implementation of :class:`.StaticSource`. Do not use directly. This class is used internally by pyglet. Args: data (AudioData): The audio data. audio_format (AudioFormat): The audio format."""
def __init__(self, data, audio_format):
"""... | stack_v2_sparse_classes_36k_train_010633 | 17,960 | permissive | [
{
"docstring": "Construct a memory source over the given data buffer.",
"name": "__init__",
"signature": "def __init__(self, data, audio_format)"
},
{
"docstring": "Seek to given timestamp. Args: timestamp (float): Time where to seek in the source.",
"name": "seek",
"signature": "def see... | 3 | null | Implement the Python class `StaticMemorySource` described below.
Class description:
Helper class for default implementation of :class:`.StaticSource`. Do not use directly. This class is used internally by pyglet. Args: data (AudioData): The audio data. audio_format (AudioFormat): The audio format.
Method signatures a... | Implement the Python class `StaticMemorySource` described below.
Class description:
Helper class for default implementation of :class:`.StaticSource`. Do not use directly. This class is used internally by pyglet. Args: data (AudioData): The audio data. audio_format (AudioFormat): The audio format.
Method signatures a... | 094c638f0529fecab4e74556487b92453a78753c | <|skeleton|>
class StaticMemorySource:
"""Helper class for default implementation of :class:`.StaticSource`. Do not use directly. This class is used internally by pyglet. Args: data (AudioData): The audio data. audio_format (AudioFormat): The audio format."""
def __init__(self, data, audio_format):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StaticMemorySource:
"""Helper class for default implementation of :class:`.StaticSource`. Do not use directly. This class is used internally by pyglet. Args: data (AudioData): The audio data. audio_format (AudioFormat): The audio format."""
def __init__(self, data, audio_format):
"""Construct a m... | the_stack_v2_python_sparse | pyglet/media/codecs/base.py | pyglet/pyglet | train | 1,687 |
1752802e88ede6bf7271518731223039f8b9cda2 | [
"self.c = c\nself.beadList: list[tuple[Position, Chapter]] = []\nself.beadPointer = -1\nself.skipBeadUpdate = False",
"c = self.c\nif g.unitTesting or not self.beadList:\n return\nprint(f'NodeHisory.beadList: {c.shortFileName()}:')\nfor i, data in enumerate(self.beadList):\n p, chapter = data\n p_s = p.h... | <|body_start_0|>
self.c = c
self.beadList: list[tuple[Position, Chapter]] = []
self.beadPointer = -1
self.skipBeadUpdate = False
<|end_body_0|>
<|body_start_1|>
c = self.c
if g.unitTesting or not self.beadList:
return
print(f'NodeHisory.beadList: {c.s... | A class encapsulating knowledge of visited nodes. | NodeHistory | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NodeHistory:
"""A class encapsulating knowledge of visited nodes."""
def __init__(self, c: Cmdr) -> None:
"""Ctor for NodeHistory class."""
<|body_0|>
def dump(self) -> None:
"""Dump the beadList"""
<|body_1|>
def goNext(self) -> Optional[Position]:
... | stack_v2_sparse_classes_36k_train_010634 | 4,612 | permissive | [
{
"docstring": "Ctor for NodeHistory class.",
"name": "__init__",
"signature": "def __init__(self, c: Cmdr) -> None"
},
{
"docstring": "Dump the beadList",
"name": "dump",
"signature": "def dump(self) -> None"
},
{
"docstring": "Select the next node, if possible.",
"name": "g... | 6 | stack_v2_sparse_classes_30k_train_014985 | Implement the Python class `NodeHistory` described below.
Class description:
A class encapsulating knowledge of visited nodes.
Method signatures and docstrings:
- def __init__(self, c: Cmdr) -> None: Ctor for NodeHistory class.
- def dump(self) -> None: Dump the beadList
- def goNext(self) -> Optional[Position]: Sele... | Implement the Python class `NodeHistory` described below.
Class description:
A class encapsulating knowledge of visited nodes.
Method signatures and docstrings:
- def __init__(self, c: Cmdr) -> None: Ctor for NodeHistory class.
- def dump(self) -> None: Dump the beadList
- def goNext(self) -> Optional[Position]: Sele... | a3f6c3ebda805dc40cd93123948f153a26eccee5 | <|skeleton|>
class NodeHistory:
"""A class encapsulating knowledge of visited nodes."""
def __init__(self, c: Cmdr) -> None:
"""Ctor for NodeHistory class."""
<|body_0|>
def dump(self) -> None:
"""Dump the beadList"""
<|body_1|>
def goNext(self) -> Optional[Position]:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NodeHistory:
"""A class encapsulating knowledge of visited nodes."""
def __init__(self, c: Cmdr) -> None:
"""Ctor for NodeHistory class."""
self.c = c
self.beadList: list[tuple[Position, Chapter]] = []
self.beadPointer = -1
self.skipBeadUpdate = False
def dump... | the_stack_v2_python_sparse | leo/core/leoHistory.py | leo-editor/leo-editor | train | 1,671 |
0ca4e5753e68fc32ad0f818913fbb4ee4dbbd303 | [
"EventHandler.__init__(self)\nself._window = win\nself._board = board\nself._deck = Deck()\nself._deck.shuffle()\nself._card = self._deck.deal()\nself._card.addTo(win)\nself._button = Rectangle(50, 50, (600, 75))\nself._button.setFillColor('blue')\nwin.add(self._button)\nself._button.addHandler(self)",
"self._car... | <|body_start_0|>
EventHandler.__init__(self)
self._window = win
self._board = board
self._deck = Deck()
self._deck.shuffle()
self._card = self._deck.deal()
self._card.addTo(win)
self._button = Rectangle(50, 50, (600, 75))
self._button.setFillColor(... | Controller | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Controller:
def __init__(self, win, board):
"""Sets up objects in the window for display"""
<|body_0|>
def handleMouseRelease(self, event):
"""Handles the physical action of the user"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
EventHandler.__ini... | stack_v2_sparse_classes_36k_train_010635 | 17,247 | no_license | [
{
"docstring": "Sets up objects in the window for display",
"name": "__init__",
"signature": "def __init__(self, win, board)"
},
{
"docstring": "Handles the physical action of the user",
"name": "handleMouseRelease",
"signature": "def handleMouseRelease(self, event)"
}
] | 2 | null | Implement the Python class `Controller` described below.
Class description:
Implement the Controller class.
Method signatures and docstrings:
- def __init__(self, win, board): Sets up objects in the window for display
- def handleMouseRelease(self, event): Handles the physical action of the user | Implement the Python class `Controller` described below.
Class description:
Implement the Controller class.
Method signatures and docstrings:
- def __init__(self, win, board): Sets up objects in the window for display
- def handleMouseRelease(self, event): Handles the physical action of the user
<|skeleton|>
class C... | e5d96a65fc84481b85072cfb55dea9a0666634b5 | <|skeleton|>
class Controller:
def __init__(self, win, board):
"""Sets up objects in the window for display"""
<|body_0|>
def handleMouseRelease(self, event):
"""Handles the physical action of the user"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Controller:
def __init__(self, win, board):
"""Sets up objects in the window for display"""
EventHandler.__init__(self)
self._window = win
self._board = board
self._deck = Deck()
self._deck.shuffle()
self._card = self._deck.deal()
self._card.addT... | the_stack_v2_python_sparse | Games-2017/25/Game.py | paulmagnus/CSPy | train | 0 | |
f34db46d9a3cae823e53a5f0a68705d2546e425c | [
"i = 0\nj = 0\nstarIndex = -1\nwhile j < len(s):\n if i < len(p) and (p[i] == '?' or s[j] == p[i]):\n i += 1\n j += 1\n elif i < len(p) and p[i] == '*':\n starIndex = i\n match = j\n i += 1\n elif starIndex != -1:\n i = starIndex + 1\n match += 1\n j ... | <|body_start_0|>
i = 0
j = 0
starIndex = -1
while j < len(s):
if i < len(p) and (p[i] == '?' or s[j] == p[i]):
i += 1
j += 1
elif i < len(p) and p[i] == '*':
starIndex = i
match = j
i ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isMatch(self, s, p):
""":type s: str :type p: str :rtype: bool"""
<|body_0|>
def isMatch0(self, s, p):
""":type s: str :type p: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
i = 0
j = 0
starIndex = -1... | stack_v2_sparse_classes_36k_train_010636 | 1,536 | no_license | [
{
"docstring": ":type s: str :type p: str :rtype: bool",
"name": "isMatch",
"signature": "def isMatch(self, s, p)"
},
{
"docstring": ":type s: str :type p: str :rtype: bool",
"name": "isMatch0",
"signature": "def isMatch0(self, s, p)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isMatch(self, s, p): :type s: str :type p: str :rtype: bool
- def isMatch0(self, s, p): :type s: str :type p: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isMatch(self, s, p): :type s: str :type p: str :rtype: bool
- def isMatch0(self, s, p): :type s: str :type p: str :rtype: bool
<|skeleton|>
class Solution:
def isMatch(... | 9e49b2c6003b957276737005d4aaac276b44d251 | <|skeleton|>
class Solution:
def isMatch(self, s, p):
""":type s: str :type p: str :rtype: bool"""
<|body_0|>
def isMatch0(self, s, p):
""":type s: str :type p: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isMatch(self, s, p):
""":type s: str :type p: str :rtype: bool"""
i = 0
j = 0
starIndex = -1
while j < len(s):
if i < len(p) and (p[i] == '?' or s[j] == p[i]):
i += 1
j += 1
elif i < len(p) and p[i] =... | the_stack_v2_python_sparse | PythonCode/src/0044_Wildcard_Matching.py | oneyuan/CodeforFun | train | 0 | |
e5384eb43e13c957e1671e1a80f9f3d35df665c4 | [
"if timezoneName is None:\n timezoneName = self.defaultTimezoneName\ndt = timeutil.now(timezoneName)\nsource.reply(timeutil.format(dt, self.timeFormat))",
"if timezoneName is None:\n timezoneName = self.defaultTimezoneName\ndt = timeutil.convert(timeString, timezoneName, self.defaultTimezoneName)\nsource.re... | <|body_start_0|>
if timezoneName is None:
timezoneName = self.defaultTimezoneName
dt = timeutil.now(timezoneName)
source.reply(timeutil.format(dt, self.timeFormat))
<|end_body_0|>
<|body_start_1|>
if timezoneName is None:
timezoneName = self.defaultTimezoneName
... | Time-related functions. | Time | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Time:
"""Time-related functions."""
def cmd_now(self, source, timezoneName=None):
"""Show the current time in the default timezone, or <timezoneName>."""
<|body_0|>
def cmd_convert(self, source, timeString, timezoneName=None):
"""Convert <timeString> to the defau... | stack_v2_sparse_classes_36k_train_010637 | 1,669 | permissive | [
{
"docstring": "Show the current time in the default timezone, or <timezoneName>.",
"name": "cmd_now",
"signature": "def cmd_now(self, source, timezoneName=None)"
},
{
"docstring": "Convert <timeString> to the default timezone, or <timezoneName>. <timeString> should be a valid time string, the f... | 2 | stack_v2_sparse_classes_30k_train_011792 | Implement the Python class `Time` described below.
Class description:
Time-related functions.
Method signatures and docstrings:
- def cmd_now(self, source, timezoneName=None): Show the current time in the default timezone, or <timezoneName>.
- def cmd_convert(self, source, timeString, timezoneName=None): Convert <tim... | Implement the Python class `Time` described below.
Class description:
Time-related functions.
Method signatures and docstrings:
- def cmd_now(self, source, timezoneName=None): Show the current time in the default timezone, or <timezoneName>.
- def cmd_convert(self, source, timeString, timezoneName=None): Convert <tim... | 11c80c7024548ce7c41800b077d3d0a738a04875 | <|skeleton|>
class Time:
"""Time-related functions."""
def cmd_now(self, source, timezoneName=None):
"""Show the current time in the default timezone, or <timezoneName>."""
<|body_0|>
def cmd_convert(self, source, timeString, timezoneName=None):
"""Convert <timeString> to the defau... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Time:
"""Time-related functions."""
def cmd_now(self, source, timezoneName=None):
"""Show the current time in the default timezone, or <timezoneName>."""
if timezoneName is None:
timezoneName = self.defaultTimezoneName
dt = timeutil.now(timezoneName)
source.rep... | the_stack_v2_python_sparse | eridanusstd/plugindefs/time.py | mithrandi/eridanus | train | 0 |
c101d2cab62c07a622a47d882250093f97ce4545 | [
"self._head = TwoWayNode()\nself._head.previous = self._head.next = self._head\nAbstractList.__init__(self, sourceCollection)",
"cursor = self._head.next\nwhile cursor != self._head:\n yield cursor.data\n cursor = cursor.next",
"if i == len(self):\n return self._head\nif i == len(self) - 1:\n return... | <|body_start_0|>
self._head = TwoWayNode()
self._head.previous = self._head.next = self._head
AbstractList.__init__(self, sourceCollection)
<|end_body_0|>
<|body_start_1|>
cursor = self._head.next
while cursor != self._head:
yield cursor.data
cursor = cur... | A link-based list implementation. | LinkedList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkedList:
"""A link-based list implementation."""
def __init__(self, sourceCollection=None):
"""Sets the initial state of self, which includes the contents of sourceCollection, if it's present."""
<|body_0|>
def __iter__(self):
"""Supports iteration over a view... | stack_v2_sparse_classes_36k_train_010638 | 2,002 | no_license | [
{
"docstring": "Sets the initial state of self, which includes the contents of sourceCollection, if it's present.",
"name": "__init__",
"signature": "def __init__(self, sourceCollection=None)"
},
{
"docstring": "Supports iteration over a view of self.",
"name": "__iter__",
"signature": "... | 5 | null | Implement the Python class `LinkedList` described below.
Class description:
A link-based list implementation.
Method signatures and docstrings:
- def __init__(self, sourceCollection=None): Sets the initial state of self, which includes the contents of sourceCollection, if it's present.
- def __iter__(self): Supports ... | Implement the Python class `LinkedList` described below.
Class description:
A link-based list implementation.
Method signatures and docstrings:
- def __init__(self, sourceCollection=None): Sets the initial state of self, which includes the contents of sourceCollection, if it's present.
- def __iter__(self): Supports ... | 5a562d76830faf78feec81bc11190b71eae3a799 | <|skeleton|>
class LinkedList:
"""A link-based list implementation."""
def __init__(self, sourceCollection=None):
"""Sets the initial state of self, which includes the contents of sourceCollection, if it's present."""
<|body_0|>
def __iter__(self):
"""Supports iteration over a view... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinkedList:
"""A link-based list implementation."""
def __init__(self, sourceCollection=None):
"""Sets the initial state of self, which includes the contents of sourceCollection, if it's present."""
self._head = TwoWayNode()
self._head.previous = self._head.next = self._head
... | the_stack_v2_python_sparse | FundamentalsOfPythonDataStructures/ExampleCode/chapter9/linkedlist.py | xjr7670/book_practice | train | 3 |
8505ee7f68520a0c7a23ee4a067257baa4fd6910 | [
"now_time = datetime.datetime.now().strftime('%Y%m%d')\nresult = format_result_id2str(InfoCompanyLine().worker_current_itinerary_info(login_user_id, now_time))\nlogger.info(result)\nreturn (ResponseCode.SUCCEED, '执行成功', result)",
"now_time = datetime.datetime.now().strftime('%Y%m%d')\nresult = format_result_id2st... | <|body_start_0|>
now_time = datetime.datetime.now().strftime('%Y%m%d')
result = format_result_id2str(InfoCompanyLine().worker_current_itinerary_info(login_user_id, now_time))
logger.info(result)
return (ResponseCode.SUCCEED, '执行成功', result)
<|end_body_0|>
<|body_start_1|>
now_ti... | ItineraryInfoService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ItineraryInfoService:
def worker_itinerary_info(login_user_id):
"""获取当前行程信息(校车工作人员) :param login_user_id: :return:"""
<|body_0|>
def parents_itinerary_info(login_user_id):
"""获取当前行程信息(家长) :param info: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_010639 | 1,968 | no_license | [
{
"docstring": "获取当前行程信息(校车工作人员) :param login_user_id: :return:",
"name": "worker_itinerary_info",
"signature": "def worker_itinerary_info(login_user_id)"
},
{
"docstring": "获取当前行程信息(家长) :param info: :return:",
"name": "parents_itinerary_info",
"signature": "def parents_itinerary_info(lo... | 2 | stack_v2_sparse_classes_30k_train_018559 | Implement the Python class `ItineraryInfoService` described below.
Class description:
Implement the ItineraryInfoService class.
Method signatures and docstrings:
- def worker_itinerary_info(login_user_id): 获取当前行程信息(校车工作人员) :param login_user_id: :return:
- def parents_itinerary_info(login_user_id): 获取当前行程信息(家长) :param... | Implement the Python class `ItineraryInfoService` described below.
Class description:
Implement the ItineraryInfoService class.
Method signatures and docstrings:
- def worker_itinerary_info(login_user_id): 获取当前行程信息(校车工作人员) :param login_user_id: :return:
- def parents_itinerary_info(login_user_id): 获取当前行程信息(家长) :param... | a7cf5a0b6daa372ed860dc43d92c55fcde764eb9 | <|skeleton|>
class ItineraryInfoService:
def worker_itinerary_info(login_user_id):
"""获取当前行程信息(校车工作人员) :param login_user_id: :return:"""
<|body_0|>
def parents_itinerary_info(login_user_id):
"""获取当前行程信息(家长) :param info: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ItineraryInfoService:
def worker_itinerary_info(login_user_id):
"""获取当前行程信息(校车工作人员) :param login_user_id: :return:"""
now_time = datetime.datetime.now().strftime('%Y%m%d')
result = format_result_id2str(InfoCompanyLine().worker_current_itinerary_info(login_user_id, now_time))
lo... | the_stack_v2_python_sparse | python_project/smart_schoolBus_project/app/schoolbus_situation/services/worker_parents_itinerary_service.py | malqch/aibus | train | 0 | |
71279b9e2c1970c0195f7020434343d05b1c2f2b | [
"self.sleeptime = param\nself.loopcount = loop_param\nself.cpu = SystemCpuUtilTask.Cpu()\nself.mem = SystemMemUtilTask.Mem()",
"if self.enableSystemPerformanceAdapter == True:\n i = 0\n while i < self.loopcount:\n cpuval = self.cpu.getDataFromSensor()\n memval = self.mem.getDataFromSensor()\n ... | <|body_start_0|>
self.sleeptime = param
self.loopcount = loop_param
self.cpu = SystemCpuUtilTask.Cpu()
self.mem = SystemMemUtilTask.Mem()
<|end_body_0|>
<|body_start_1|>
if self.enableSystemPerformanceAdapter == True:
i = 0
while i < self.loopcount:
... | SystemPerformanceAdapter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SystemPerformanceAdapter:
def __init__(self, param, loop_param):
"""Constructor"""
<|body_0|>
def run_adapter(self):
"""Method to log the current CPU and Memory usage"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.sleeptime = param
sel... | stack_v2_sparse_classes_36k_train_010640 | 1,276 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, param, loop_param)"
},
{
"docstring": "Method to log the current CPU and Memory usage",
"name": "run_adapter",
"signature": "def run_adapter(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004159 | Implement the Python class `SystemPerformanceAdapter` described below.
Class description:
Implement the SystemPerformanceAdapter class.
Method signatures and docstrings:
- def __init__(self, param, loop_param): Constructor
- def run_adapter(self): Method to log the current CPU and Memory usage | Implement the Python class `SystemPerformanceAdapter` described below.
Class description:
Implement the SystemPerformanceAdapter class.
Method signatures and docstrings:
- def __init__(self, param, loop_param): Constructor
- def run_adapter(self): Method to log the current CPU and Memory usage
<|skeleton|>
class Sys... | dfd5fd8c757cae8b1306ae3e4eb2cfc9bf124fee | <|skeleton|>
class SystemPerformanceAdapter:
def __init__(self, param, loop_param):
"""Constructor"""
<|body_0|>
def run_adapter(self):
"""Method to log the current CPU and Memory usage"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SystemPerformanceAdapter:
def __init__(self, param, loop_param):
"""Constructor"""
self.sleeptime = param
self.loopcount = loop_param
self.cpu = SystemCpuUtilTask.Cpu()
self.mem = SystemMemUtilTask.Mem()
def run_adapter(self):
"""Method to log the current C... | the_stack_v2_python_sparse | apps/labs/module01/SystemPerformanceAdapter.py | mnk400/iot-device | train | 0 | |
e565a4248127ad90b35b1c223db00e8ed4594589 | [
"valid_palindromes = set()\n\ndef check(s):\n if s[1:-1] in valid_palindromes:\n if s[0] == s[-1]:\n valid_palindromes.add(s)\n return True\n else:\n return False\n else:\n for i in range(len(s) >> 1):\n if s[i] != s[~i]:\n return... | <|body_start_0|>
valid_palindromes = set()
def check(s):
if s[1:-1] in valid_palindromes:
if s[0] == s[-1]:
valid_palindromes.add(s)
return True
else:
return False
else:
f... | Solution | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s: str) -> str:
"""Check every substring is a valid palindrome."""
<|body_0|>
def longestPalindrome_v2(self, s: str) -> str:
"""Dynamic Programming dp(i,j) = true if Si...Sj is a palindrome else false dp(i,j) = (dp(i+1, j-1) and ... | stack_v2_sparse_classes_36k_train_010641 | 5,178 | permissive | [
{
"docstring": "Check every substring is a valid palindrome.",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s: str) -> str"
},
{
"docstring": "Dynamic Programming dp(i,j) = true if Si...Sj is a palindrome else false dp(i,j) = (dp(i+1, j-1) and (Si == Sj))",
"name": ... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s: str) -> str: Check every substring is a valid palindrome.
- def longestPalindrome_v2(self, s: str) -> str: Dynamic Programming dp(i,j) = true if Si... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s: str) -> str: Check every substring is a valid palindrome.
- def longestPalindrome_v2(self, s: str) -> str: Dynamic Programming dp(i,j) = true if Si... | 226cecde136531341ce23cdf88529345be1912fc | <|skeleton|>
class Solution:
def longestPalindrome(self, s: str) -> str:
"""Check every substring is a valid palindrome."""
<|body_0|>
def longestPalindrome_v2(self, s: str) -> str:
"""Dynamic Programming dp(i,j) = true if Si...Sj is a palindrome else false dp(i,j) = (dp(i+1, j-1) and ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPalindrome(self, s: str) -> str:
"""Check every substring is a valid palindrome."""
valid_palindromes = set()
def check(s):
if s[1:-1] in valid_palindromes:
if s[0] == s[-1]:
valid_palindromes.add(s)
... | the_stack_v2_python_sparse | Leetcode/Intermediate/Array_and_string/5_Longest_Palindromic_Substring.py | ZR-Huang/AlgorithmsPractices | train | 1 | |
e3423b900e151baa1344be855f1ab50c90089121 | [
"super(RNNDecoder, self).__init__()\nself.embedding = tf.keras.layers.Embedding(vocab, embedding)\nself.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)\nself.F = tf.keras.layers.Dense(vocab)",
"batch, units = s_prev.shape\nattention = SelfAttentio... | <|body_start_0|>
super(RNNDecoder, self).__init__()
self.embedding = tf.keras.layers.Embedding(vocab, embedding)
self.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)
self.F = tf.keras.layers.Dense(vocab)
<|end_body_0|>
<... | RNN Decoder Class | RNNDecoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNDecoder:
"""RNN Decoder Class"""
def __init__(self, vocab, embedding, units, batch):
"""Class constructor. Args: vocab (int): the size of the output vocabulary. embedding (int): the dimensionality of the embedding vector. units (int): the number of hidden units in the RNN cell. ba... | stack_v2_sparse_classes_36k_train_010642 | 2,329 | no_license | [
{
"docstring": "Class constructor. Args: vocab (int): the size of the output vocabulary. embedding (int): the dimensionality of the embedding vector. units (int): the number of hidden units in the RNN cell. batch (int): the batch size.",
"name": "__init__",
"signature": "def __init__(self, vocab, embedd... | 2 | stack_v2_sparse_classes_30k_train_018861 | Implement the Python class `RNNDecoder` described below.
Class description:
RNN Decoder Class
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): Class constructor. Args: vocab (int): the size of the output vocabulary. embedding (int): the dimensionality of the embedding vector. un... | Implement the Python class `RNNDecoder` described below.
Class description:
RNN Decoder Class
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): Class constructor. Args: vocab (int): the size of the output vocabulary. embedding (int): the dimensionality of the embedding vector. un... | 5aff923277cfe9f2b5324a773e4e5c3cac810a0c | <|skeleton|>
class RNNDecoder:
"""RNN Decoder Class"""
def __init__(self, vocab, embedding, units, batch):
"""Class constructor. Args: vocab (int): the size of the output vocabulary. embedding (int): the dimensionality of the embedding vector. units (int): the number of hidden units in the RNN cell. ba... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNNDecoder:
"""RNN Decoder Class"""
def __init__(self, vocab, embedding, units, batch):
"""Class constructor. Args: vocab (int): the size of the output vocabulary. embedding (int): the dimensionality of the embedding vector. units (int): the number of hidden units in the RNN cell. batch (int): th... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/2-rnn_decoder.py | cmmolanos1/holbertonschool-machine_learning | train | 1 |
d7ac6d7dac049ae4971fbf6159c7a17edd9e1030 | [
"if root is None:\n return\nhead, tail = self.dfs(root)\ncur = head\nwhile cur:\n print(cur.val)\n cur = cur.right",
"if not (node.left or node.right):\n return (node, node)\nif node.left:\n lts, lte = self.dfs(node.left)\nif node.right:\n rts, rte = self.dfs(node.right)\nif node.left and node.r... | <|body_start_0|>
if root is None:
return
head, tail = self.dfs(root)
cur = head
while cur:
print(cur.val)
cur = cur.right
<|end_body_0|>
<|body_start_1|>
if not (node.left or node.right):
return (node, node)
if node.left:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def flatten(self, root):
"""Do not return anything, modify root in-place instead. :type node: TreeNode"""
<|body_0|>
def dfs(self, node):
""":type node: TreeNode :rtype: (TreeNode, TreeNode)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_010643 | 1,687 | no_license | [
{
"docstring": "Do not return anything, modify root in-place instead. :type node: TreeNode",
"name": "flatten",
"signature": "def flatten(self, root)"
},
{
"docstring": ":type node: TreeNode :rtype: (TreeNode, TreeNode)",
"name": "dfs",
"signature": "def dfs(self, node)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, root): Do not return anything, modify root in-place instead. :type node: TreeNode
- def dfs(self, node): :type node: TreeNode :rtype: (TreeNode, TreeNode) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, root): Do not return anything, modify root in-place instead. :type node: TreeNode
- def dfs(self, node): :type node: TreeNode :rtype: (TreeNode, TreeNode)
<|sk... | f832227c4d0e0b1c0cc326561187004ef24e2a68 | <|skeleton|>
class Solution:
def flatten(self, root):
"""Do not return anything, modify root in-place instead. :type node: TreeNode"""
<|body_0|>
def dfs(self, node):
""":type node: TreeNode :rtype: (TreeNode, TreeNode)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def flatten(self, root):
"""Do not return anything, modify root in-place instead. :type node: TreeNode"""
if root is None:
return
head, tail = self.dfs(root)
cur = head
while cur:
print(cur.val)
cur = cur.right
def dfs(... | the_stack_v2_python_sparse | 114.py | Gackle/leetcode_practice | train | 0 | |
9f3b0ac250df991444202b1fb1d8c40ac18036bc | [
"nums.sort(key=lambda x: x != 0)\nprint(nums)\npoint = 0\nfor index, value in enumerate(nums):\n if value != 0:\n point = index\n break\nnums[point:] = list(reversed(nums[point:]))\nprint(nums)\nnums.reverse()\nprint(nums)",
"p1, p2 = (0, 0)\nN = len(nums)\nwhile p2 < N:\n while p1 < N and num... | <|body_start_0|>
nums.sort(key=lambda x: x != 0)
print(nums)
point = 0
for index, value in enumerate(nums):
if value != 0:
point = index
break
nums[point:] = list(reversed(nums[point:]))
print(nums)
nums.reverse()
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def moveZeroes(self, nums) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroes2(self, nums) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_010644 | 1,125 | no_license | [
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "moveZeroes",
"signature": "def moveZeroes(self, nums) -> None"
},
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "moveZeroes2",
"signature": "def moveZeroes2(self, nums) -> N... | 2 | stack_v2_sparse_classes_30k_train_002335 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveZeroes(self, nums) -> None: Do not return anything, modify nums in-place instead.
- def moveZeroes2(self, nums) -> None: Do not return anything, modify nums in-place inst... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveZeroes(self, nums) -> None: Do not return anything, modify nums in-place instead.
- def moveZeroes2(self, nums) -> None: Do not return anything, modify nums in-place inst... | 59313bbf699ba71adff0f614a49d1c3a669eb7f3 | <|skeleton|>
class Solution:
def moveZeroes(self, nums) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroes2(self, nums) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def moveZeroes(self, nums) -> None:
"""Do not return anything, modify nums in-place instead."""
nums.sort(key=lambda x: x != 0)
print(nums)
point = 0
for index, value in enumerate(nums):
if value != 0:
point = index
... | the_stack_v2_python_sparse | amazing/move zeroes.py | Johnson-xie/jeetcode | train | 0 | |
57e848434930064ff3b95b1aa8e9fe20a3496a6f | [
"Parametre.__init__(self, 'montrer', 'show')\nself.schema = '<nom_objet>'\nself.aide_courte = 'montre le pavillon'\nself.aide_longue = 'Cette commande est assez identique à %pavillon% %pavillon:hisser%, mais au lieu de hisser le pavillon en tête de mât, elle le montre simplement pour être visible des autres navires... | <|body_start_0|>
Parametre.__init__(self, 'montrer', 'show')
self.schema = '<nom_objet>'
self.aide_courte = 'montre le pavillon'
self.aide_longue = 'Cette commande est assez identique à %pavillon% %pavillon:hisser%, mais au lieu de hisser le pavillon en tête de mât, elle le montre simple... | Commande 'pavillon montrer'. | PrmMontrer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmMontrer:
"""Commande 'pavillon montrer'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def ajouter(self):
"""Méthode appelée lors de l'ajout de la commande à l'interpréteur"""
<|body_1|>
def interpreter(self, personnage, dic_ma... | stack_v2_sparse_classes_36k_train_010645 | 3,742 | permissive | [
{
"docstring": "Constructeur du paramètre",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Méthode appelée lors de l'ajout de la commande à l'interpréteur",
"name": "ajouter",
"signature": "def ajouter(self)"
},
{
"docstring": "Interprétation du paramètr... | 3 | null | Implement the Python class `PrmMontrer` described below.
Class description:
Commande 'pavillon montrer'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def ajouter(self): Méthode appelée lors de l'ajout de la commande à l'interpréteur
- def interpreter(self, personnage, dic_masque... | Implement the Python class `PrmMontrer` described below.
Class description:
Commande 'pavillon montrer'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def ajouter(self): Méthode appelée lors de l'ajout de la commande à l'interpréteur
- def interpreter(self, personnage, dic_masque... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmMontrer:
"""Commande 'pavillon montrer'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def ajouter(self):
"""Méthode appelée lors de l'ajout de la commande à l'interpréteur"""
<|body_1|>
def interpreter(self, personnage, dic_ma... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrmMontrer:
"""Commande 'pavillon montrer'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'montrer', 'show')
self.schema = '<nom_objet>'
self.aide_courte = 'montre le pavillon'
self.aide_longue = 'Cette commande est assez identique... | the_stack_v2_python_sparse | src/secondaires/navigation/commandes/pavillon/montrer.py | vincent-lg/tsunami | train | 5 |
cd2ec1b23043295195dbac9f687b99f2f27efad6 | [
"super(NerBiLstmModel, self).__init__()\nself.config = config\nself._max_length = min(config.max_length, helper.max_length)\nself._dropout = torch.nn.Dropout(config.dropout)\nself._embeddings = torch.nn.Embedding.from_pretrained(pretrained_embeddings, freeze=False)\nself._nerbilstm = torch.nn.LSTM(input_size=config... | <|body_start_0|>
super(NerBiLstmModel, self).__init__()
self.config = config
self._max_length = min(config.max_length, helper.max_length)
self._dropout = torch.nn.Dropout(config.dropout)
self._embeddings = torch.nn.Embedding.from_pretrained(pretrained_embeddings, freeze=False)
... | Implements a BiLSTM network with an embedding layer and single hidden layer. This network will predict a sequence of labels (e.g. PER) for a given token (e.g. Henry) using a featurized window around the token. | NerBiLstmModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NerBiLstmModel:
"""Implements a BiLSTM network with an embedding layer and single hidden layer. This network will predict a sequence of labels (e.g. PER) for a given token (e.g. Henry) using a featurized window around the token."""
def __init__(self, helper, config, pretrained_embeddings):
... | stack_v2_sparse_classes_36k_train_010646 | 20,493 | no_license | [
{
"docstring": "TODO: - Initialize the layer of the models: - *Unfrozen* embeddings of shape (V, D) which are loaded with pre-trained weights (`pretrained_embeddings`) - BiLSTM layer with hidden size of H/2 per direction - Linear layer with output of shape C Where: V - size of the vocabulary D - size of a word ... | 2 | stack_v2_sparse_classes_30k_train_011179 | Implement the Python class `NerBiLstmModel` described below.
Class description:
Implements a BiLSTM network with an embedding layer and single hidden layer. This network will predict a sequence of labels (e.g. PER) for a given token (e.g. Henry) using a featurized window around the token.
Method signatures and docstr... | Implement the Python class `NerBiLstmModel` described below.
Class description:
Implements a BiLSTM network with an embedding layer and single hidden layer. This network will predict a sequence of labels (e.g. PER) for a given token (e.g. Henry) using a featurized window around the token.
Method signatures and docstr... | b15acc98448341802562d1ccb43924c97560d530 | <|skeleton|>
class NerBiLstmModel:
"""Implements a BiLSTM network with an embedding layer and single hidden layer. This network will predict a sequence of labels (e.g. PER) for a given token (e.g. Henry) using a featurized window around the token."""
def __init__(self, helper, config, pretrained_embeddings):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NerBiLstmModel:
"""Implements a BiLSTM network with an embedding layer and single hidden layer. This network will predict a sequence of labels (e.g. PER) for a given token (e.g. Henry) using a featurized window around the token."""
def __init__(self, helper, config, pretrained_embeddings):
"""TOD... | the_stack_v2_python_sparse | nlp-hw3/Code/q5/ner_bilstm_model.py | AvivYaniv/Natural-Language-Processing | train | 3 |
9bc5372c304370702058f75859d319ad475f5422 | [
"self.address_to_instance_map = None\nif i2c_instances is None:\n self.i2c_instances = _detect_all_i2c_instances()\nelse:\n self.i2c_instances = i2c_instances\nif instance_to_address_map is None:\n self.instance_to_address_map = {instance: _detect_all_addresses_on_i2c_instance(instance) for instance in sel... | <|body_start_0|>
self.address_to_instance_map = None
if i2c_instances is None:
self.i2c_instances = _detect_all_i2c_instances()
else:
self.i2c_instances = i2c_instances
if instance_to_address_map is None:
self.instance_to_address_map = {instance: _dete... | I2CBus | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class I2CBus:
def __init__(self, i2c_instances=None, instance_to_address_map=None) -> None:
"""Initialize the I2CBus object. By default, scans the I2C hardware bus to determine what addresses are present. For testing, pass in `i2c_instances` (list of int) and pass in the `instance_to_address_m... | stack_v2_sparse_classes_36k_train_010647 | 7,412 | permissive | [
{
"docstring": "Initialize the I2CBus object. By default, scans the I2C hardware bus to determine what addresses are present. For testing, pass in `i2c_instances` (list of int) and pass in the `instance_to_address_map` yourself. It should be a dict of the form {int: [addresses]}",
"name": "__init__",
"s... | 2 | stack_v2_sparse_classes_30k_train_016789 | Implement the Python class `I2CBus` described below.
Class description:
Implement the I2CBus class.
Method signatures and docstrings:
- def __init__(self, i2c_instances=None, instance_to_address_map=None) -> None: Initialize the I2CBus object. By default, scans the I2C hardware bus to determine what addresses are pre... | Implement the Python class `I2CBus` described below.
Class description:
Implement the I2CBus class.
Method signatures and docstrings:
- def __init__(self, i2c_instances=None, instance_to_address_map=None) -> None: Initialize the I2CBus object. By default, scans the I2C hardware bus to determine what addresses are pre... | e2e3224d2a2d604db2d35ec69ed6f1ad366cc970 | <|skeleton|>
class I2CBus:
def __init__(self, i2c_instances=None, instance_to_address_map=None) -> None:
"""Initialize the I2CBus object. By default, scans the I2C hardware bus to determine what addresses are present. For testing, pass in `i2c_instances` (list of int) and pass in the `instance_to_address_m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class I2CBus:
def __init__(self, i2c_instances=None, instance_to_address_map=None) -> None:
"""Initialize the I2CBus object. By default, scans the I2C hardware bus to determine what addresses are present. For testing, pass in `i2c_instances` (list of int) and pass in the `instance_to_address_map` yourself. ... | the_stack_v2_python_sparse | libraries/artie-i2c/src/artie_i2c/i2c.py | MaxStrange/Artie | train | 0 | |
c89523e3d727e25d00ceafeebffd522ba3fdc5f8 | [
"project = Project()\nproject.id = '%s:%d' % (market_tool_name, owner.id)\nproject.owner = owner\nproject.type = 'market_tool'\nreturn project",
"project = Project()\nproject.id = '%s:%d' % (app_name, owner.id)\nproject.owner = owner\nproject.type = 'app'\nreturn project"
] | <|body_start_0|>
project = Project()
project.id = '%s:%d' % (market_tool_name, owner.id)
project.owner = owner
project.type = 'market_tool'
return project
<|end_body_0|>
<|body_start_1|>
project = Project()
project.id = '%s:%d' % (app_name, owner.id)
proj... | Project: 一个项目,可包含多个Page | Project | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Project:
"""Project: 一个项目,可包含多个Page"""
def get_market_tool_project(owner, market_tool_name):
"""market_tool_name的格式为: market_tool:vote"""
<|body_0|>
def get_app_project(owner, app_name):
"""app_name的格式为: apps:vote"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_36k_train_010648 | 7,349 | no_license | [
{
"docstring": "market_tool_name的格式为: market_tool:vote",
"name": "get_market_tool_project",
"signature": "def get_market_tool_project(owner, market_tool_name)"
},
{
"docstring": "app_name的格式为: apps:vote",
"name": "get_app_project",
"signature": "def get_app_project(owner, app_name)"
}
... | 2 | null | Implement the Python class `Project` described below.
Class description:
Project: 一个项目,可包含多个Page
Method signatures and docstrings:
- def get_market_tool_project(owner, market_tool_name): market_tool_name的格式为: market_tool:vote
- def get_app_project(owner, app_name): app_name的格式为: apps:vote | Implement the Python class `Project` described below.
Class description:
Project: 一个项目,可包含多个Page
Method signatures and docstrings:
- def get_market_tool_project(owner, market_tool_name): market_tool_name的格式为: market_tool:vote
- def get_app_project(owner, app_name): app_name的格式为: apps:vote
<|skeleton|>
class Project:... | 8b2f7befe92841bcc35e0e60cac5958ef3f3af54 | <|skeleton|>
class Project:
"""Project: 一个项目,可包含多个Page"""
def get_market_tool_project(owner, market_tool_name):
"""market_tool_name的格式为: market_tool:vote"""
<|body_0|>
def get_app_project(owner, app_name):
"""app_name的格式为: apps:vote"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Project:
"""Project: 一个项目,可包含多个Page"""
def get_market_tool_project(owner, market_tool_name):
"""market_tool_name的格式为: market_tool:vote"""
project = Project()
project.id = '%s:%d' % (market_tool_name, owner.id)
project.owner = owner
project.type = 'market_tool'
... | the_stack_v2_python_sparse | weapp/webapp/models.py | chengdg/weizoom | train | 1 |
0653ae74d5b9237b8d2b8c88a5fb03db602623c4 | [
"print('test_start_stop_streaming')\nconfig = component_tests_config(cfd_mode=CfdModes.NAMED, run_proxy_dns=False, provide_ingress=False)\nLOGGER.debug(config)\nconfig_path = write_config(tmp_path, config.full_config)\nwith start_cloudflared(tmp_path, config, cfd_args=['run', '--hello-world'], new_process=True):\n ... | <|body_start_0|>
print('test_start_stop_streaming')
config = component_tests_config(cfd_mode=CfdModes.NAMED, run_proxy_dns=False, provide_ingress=False)
LOGGER.debug(config)
config_path = write_config(tmp_path, config.full_config)
with start_cloudflared(tmp_path, config, cfd_args... | TestTail | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestTail:
async def test_start_stop_streaming(self, tmp_path, component_tests_config):
"""Validates that a websocket connection to management.argotunnel.com/logs can be opened with the access token and start and stop streaming on-demand."""
<|body_0|>
async def test_streamin... | stack_v2_sparse_classes_36k_train_010649 | 9,312 | permissive | [
{
"docstring": "Validates that a websocket connection to management.argotunnel.com/logs can be opened with the access token and start and stop streaming on-demand.",
"name": "test_start_stop_streaming",
"signature": "async def test_start_stop_streaming(self, tmp_path, component_tests_config)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_008344 | Implement the Python class `TestTail` described below.
Class description:
Implement the TestTail class.
Method signatures and docstrings:
- async def test_start_stop_streaming(self, tmp_path, component_tests_config): Validates that a websocket connection to management.argotunnel.com/logs can be opened with the access... | Implement the Python class `TestTail` described below.
Class description:
Implement the TestTail class.
Method signatures and docstrings:
- async def test_start_stop_streaming(self, tmp_path, component_tests_config): Validates that a websocket connection to management.argotunnel.com/logs can be opened with the access... | 569a7c3c9ed02df9d3a8cb4b7b7725f1466c065f | <|skeleton|>
class TestTail:
async def test_start_stop_streaming(self, tmp_path, component_tests_config):
"""Validates that a websocket connection to management.argotunnel.com/logs can be opened with the access token and start and stop streaming on-demand."""
<|body_0|>
async def test_streamin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestTail:
async def test_start_stop_streaming(self, tmp_path, component_tests_config):
"""Validates that a websocket connection to management.argotunnel.com/logs can be opened with the access token and start and stop streaming on-demand."""
print('test_start_stop_streaming')
config = c... | the_stack_v2_python_sparse | component-tests/test_tail.py | cloudflare/cloudflared | train | 6,402 | |
2c425ad5b59573634a557fb8739cefe9e91eaea4 | [
"valid_features = []\nfor feature in features:\n if feature in data.columns and (data[feature].dtype == 'float64' or data[feature].dtype == 'int64'):\n valid_features.append(feature)\nreturn valid_features",
"valid_features = MyPlotLib.validate_features(data, features)\nif valid_features:\n data[feat... | <|body_start_0|>
valid_features = []
for feature in features:
if feature in data.columns and (data[feature].dtype == 'float64' or data[feature].dtype == 'int64'):
valid_features.append(feature)
return valid_features
<|end_body_0|>
<|body_start_1|>
valid_featu... | MyPlotLib | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyPlotLib:
def validate_features(data, features):
"""Validate if the features are numerical and present in the dataframe."""
<|body_0|>
def histogram(data, features):
"""Plots one histogram for each numerical feature in the list."""
<|body_1|>
def pair_p... | stack_v2_sparse_classes_36k_train_010650 | 2,460 | no_license | [
{
"docstring": "Validate if the features are numerical and present in the dataframe.",
"name": "validate_features",
"signature": "def validate_features(data, features)"
},
{
"docstring": "Plots one histogram for each numerical feature in the list.",
"name": "histogram",
"signature": "def... | 5 | stack_v2_sparse_classes_30k_train_000675 | Implement the Python class `MyPlotLib` described below.
Class description:
Implement the MyPlotLib class.
Method signatures and docstrings:
- def validate_features(data, features): Validate if the features are numerical and present in the dataframe.
- def histogram(data, features): Plots one histogram for each numeri... | Implement the Python class `MyPlotLib` described below.
Class description:
Implement the MyPlotLib class.
Method signatures and docstrings:
- def validate_features(data, features): Validate if the features are numerical and present in the dataframe.
- def histogram(data, features): Plots one histogram for each numeri... | 24358cc6807d86fe5da766bb4505eef29f1e371f | <|skeleton|>
class MyPlotLib:
def validate_features(data, features):
"""Validate if the features are numerical and present in the dataframe."""
<|body_0|>
def histogram(data, features):
"""Plots one histogram for each numerical feature in the list."""
<|body_1|>
def pair_p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyPlotLib:
def validate_features(data, features):
"""Validate if the features are numerical and present in the dataframe."""
valid_features = []
for feature in features:
if feature in data.columns and (data[feature].dtype == 'float64' or data[feature].dtype == 'int64'):
... | the_stack_v2_python_sparse | day04/ex06/MyPlotLib.py | Ghilphar/bootcamp_python | train | 0 | |
1ef4b04c6286880de38f8288b596613a9a0ea322 | [
"super(SetConv, self).__init__()\nself.fc1 = torch.nn.Conv2d(nb_feat_in + 3, nb_feat_out, 1, bias=False)\nself.bn1 = torch.nn.InstanceNorm2d(nb_feat_out, affine=True)\nself.fc2 = torch.nn.Conv2d(nb_feat_out, nb_feat_out, 1, bias=False)\nself.bn2 = torch.nn.InstanceNorm2d(nb_feat_out, affine=True)\nself.fc3 = torch.... | <|body_start_0|>
super(SetConv, self).__init__()
self.fc1 = torch.nn.Conv2d(nb_feat_in + 3, nb_feat_out, 1, bias=False)
self.bn1 = torch.nn.InstanceNorm2d(nb_feat_out, affine=True)
self.fc2 = torch.nn.Conv2d(nb_feat_out, nb_feat_out, 1, bias=False)
self.bn2 = torch.nn.InstanceNor... | SetConv | [
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SetConv:
def __init__(self, nb_feat_in, nb_feat_out):
"""Module that performs PointNet++-like convolution on point clouds. Parameters ---------- nb_feat_in : int Number of input channels. nb_feat_out : int Number of ouput channels. Returns ------- None."""
<|body_0|>
def for... | stack_v2_sparse_classes_36k_train_010651 | 2,386 | permissive | [
{
"docstring": "Module that performs PointNet++-like convolution on point clouds. Parameters ---------- nb_feat_in : int Number of input channels. nb_feat_out : int Number of ouput channels. Returns ------- None.",
"name": "__init__",
"signature": "def __init__(self, nb_feat_in, nb_feat_out)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_017339 | Implement the Python class `SetConv` described below.
Class description:
Implement the SetConv class.
Method signatures and docstrings:
- def __init__(self, nb_feat_in, nb_feat_out): Module that performs PointNet++-like convolution on point clouds. Parameters ---------- nb_feat_in : int Number of input channels. nb_f... | Implement the Python class `SetConv` described below.
Class description:
Implement the SetConv class.
Method signatures and docstrings:
- def __init__(self, nb_feat_in, nb_feat_out): Module that performs PointNet++-like convolution on point clouds. Parameters ---------- nb_feat_in : int Number of input channels. nb_f... | 2a5578577ce58786f05bb8701f2329b32ed6bb3a | <|skeleton|>
class SetConv:
def __init__(self, nb_feat_in, nb_feat_out):
"""Module that performs PointNet++-like convolution on point clouds. Parameters ---------- nb_feat_in : int Number of input channels. nb_feat_out : int Number of ouput channels. Returns ------- None."""
<|body_0|>
def for... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SetConv:
def __init__(self, nb_feat_in, nb_feat_out):
"""Module that performs PointNet++-like convolution on point clouds. Parameters ---------- nb_feat_in : int Number of input channels. nb_feat_out : int Number of ouput channels. Returns ------- None."""
super(SetConv, self).__init__()
... | the_stack_v2_python_sparse | shapmagn/modules_reg/networks/gconv.py | dugushiyu/shapmagn | train | 0 | |
f05d13978cca7829f393a6088c65c16c1fbe5d0a | [
"logging.debug('%s', request)\nbot_id = request.bot_id\nbot = bot_management.get_info_key(bot_id).get()\ndeleted = False\nif not bot:\n events = bot_management.get_events_query(bot_id, True).fetch(1)\n if not events:\n raise endpoints.NotFoundException('%s not found.' % bot_id)\n bot = bot_managemen... | <|body_start_0|>
logging.debug('%s', request)
bot_id = request.bot_id
bot = bot_management.get_info_key(bot_id).get()
deleted = False
if not bot:
events = bot_management.get_events_query(bot_id, True).fetch(1)
if not events:
raise endpoints... | Bot-related API. Permits querying information about the bot's properties | SwarmingBotService | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SwarmingBotService:
"""Bot-related API. Permits querying information about the bot's properties"""
def get(self, request):
"""Returns information about a known bot. This includes its state and dimensions, and if it is currently running a task."""
<|body_0|>
def delete(se... | stack_v2_sparse_classes_36k_train_010652 | 31,178 | permissive | [
{
"docstring": "Returns information about a known bot. This includes its state and dimensions, and if it is currently running a task.",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Deletes the bot corresponding to a provided bot_id. At that point, the bot will not appe... | 5 | stack_v2_sparse_classes_30k_train_006236 | Implement the Python class `SwarmingBotService` described below.
Class description:
Bot-related API. Permits querying information about the bot's properties
Method signatures and docstrings:
- def get(self, request): Returns information about a known bot. This includes its state and dimensions, and if it is currently... | Implement the Python class `SwarmingBotService` described below.
Class description:
Bot-related API. Permits querying information about the bot's properties
Method signatures and docstrings:
- def get(self, request): Returns information about a known bot. This includes its state and dimensions, and if it is currently... | 3fa4c520dddd82ed190152709e0a54b35faa3bae | <|skeleton|>
class SwarmingBotService:
"""Bot-related API. Permits querying information about the bot's properties"""
def get(self, request):
"""Returns information about a known bot. This includes its state and dimensions, and if it is currently running a task."""
<|body_0|>
def delete(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SwarmingBotService:
"""Bot-related API. Permits querying information about the bot's properties"""
def get(self, request):
"""Returns information about a known bot. This includes its state and dimensions, and if it is currently running a task."""
logging.debug('%s', request)
bot_i... | the_stack_v2_python_sparse | appengine/swarming/handlers_endpoints.py | Slayo2008/New2 | train | 1 |
cdc1c3592b7823c2caa81cd7950547c992552e49 | [
"try:\n sh.zfs('list', '-t', 'filesystem', self.name)\nexcept sh.ErrorReturnCode_1:\n return False\nreturn True",
"try:\n sh.zfs('create', self.name)\nexcept sh.ErrorReturnCode_1:\n raise\nreturn True",
"if confirm is not True:\n raise ZfsError('Destroy of storage filesystem requires confirm=True... | <|body_start_0|>
try:
sh.zfs('list', '-t', 'filesystem', self.name)
except sh.ErrorReturnCode_1:
return False
return True
<|end_body_0|>
<|body_start_1|>
try:
sh.zfs('create', self.name)
except sh.ErrorReturnCode_1:
raise
r... | Filesystem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Filesystem:
def exists(self):
"""Checks if filesystem exists. filesystem = Filesystem('dpool/tmp/test0') filesystem.exists()"""
<|body_0|>
def create(self):
"""Creates storage filesystem. filesystem = Filesystem('dpool/tmp/test0') filesystem.create()"""
<|bod... | stack_v2_sparse_classes_36k_train_010653 | 3,103 | no_license | [
{
"docstring": "Checks if filesystem exists. filesystem = Filesystem('dpool/tmp/test0') filesystem.exists()",
"name": "exists",
"signature": "def exists(self)"
},
{
"docstring": "Creates storage filesystem. filesystem = Filesystem('dpool/tmp/test0') filesystem.create()",
"name": "create",
... | 4 | stack_v2_sparse_classes_30k_train_011760 | Implement the Python class `Filesystem` described below.
Class description:
Implement the Filesystem class.
Method signatures and docstrings:
- def exists(self): Checks if filesystem exists. filesystem = Filesystem('dpool/tmp/test0') filesystem.exists()
- def create(self): Creates storage filesystem. filesystem = Fil... | Implement the Python class `Filesystem` described below.
Class description:
Implement the Filesystem class.
Method signatures and docstrings:
- def exists(self): Checks if filesystem exists. filesystem = Filesystem('dpool/tmp/test0') filesystem.exists()
- def create(self): Creates storage filesystem. filesystem = Fil... | 8ed19bc7d481e398bce318b7d513f4583f1e623f | <|skeleton|>
class Filesystem:
def exists(self):
"""Checks if filesystem exists. filesystem = Filesystem('dpool/tmp/test0') filesystem.exists()"""
<|body_0|>
def create(self):
"""Creates storage filesystem. filesystem = Filesystem('dpool/tmp/test0') filesystem.create()"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Filesystem:
def exists(self):
"""Checks if filesystem exists. filesystem = Filesystem('dpool/tmp/test0') filesystem.exists()"""
try:
sh.zfs('list', '-t', 'filesystem', self.name)
except sh.ErrorReturnCode_1:
return False
return True
def create(self)... | the_stack_v2_python_sparse | solarsan/storage/filesystem.py | akatrevorjay/solarsan | train | 1 | |
c2e41376db9878a7231a2d01be4ef762e84374fc | [
"self.char_level = char_level\nself.hard_constraint = hard_constraint\nself.sent_delimiter = sent_delimiter\nself.max_seq_len = max_seq_len\nsuper().__init__(data, transform, cache, generate_idx)",
"filepath = get_resource(filepath)\nfor words, tags in generate_words_tags_from_tsv(filepath, lower=False):\n if ... | <|body_start_0|>
self.char_level = char_level
self.hard_constraint = hard_constraint
self.sent_delimiter = sent_delimiter
self.max_seq_len = max_seq_len
super().__init__(data, transform, cache, generate_idx)
<|end_body_0|>
<|body_start_1|>
filepath = get_resource(filepat... | TSVTaggingDataset | [
"Apache-2.0",
"CC-BY-NC-SA-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TSVTaggingDataset:
def __init__(self, data: Union[str, List], transform: Union[Callable, List]=None, cache=None, generate_idx=None, max_seq_len=None, sent_delimiter=None, char_level=False, hard_constraint=False, **kwargs) -> None:
"""Args: data: The local or remote path to a dataset, or ... | stack_v2_sparse_classes_36k_train_010654 | 3,588 | permissive | [
{
"docstring": "Args: data: The local or remote path to a dataset, or a list of samples where each sample is a dict. transform: Predefined transform(s). cache: ``True`` to enable caching, so that transforms won't be called twice. generate_idx: Create a :const:`~hanlp_common.constants.IDX` field for each sample ... | 2 | stack_v2_sparse_classes_30k_train_003345 | Implement the Python class `TSVTaggingDataset` described below.
Class description:
Implement the TSVTaggingDataset class.
Method signatures and docstrings:
- def __init__(self, data: Union[str, List], transform: Union[Callable, List]=None, cache=None, generate_idx=None, max_seq_len=None, sent_delimiter=None, char_lev... | Implement the Python class `TSVTaggingDataset` described below.
Class description:
Implement the TSVTaggingDataset class.
Method signatures and docstrings:
- def __init__(self, data: Union[str, List], transform: Union[Callable, List]=None, cache=None, generate_idx=None, max_seq_len=None, sent_delimiter=None, char_lev... | be2f04905a12990a527417bd47b79b851874a201 | <|skeleton|>
class TSVTaggingDataset:
def __init__(self, data: Union[str, List], transform: Union[Callable, List]=None, cache=None, generate_idx=None, max_seq_len=None, sent_delimiter=None, char_level=False, hard_constraint=False, **kwargs) -> None:
"""Args: data: The local or remote path to a dataset, or ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TSVTaggingDataset:
def __init__(self, data: Union[str, List], transform: Union[Callable, List]=None, cache=None, generate_idx=None, max_seq_len=None, sent_delimiter=None, char_level=False, hard_constraint=False, **kwargs) -> None:
"""Args: data: The local or remote path to a dataset, or a list of samp... | the_stack_v2_python_sparse | hanlp/datasets/ner/loaders/tsv.py | hankcs/HanLP | train | 32,454 | |
96173dbab64a704a24cb16fca1087886f4755f1a | [
"super().__init__(graph)\nif dim_p is None:\n dim_p = np.ceil(np.sqrt(2 * len(graph)))\nself.dim_p = int(dim_p)\nself._kwargs = kwargs",
"adjacent = nx.adjacency_matrix(self.graph).toarray()\nrtr = RiemannianTrustRegion(adjacent, self.dim_p, **self._kwargs)\ncandidates = rtr.get_candidates(verbose)\nmatrix, cu... | <|body_start_0|>
super().__init__(graph)
if dim_p is None:
dim_p = np.ceil(np.sqrt(2 * len(graph)))
self.dim_p = int(dim_p)
self._kwargs = kwargs
<|end_body_0|>
<|body_start_1|>
adjacent = nx.adjacency_matrix(self.graph).toarray()
rtr = RiemannianTrustRegion(... | Bureir-Monteiro approach solver for the Max-Cut problem. Given a graph with non-negative weights, the method implemented here aims at minimizing $$<CY, Y>$$, where C denotes the adjacency matrix of the graph and $Y$ is a matrix of dimensions (n, p) so that each of its rows is of unit norm. The implementation relies on ... | MaxCutBM | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaxCutBM:
"""Bureir-Monteiro approach solver for the Max-Cut problem. Given a graph with non-negative weights, the method implemented here aims at minimizing $$<CY, Y>$$, where C denotes the adjacency matrix of the graph and $Y$ is a matrix of dimensions (n, p) so that each of its rows is of unit... | stack_v2_sparse_classes_36k_train_010655 | 3,529 | permissive | [
{
"docstring": "Instantiate the Bureir-Monteiro Max-Cut solver. graph : networkx.Graph instance of the graph to cut dim_p : optional value of p; otherwise, use ceil(sqrt(2 * n_nodes)) **kwargs : any keyword argument for RiemannianTrustRegion may additionally be passed (e.g. maxiter)",
"name": "__init__",
... | 3 | null | Implement the Python class `MaxCutBM` described below.
Class description:
Bureir-Monteiro approach solver for the Max-Cut problem. Given a graph with non-negative weights, the method implemented here aims at minimizing $$<CY, Y>$$, where C denotes the adjacency matrix of the graph and $Y$ is a matrix of dimensions (n,... | Implement the Python class `MaxCutBM` described below.
Class description:
Bureir-Monteiro approach solver for the Max-Cut problem. Given a graph with non-negative weights, the method implemented here aims at minimizing $$<CY, Y>$$, where C denotes the adjacency matrix of the graph and $Y$ is a matrix of dimensions (n,... | 002c5ecbad671b75059290065db73a7152c98db9 | <|skeleton|>
class MaxCutBM:
"""Bureir-Monteiro approach solver for the Max-Cut problem. Given a graph with non-negative weights, the method implemented here aims at minimizing $$<CY, Y>$$, where C denotes the adjacency matrix of the graph and $Y$ is a matrix of dimensions (n, p) so that each of its rows is of unit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MaxCutBM:
"""Bureir-Monteiro approach solver for the Max-Cut problem. Given a graph with non-negative weights, the method implemented here aims at minimizing $$<CY, Y>$$, where C denotes the adjacency matrix of the graph and $Y$ is a matrix of dimensions (n, p) so that each of its rows is of unit norm. The im... | the_stack_v2_python_sparse | 启发式搜索与演化算法/hw4/_bm.py | jocelyn2002/NJUAI_CodingHW | train | 5 |
560ed6107d6f4861bc63da25c891c8e2eebd6c13 | [
"super(SentimentClassifierMLP, self).__init__()\nself.fc1 = nn.Linear(in_features=input_dim, out_features=hidden_dim)\nself.fc2 = nn.Linear(in_features=hidden_dim, out_features=output_dim)",
"y_out = self.fc1(x_in)\ny_out = F.relu(y_out)\ny_out = self.fc2(y_out)\nif apply_softmax:\n y_out = F.softmax(y_out, di... | <|body_start_0|>
super(SentimentClassifierMLP, self).__init__()
self.fc1 = nn.Linear(in_features=input_dim, out_features=hidden_dim)
self.fc2 = nn.Linear(in_features=hidden_dim, out_features=output_dim)
<|end_body_0|>
<|body_start_1|>
y_out = self.fc1(x_in)
y_out = F.relu(y_out)... | A 2-layer multilayer perceptron based classifier that uses one-hot encoding as an input sequence representation | SentimentClassifierMLP | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SentimentClassifierMLP:
"""A 2-layer multilayer perceptron based classifier that uses one-hot encoding as an input sequence representation"""
def __init__(self, input_dim, hidden_dim, output_dim):
"""Args: input_dim (int): the size of the input feature vector hidden_dim (int): the ou... | stack_v2_sparse_classes_36k_train_010656 | 1,999 | no_license | [
{
"docstring": "Args: input_dim (int): the size of the input feature vector hidden_dim (int): the output size of the first Linear layer output_dim (int): the output size of the second Linear layer",
"name": "__init__",
"signature": "def __init__(self, input_dim, hidden_dim, output_dim)"
},
{
"do... | 2 | stack_v2_sparse_classes_30k_train_013553 | Implement the Python class `SentimentClassifierMLP` described below.
Class description:
A 2-layer multilayer perceptron based classifier that uses one-hot encoding as an input sequence representation
Method signatures and docstrings:
- def __init__(self, input_dim, hidden_dim, output_dim): Args: input_dim (int): the ... | Implement the Python class `SentimentClassifierMLP` described below.
Class description:
A 2-layer multilayer perceptron based classifier that uses one-hot encoding as an input sequence representation
Method signatures and docstrings:
- def __init__(self, input_dim, hidden_dim, output_dim): Args: input_dim (int): the ... | 43a453a03060c2adf6bf16302d5138cfa77a30d1 | <|skeleton|>
class SentimentClassifierMLP:
"""A 2-layer multilayer perceptron based classifier that uses one-hot encoding as an input sequence representation"""
def __init__(self, input_dim, hidden_dim, output_dim):
"""Args: input_dim (int): the size of the input feature vector hidden_dim (int): the ou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SentimentClassifierMLP:
"""A 2-layer multilayer perceptron based classifier that uses one-hot encoding as an input sequence representation"""
def __init__(self, input_dim, hidden_dim, output_dim):
"""Args: input_dim (int): the size of the input feature vector hidden_dim (int): the output size of ... | the_stack_v2_python_sparse | workshops/sentiment2020/Solution/ModelMLP.py | Petlja/PSIML | train | 17 |
328bda4e6891fd1d1145b1320580ef8f119262b2 | [
"self.fig = plt.figure()\nsuper().__init__(self.fig)\nself.ax_main = self.fig.add_subplot()\nif hasattr(specmodel, 'spec'):\n if specmodel.spec is not None:\n specmodel._plot_specmodel(self.ax_main)\nself.ax_main.set_xlim(specmodel.xlim)\nself.ax_main.set_ylim(specmodel.ylim)\nself.draw()",
"self.ax_mai... | <|body_start_0|>
self.fig = plt.figure()
super().__init__(self.fig)
self.ax_main = self.fig.add_subplot()
if hasattr(specmodel, 'spec'):
if specmodel.spec is not None:
specmodel._plot_specmodel(self.ax_main)
self.ax_main.set_xlim(specmodel.xlim)
... | A FigureCanvas for plotting an astronomical spectrum from a SpecModel object. This class provides the plotting routine for the SpecModelWidget. Attributes: fig (matplotlib.figure.Figure): Figure object for the plot. ax_main (matplotlib.axes.Axis): Axis for main plot | SpecModelCanvas | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpecModelCanvas:
"""A FigureCanvas for plotting an astronomical spectrum from a SpecModel object. This class provides the plotting routine for the SpecModelWidget. Attributes: fig (matplotlib.figure.Figure): Figure object for the plot. ax_main (matplotlib.axes.Axis): Axis for main plot"""
de... | stack_v2_sparse_classes_36k_train_010657 | 1,655 | permissive | [
{
"docstring": "Initilization method for the SpecFitCanvas :param (SpecModel) specmodel: SpecModel object, which holds information on the astronomical spectrum and its fit.",
"name": "__init__",
"signature": "def __init__(self, specmodel)"
},
{
"docstring": "Plot the spectrum and the model :para... | 2 | stack_v2_sparse_classes_30k_train_015073 | Implement the Python class `SpecModelCanvas` described below.
Class description:
A FigureCanvas for plotting an astronomical spectrum from a SpecModel object. This class provides the plotting routine for the SpecModelWidget. Attributes: fig (matplotlib.figure.Figure): Figure object for the plot. ax_main (matplotlib.ax... | Implement the Python class `SpecModelCanvas` described below.
Class description:
A FigureCanvas for plotting an astronomical spectrum from a SpecModel object. This class provides the plotting routine for the SpecModelWidget. Attributes: fig (matplotlib.figure.Figure): Figure object for the plot. ax_main (matplotlib.ax... | a71c24f07a13546e662271349b1e83b31ac1720e | <|skeleton|>
class SpecModelCanvas:
"""A FigureCanvas for plotting an astronomical spectrum from a SpecModel object. This class provides the plotting routine for the SpecModelWidget. Attributes: fig (matplotlib.figure.Figure): Figure object for the plot. ax_main (matplotlib.axes.Axis): Axis for main plot"""
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpecModelCanvas:
"""A FigureCanvas for plotting an astronomical spectrum from a SpecModel object. This class provides the plotting routine for the SpecModelWidget. Attributes: fig (matplotlib.figure.Figure): Figure object for the plot. ax_main (matplotlib.axes.Axis): Axis for main plot"""
def __init__(se... | the_stack_v2_python_sparse | sculptor/specmodelcanvas.py | jtschindler/sculptor | train | 9 |
acd0bc0cc66c416df26241f5a8fd54ffbe0e8f9e | [
"t = parse_tree(\"(('foo' : 0.1, 'bar' : 1.0) : 2, baz)\")\nself.assertEqual(len(t.get_edges()), 2)\n(t1, b1, l1), (t2, b2, l2) = t.get_edges()\nself.assertEqual(len(t1.get_edges()), 2)\nself.assertEqual(l1, 2.0)\nself.assertEqual(t2.__class__, Leaf)\nself.assertEqual(l2, None)\nself.assertEqual(t.leaves_identifier... | <|body_start_0|>
t = parse_tree("(('foo' : 0.1, 'bar' : 1.0) : 2, baz)")
self.assertEqual(len(t.get_edges()), 2)
(t1, b1, l1), (t2, b2, l2) = t.get_edges()
self.assertEqual(len(t1.get_edges()), 2)
self.assertEqual(l1, 2.0)
self.assertEqual(t2.__class__, Leaf)
self... | Test of the parse_tree() function. | TestParseTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestParseTree:
"""Test of the parse_tree() function."""
def testTreeStructure(self):
"""Test that a parsed tree has the right structure."""
<|body_0|>
def testSpecialCases(self):
"""Test that we can parse some special cases of trees."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_010658 | 4,457 | no_license | [
{
"docstring": "Test that a parsed tree has the right structure.",
"name": "testTreeStructure",
"signature": "def testTreeStructure(self)"
},
{
"docstring": "Test that we can parse some special cases of trees.",
"name": "testSpecialCases",
"signature": "def testSpecialCases(self)"
}
] | 2 | null | Implement the Python class `TestParseTree` described below.
Class description:
Test of the parse_tree() function.
Method signatures and docstrings:
- def testTreeStructure(self): Test that a parsed tree has the right structure.
- def testSpecialCases(self): Test that we can parse some special cases of trees. | Implement the Python class `TestParseTree` described below.
Class description:
Test of the parse_tree() function.
Method signatures and docstrings:
- def testTreeStructure(self): Test that a parsed tree has the right structure.
- def testSpecialCases(self): Test that we can parse some special cases of trees.
<|skele... | 40979405a43703506b84925b26bb9d2c7c9c021b | <|skeleton|>
class TestParseTree:
"""Test of the parse_tree() function."""
def testTreeStructure(self):
"""Test that a parsed tree has the right structure."""
<|body_0|>
def testSpecialCases(self):
"""Test that we can parse some special cases of trees."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestParseTree:
"""Test of the parse_tree() function."""
def testTreeStructure(self):
"""Test that a parsed tree has the right structure."""
t = parse_tree("(('foo' : 0.1, 'bar' : 1.0) : 2, baz)")
self.assertEqual(len(t.get_edges()), 2)
(t1, b1, l1), (t2, b2, l2) = t.get_ed... | the_stack_v2_python_sparse | newick_modified/treetest.py | dtneves/SuperFine | train | 7 |
a55fe2eacead91f0973ce740dea2fa80d7de197c | [
"status = ErrorCode.SUCCESS\ntry:\n profile = DotDict()\n oper = QueryHelper.get_operator_by_oid(self.current_user.oid, self.db)\n if not oper:\n status = ErrorCode.LOGIN_AGAIN\n logging.error('[UWEB] Operator does not exist, redirect to login.html. oid: %s.', self.current_user.oid)\n ... | <|body_start_0|>
status = ErrorCode.SUCCESS
try:
profile = DotDict()
oper = QueryHelper.get_operator_by_oid(self.current_user.oid, self.db)
if not oper:
status = ErrorCode.LOGIN_AGAIN
logging.error('[UWEB] Operator does not exist, redir... | ProfileOperHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileOperHandler:
def get(self):
"""Display profile of current operator."""
<|body_0|>
def put(self):
"""Modify profile of current operator."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
status = ErrorCode.SUCCESS
try:
profil... | stack_v2_sparse_classes_36k_train_010659 | 8,584 | no_license | [
{
"docstring": "Display profile of current operator.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Modify profile of current operator.",
"name": "put",
"signature": "def put(self)"
}
] | 2 | null | Implement the Python class `ProfileOperHandler` described below.
Class description:
Implement the ProfileOperHandler class.
Method signatures and docstrings:
- def get(self): Display profile of current operator.
- def put(self): Modify profile of current operator. | Implement the Python class `ProfileOperHandler` described below.
Class description:
Implement the ProfileOperHandler class.
Method signatures and docstrings:
- def get(self): Display profile of current operator.
- def put(self): Modify profile of current operator.
<|skeleton|>
class ProfileOperHandler:
def get(... | 3b095a325581b1fc48497c234f0ad55e928586a1 | <|skeleton|>
class ProfileOperHandler:
def get(self):
"""Display profile of current operator."""
<|body_0|>
def put(self):
"""Modify profile of current operator."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProfileOperHandler:
def get(self):
"""Display profile of current operator."""
status = ErrorCode.SUCCESS
try:
profile = DotDict()
oper = QueryHelper.get_operator_by_oid(self.current_user.oid, self.db)
if not oper:
status = ErrorCode.L... | the_stack_v2_python_sparse | apps/uweb/handlers/profile.py | jcsy521/ydws | train | 0 | |
b62173335183be65b5f41cc1779a5b84b3e2cbfb | [
"super(C51DQN, self).__init__()\nobs_shape, action_shape = (squeeze(obs_shape), squeeze(action_shape))\nif isinstance(obs_shape, int) or len(obs_shape) == 1:\n self.encoder = FCEncoder(obs_shape, encoder_hidden_size_list, activation=activation, norm_type=norm_type)\nelif len(obs_shape) == 3:\n self.encoder = ... | <|body_start_0|>
super(C51DQN, self).__init__()
obs_shape, action_shape = (squeeze(obs_shape), squeeze(action_shape))
if isinstance(obs_shape, int) or len(obs_shape) == 1:
self.encoder = FCEncoder(obs_shape, encoder_hidden_size_list, activation=activation, norm_type=norm_type)
... | C51DQN | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class C51DQN:
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: int=64, head_layer_num: int=1, activation: Optional[nn.Module]=nn.ReLU(), norm_type: Optional[str]=None, v_min: Optiona... | stack_v2_sparse_classes_36k_train_010660 | 30,380 | permissive | [
{
"docstring": "Overview: Init the C51 Model according to input arguments. Arguments: - obs_shape (:obj:`Union[int, SequenceType]`): Observation's space. - action_shape (:obj:`Union[int, SequenceType]`): Action's space. - encoder_hidden_size_list (:obj:`SequenceType`): Collection of ``hidden_size`` to pass to `... | 2 | stack_v2_sparse_classes_30k_train_000567 | Implement the Python class `C51DQN` described below.
Class description:
Implement the C51DQN class.
Method signatures and docstrings:
- def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: int=64, head_... | Implement the Python class `C51DQN` described below.
Class description:
Implement the C51DQN class.
Method signatures and docstrings:
- def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: int=64, head_... | eb483fa6e46602d58c8e7d2ca1e566adca28e703 | <|skeleton|>
class C51DQN:
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: int=64, head_layer_num: int=1, activation: Optional[nn.Module]=nn.ReLU(), norm_type: Optional[str]=None, v_min: Optiona... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class C51DQN:
def __init__(self, obs_shape: Union[int, SequenceType], action_shape: Union[int, SequenceType], encoder_hidden_size_list: SequenceType=[128, 128, 64], head_hidden_size: int=64, head_layer_num: int=1, activation: Optional[nn.Module]=nn.ReLU(), norm_type: Optional[str]=None, v_min: Optional[float]=-10, ... | the_stack_v2_python_sparse | ding/model/template/q_learning.py | shengxuesun/DI-engine | train | 1 | |
ae40e0efbf4c9f7c9c1627538b6ebab90918b6ae | [
"IMAGE = 'image'\nstart_time = datetime.datetime.now()\nif IMAGE not in request.data or not isinstance(request.data[IMAGE], InMemoryUploadedFile):\n return SimpleResponse(status=status.HTTP_400_BAD_REQUEST)\nrequest.data[IMAGE].name = str(datetime.datetime.now().microsecond) + str(request.data[IMAGE].name)\nseri... | <|body_start_0|>
IMAGE = 'image'
start_time = datetime.datetime.now()
if IMAGE not in request.data or not isinstance(request.data[IMAGE], InMemoryUploadedFile):
return SimpleResponse(status=status.HTTP_400_BAD_REQUEST)
request.data[IMAGE].name = str(datetime.datetime.now().mi... | ImageViewSet | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageViewSet:
def create(self, request):
"""Upload an image. --- omit_serializer: true omit_parameters: - form parameters: - name: image type: file"""
<|body_0|>
def list(self, request):
"""List all images. --- omit_serializer: true"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_010661 | 1,788 | permissive | [
{
"docstring": "Upload an image. --- omit_serializer: true omit_parameters: - form parameters: - name: image type: file",
"name": "create",
"signature": "def create(self, request)"
},
{
"docstring": "List all images. --- omit_serializer: true",
"name": "list",
"signature": "def list(self... | 2 | stack_v2_sparse_classes_30k_train_012086 | Implement the Python class `ImageViewSet` described below.
Class description:
Implement the ImageViewSet class.
Method signatures and docstrings:
- def create(self, request): Upload an image. --- omit_serializer: true omit_parameters: - form parameters: - name: image type: file
- def list(self, request): List all ima... | Implement the Python class `ImageViewSet` described below.
Class description:
Implement the ImageViewSet class.
Method signatures and docstrings:
- def create(self, request): Upload an image. --- omit_serializer: true omit_parameters: - form parameters: - name: image type: file
- def list(self, request): List all ima... | 31ac08148fbe67ab166faa897c0cbe72cd7f62db | <|skeleton|>
class ImageViewSet:
def create(self, request):
"""Upload an image. --- omit_serializer: true omit_parameters: - form parameters: - name: image type: file"""
<|body_0|>
def list(self, request):
"""List all images. --- omit_serializer: true"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageViewSet:
def create(self, request):
"""Upload an image. --- omit_serializer: true omit_parameters: - form parameters: - name: image type: file"""
IMAGE = 'image'
start_time = datetime.datetime.now()
if IMAGE not in request.data or not isinstance(request.data[IMAGE], InMemo... | the_stack_v2_python_sparse | wheat/apps/image/apis.py | fortyMiles/moment-note | train | 2 | |
86fb1e3951d579b6b2023346d0cc8b054f5586b5 | [
"if not root or root == p or root == q:\n return root\nleft = self.lowestCommonAncestor(root.left, p, q)\nright = self.lowestCommonAncestor(root.right, p, q)\nif not left:\n return right\nif not right:\n return left\nreturn root",
"if not root or root == p or root == q:\n return root\nleft = self.lowe... | <|body_start_0|>
if not root or root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if not left:
return right
if not right:
return left
return root
<|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""祖先的定义:若节点p在节点root的左/右子树中,或者p=root,则称root 是p的祖先 最近公共祖先的定义:设节点root为节点p,q的某公共祖先,若其左子节点root.left 和右子节点 root.right都不是p和q的公共祖先,则称root是“最近的公共祖先” 根据以上定义,若root是p,q的最近公共祖先,则只可能为以下情况之一: 1,p和q ... | stack_v2_sparse_classes_36k_train_010662 | 4,599 | no_license | [
{
"docstring": "祖先的定义:若节点p在节点root的左/右子树中,或者p=root,则称root 是p的祖先 最近公共祖先的定义:设节点root为节点p,q的某公共祖先,若其左子节点root.left 和右子节点 root.right都不是p和q的公共祖先,则称root是“最近的公共祖先” 根据以上定义,若root是p,q的最近公共祖先,则只可能为以下情况之一: 1,p和q 在root的子树中,且分列root的异侧,(即分别在左,右子树中) 2,p=root,且q在root的左子树或右子树中 3,q=root,且p在root的左子树或右子树中 考虑通过递归对二叉树进行后续遍历,当遇到节点p和q时返回,... | 2 | stack_v2_sparse_classes_30k_train_011070 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 祖先的定义:若节点p在节点root的左/右子树中,或者p=root,则称root 是p的祖先 最近公共祖先的定义:设节点root为节点p,q的某公共祖先,若其左子节点r... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 祖先的定义:若节点p在节点root的左/右子树中,或者p=root,则称root 是p的祖先 最近公共祖先的定义:设节点root为节点p,q的某公共祖先,若其左子节点r... | 51943e2c2c4ec70c7c1d5b53c9fdf0a719428d7a | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""祖先的定义:若节点p在节点root的左/右子树中,或者p=root,则称root 是p的祖先 最近公共祖先的定义:设节点root为节点p,q的某公共祖先,若其左子节点root.left 和右子节点 root.right都不是p和q的公共祖先,则称root是“最近的公共祖先” 根据以上定义,若root是p,q的最近公共祖先,则只可能为以下情况之一: 1,p和q ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""祖先的定义:若节点p在节点root的左/右子树中,或者p=root,则称root 是p的祖先 最近公共祖先的定义:设节点root为节点p,q的某公共祖先,若其左子节点root.left 和右子节点 root.right都不是p和q的公共祖先,则称root是“最近的公共祖先” 根据以上定义,若root是p,q的最近公共祖先,则只可能为以下情况之一: 1,p和q 在root的子树中,且分列r... | the_stack_v2_python_sparse | 剑指offer/PythonVersion/68_2_二叉树的最近公共祖先.py | LeBron-Jian/BasicAlgorithmPractice | train | 13 | |
67d2cbc2f51c1ae654776666ac85d2424fd1e16e | [
"accumulator = gamma11.QuarticTermDictAccumulator()\n_add_term(accumulator)\nfirst_entries = list(itertools.islice(accumulator.collected(scale_by=0.125), 0, 3))\nexpected = [(-1.5, ('psi_v01s01', 'psi_v01s02', 'psi_v02s01', 'psi_v02s02')), (-3.0, ('psi_v01s01', 'psi_v01s02', 'psi_v02s09', 'psi_v02s10')), (3.0, ('ps... | <|body_start_0|>
accumulator = gamma11.QuarticTermDictAccumulator()
_add_term(accumulator)
first_entries = list(itertools.islice(accumulator.collected(scale_by=0.125), 0, 3))
expected = [(-1.5, ('psi_v01s01', 'psi_v01s02', 'psi_v02s01', 'psi_v02s02')), (-3.0, ('psi_v01s01', 'psi_v01s02',... | Validation of some basic calculations. | ComputationTest | [
"CC-BY-4.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComputationTest:
"""Validation of some basic calculations."""
def test_dict_accumulator_computation(self):
"""Validates a basic dict-accumulator calculation."""
<|body_0|>
def test_fast_accumulator_computation(self):
"""Validates a basic fast-accumulator calculat... | stack_v2_sparse_classes_36k_train_010663 | 12,035 | permissive | [
{
"docstring": "Validates a basic dict-accumulator calculation.",
"name": "test_dict_accumulator_computation",
"signature": "def test_dict_accumulator_computation(self)"
},
{
"docstring": "Validates a basic fast-accumulator calculation.",
"name": "test_fast_accumulator_computation",
"sig... | 4 | null | Implement the Python class `ComputationTest` described below.
Class description:
Validation of some basic calculations.
Method signatures and docstrings:
- def test_dict_accumulator_computation(self): Validates a basic dict-accumulator calculation.
- def test_fast_accumulator_computation(self): Validates a basic fast... | Implement the Python class `ComputationTest` described below.
Class description:
Validation of some basic calculations.
Method signatures and docstrings:
- def test_dict_accumulator_computation(self): Validates a basic dict-accumulator calculation.
- def test_fast_accumulator_computation(self): Validates a basic fast... | c1ae273841592fce4c993bf35cdd0a6424e73da4 | <|skeleton|>
class ComputationTest:
"""Validation of some basic calculations."""
def test_dict_accumulator_computation(self):
"""Validates a basic dict-accumulator calculation."""
<|body_0|>
def test_fast_accumulator_computation(self):
"""Validates a basic fast-accumulator calculat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ComputationTest:
"""Validation of some basic calculations."""
def test_dict_accumulator_computation(self):
"""Validates a basic dict-accumulator calculation."""
accumulator = gamma11.QuarticTermDictAccumulator()
_add_term(accumulator)
first_entries = list(itertools.islice(... | the_stack_v2_python_sparse | m_theory/dim1/papers/gamma_bth/gamma11_test.py | ishine/google-research | train | 0 |
cfbbd6b39e914142109e4cd7154ce1b886a62fff | [
"self.before_get_collection(qs, view_kwargs)\nquery = self.query(view_kwargs)\nif filters:\n query = query.filter_by(**filters)\nif qs.filters:\n query = self.filter_query(query, qs.filters, self.model)\nobject_count = query.count()\nif getattr(self, 'eagerload_includes', True):\n query = self.eagerload_in... | <|body_start_0|>
self.before_get_collection(qs, view_kwargs)
query = self.query(view_kwargs)
if filters:
query = query.filter_by(**filters)
if qs.filters:
query = self.filter_query(query, qs.filters, self.model)
object_count = query.count()
if geta... | Sqlalchemy data layer specifically to use python sorting. | SearchDataLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchDataLayer:
"""Sqlalchemy data layer specifically to use python sorting."""
def get_collection(self, qs, view_kwargs, filters=None):
"""Retrieve a collection of objects through sqlalchemy :param QueryStringManager qs: a querystring manager to retrieve information from url :param... | stack_v2_sparse_classes_36k_train_010664 | 2,921 | permissive | [
{
"docstring": "Retrieve a collection of objects through sqlalchemy :param QueryStringManager qs: a querystring manager to retrieve information from url :param dict view_kwargs: kwargs from the resource view :param dict filters: A dictionary of key/value filters to apply to the eventual query :return tuple: the... | 3 | stack_v2_sparse_classes_30k_train_010081 | Implement the Python class `SearchDataLayer` described below.
Class description:
Sqlalchemy data layer specifically to use python sorting.
Method signatures and docstrings:
- def get_collection(self, qs, view_kwargs, filters=None): Retrieve a collection of objects through sqlalchemy :param QueryStringManager qs: a qu... | Implement the Python class `SearchDataLayer` described below.
Class description:
Sqlalchemy data layer specifically to use python sorting.
Method signatures and docstrings:
- def get_collection(self, qs, view_kwargs, filters=None): Retrieve a collection of objects through sqlalchemy :param QueryStringManager qs: a qu... | 21c7597b35f83f0c9ff6197db702268f05e98be2 | <|skeleton|>
class SearchDataLayer:
"""Sqlalchemy data layer specifically to use python sorting."""
def get_collection(self, qs, view_kwargs, filters=None):
"""Retrieve a collection of objects through sqlalchemy :param QueryStringManager qs: a querystring manager to retrieve information from url :param... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SearchDataLayer:
"""Sqlalchemy data layer specifically to use python sorting."""
def get_collection(self, qs, view_kwargs, filters=None):
"""Retrieve a collection of objects through sqlalchemy :param QueryStringManager qs: a querystring manager to retrieve information from url :param dict view_kw... | the_stack_v2_python_sparse | resolver/api/data_layers.py | Chemical-Curation/resolver | train | 0 |
706e065d5a7f1fe0b5b92beff9432613340340a9 | [
"data = []\ndata.append(scheduler_id)\nres = requests.post(url=enable_scheduler_url, headers=get_headers(HOST_189), data=json.dumps(data))\nself.assertEqual(res.status_code, 204, msg='启用计划接口调用失败')",
"data = []\ndata.append(scheduler_id)\nres = requests.post(url=disable_scheduler_url, headers=get_headers(HOST_189)... | <|body_start_0|>
data = []
data.append(scheduler_id)
res = requests.post(url=enable_scheduler_url, headers=get_headers(HOST_189), data=json.dumps(data))
self.assertEqual(res.status_code, 204, msg='启用计划接口调用失败')
<|end_body_0|>
<|body_start_1|>
data = []
data.append(schedul... | 测试启用停用、批量删除schedulers接口 | EnableDisable | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnableDisable:
"""测试启用停用、批量删除schedulers接口"""
def test_case01(self):
"""启用计划"""
<|body_0|>
def test_case02(self):
"""停用计划"""
<|body_1|>
def test_case03(self):
"""批量删除计划"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
data = [... | stack_v2_sparse_classes_36k_train_010665 | 15,511 | no_license | [
{
"docstring": "启用计划",
"name": "test_case01",
"signature": "def test_case01(self)"
},
{
"docstring": "停用计划",
"name": "test_case02",
"signature": "def test_case02(self)"
},
{
"docstring": "批量删除计划",
"name": "test_case03",
"signature": "def test_case03(self)"
}
] | 3 | stack_v2_sparse_classes_30k_train_013952 | Implement the Python class `EnableDisable` described below.
Class description:
测试启用停用、批量删除schedulers接口
Method signatures and docstrings:
- def test_case01(self): 启用计划
- def test_case02(self): 停用计划
- def test_case03(self): 批量删除计划 | Implement the Python class `EnableDisable` described below.
Class description:
测试启用停用、批量删除schedulers接口
Method signatures and docstrings:
- def test_case01(self): 启用计划
- def test_case02(self): 停用计划
- def test_case03(self): 批量删除计划
<|skeleton|>
class EnableDisable:
"""测试启用停用、批量删除schedulers接口"""
def test_case01... | fc41513af3063169ff1b17d6f01f7074057ceb1f | <|skeleton|>
class EnableDisable:
"""测试启用停用、批量删除schedulers接口"""
def test_case01(self):
"""启用计划"""
<|body_0|>
def test_case02(self):
"""停用计划"""
<|body_1|>
def test_case03(self):
"""批量删除计划"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EnableDisable:
"""测试启用停用、批量删除schedulers接口"""
def test_case01(self):
"""启用计划"""
data = []
data.append(scheduler_id)
res = requests.post(url=enable_scheduler_url, headers=get_headers(HOST_189), data=json.dumps(data))
self.assertEqual(res.status_code, 204, msg='启用计划接口... | the_stack_v2_python_sparse | singl_api/api_test_cases/cases_for_schedulers_api.py | bingjiegu/For_API | train | 0 |
30888ce6691053cf4bca606de63403c2ffbb24e0 | [
"driver = browser\ndriver.get(base_url)\ndriver.find_element_by_xpath(\"//span[text()='账号登录']\").click()\ndriver.get_screenshot_as_file(images_path + 'test_login_case-验证截图-' + str(time.time()) + '.png')\ndriver.find_element_by_id('username_no').send_keys(self.user)\ndriver.find_element_by_id('password').send_keys(s... | <|body_start_0|>
driver = browser
driver.get(base_url)
driver.find_element_by_xpath("//span[text()='账号登录']").click()
driver.get_screenshot_as_file(images_path + 'test_login_case-验证截图-' + str(time.time()) + '.png')
driver.find_element_by_id('username_no').send_keys(self.user)
... | 测试登录 | Testsign | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Testsign:
"""测试登录"""
def test_login_case(self, browser, base_url, images_path):
"""测试登录"""
<|body_0|>
def test_create(self, browser, images_path):
"""新建文件夹"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
driver = browser
driver.get(base_... | stack_v2_sparse_classes_36k_train_010666 | 2,702 | no_license | [
{
"docstring": "测试登录",
"name": "test_login_case",
"signature": "def test_login_case(self, browser, base_url, images_path)"
},
{
"docstring": "新建文件夹",
"name": "test_create",
"signature": "def test_create(self, browser, images_path)"
}
] | 2 | null | Implement the Python class `Testsign` described below.
Class description:
测试登录
Method signatures and docstrings:
- def test_login_case(self, browser, base_url, images_path): 测试登录
- def test_create(self, browser, images_path): 新建文件夹 | Implement the Python class `Testsign` described below.
Class description:
测试登录
Method signatures and docstrings:
- def test_login_case(self, browser, base_url, images_path): 测试登录
- def test_create(self, browser, images_path): 新建文件夹
<|skeleton|>
class Testsign:
"""测试登录"""
def test_login_case(self, browser, b... | baa61dafeeebb39390bcfa1f85237ebd44021918 | <|skeleton|>
class Testsign:
"""测试登录"""
def test_login_case(self, browser, base_url, images_path):
"""测试登录"""
<|body_0|>
def test_create(self, browser, images_path):
"""新建文件夹"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Testsign:
"""测试登录"""
def test_login_case(self, browser, base_url, images_path):
"""测试登录"""
driver = browser
driver.get(base_url)
driver.find_element_by_xpath("//span[text()='账号登录']").click()
driver.get_screenshot_as_file(images_path + 'test_login_case-验证截图-' + str(... | the_stack_v2_python_sparse | test_dir/1test_Alogin.py | qinchuan-he/ui-test | train | 1 |
f792352fdeb28ea284804cd869049f0028cbec07 | [
"fn = itembarNode.getAttr('back', data.D_FILENAME)\nkwargs['background'] = fn\nself.init(parent, **kwargs)\nfn = itembarNode.getAttr('backarrow', data.D_FILENAME)\nself.backArrow = data.getImage(fn, itembarNode.ditto_fn)\nself.icon = None\nself.labels = []",
"if self.icon is not None:\n self.icon.destroy()\n ... | <|body_start_0|>
fn = itembarNode.getAttr('back', data.D_FILENAME)
kwargs['background'] = fn
self.init(parent, **kwargs)
fn = itembarNode.getAttr('backarrow', data.D_FILENAME)
self.backArrow = data.getImage(fn, itembarNode.ditto_fn)
self.icon = None
self.labels = ... | Widget to show the item info at the bottom of the screen. | ItemBar | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ItemBar:
"""Widget to show the item info at the bottom of the screen."""
def __init__(self, parent, itembarNode, **kwargs):
"""Create the item bar. parent - the parent widget. location - the location of the widget relative to its parent. font - the font to write with. itembarNode - t... | stack_v2_sparse_classes_36k_train_010667 | 18,452 | no_license | [
{
"docstring": "Create the item bar. parent - the parent widget. location - the location of the widget relative to its parent. font - the font to write with. itembarNode - the <itembar> node.",
"name": "__init__",
"signature": "def __init__(self, parent, itembarNode, **kwargs)"
},
{
"docstring":... | 3 | stack_v2_sparse_classes_30k_val_000378 | Implement the Python class `ItemBar` described below.
Class description:
Widget to show the item info at the bottom of the screen.
Method signatures and docstrings:
- def __init__(self, parent, itembarNode, **kwargs): Create the item bar. parent - the parent widget. location - the location of the widget relative to i... | Implement the Python class `ItemBar` described below.
Class description:
Widget to show the item info at the bottom of the screen.
Method signatures and docstrings:
- def __init__(self, parent, itembarNode, **kwargs): Create the item bar. parent - the parent widget. location - the location of the widget relative to i... | 72841fc503c716ac3b524e42f2311cbd9d18a092 | <|skeleton|>
class ItemBar:
"""Widget to show the item info at the bottom of the screen."""
def __init__(self, parent, itembarNode, **kwargs):
"""Create the item bar. parent - the parent widget. location - the location of the widget relative to its parent. font - the font to write with. itembarNode - t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ItemBar:
"""Widget to show the item info at the bottom of the screen."""
def __init__(self, parent, itembarNode, **kwargs):
"""Create the item bar. parent - the parent widget. location - the location of the widget relative to its parent. font - the font to write with. itembarNode - the <itembar> ... | the_stack_v2_python_sparse | eng/menus/bag_screen.py | andrew-turner/Ditto | train | 0 |
67347296046b45bd31aeaef3c0ca45b1f6fb8ec3 | [
"self.model = model\nself.beta = beta\nself.S0 = S0\nself.iso = iso",
"odf_matrix = self.model.cache_get('odf_matrix', key=sphere)\nif odf_matrix is None:\n odf_matrix = sfm_design_matrix(sphere, self.model.sphere, self.model.response, mode='odf')\n self.model.cache_set('odf_matrix', key=sphere, value=odf_m... | <|body_start_0|>
self.model = model
self.beta = beta
self.S0 = S0
self.iso = iso
<|end_body_0|>
<|body_start_1|>
odf_matrix = self.model.cache_get('odf_matrix', key=sphere)
if odf_matrix is None:
odf_matrix = sfm_design_matrix(sphere, self.model.sphere, self.... | SparseFascicleFit | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparseFascicleFit:
def __init__(self, model, beta, S0, iso):
"""Initalize a SparseFascicleFit class instance Parameters ---------- model : a SparseFascicleModel object. beta : ndarray The parameters of fit to data. S0 : ndarray The mean non-diffusion-weighted signal. iso : IsotropicFit c... | stack_v2_sparse_classes_36k_train_010668 | 20,499 | permissive | [
{
"docstring": "Initalize a SparseFascicleFit class instance Parameters ---------- model : a SparseFascicleModel object. beta : ndarray The parameters of fit to data. S0 : ndarray The mean non-diffusion-weighted signal. iso : IsotropicFit class instance A representation of the isotropic signal, together with pa... | 3 | stack_v2_sparse_classes_30k_train_000201 | Implement the Python class `SparseFascicleFit` described below.
Class description:
Implement the SparseFascicleFit class.
Method signatures and docstrings:
- def __init__(self, model, beta, S0, iso): Initalize a SparseFascicleFit class instance Parameters ---------- model : a SparseFascicleModel object. beta : ndarra... | Implement the Python class `SparseFascicleFit` described below.
Class description:
Implement the SparseFascicleFit class.
Method signatures and docstrings:
- def __init__(self, model, beta, S0, iso): Initalize a SparseFascicleFit class instance Parameters ---------- model : a SparseFascicleModel object. beta : ndarra... | 3c3acc55de8ba741e673063378e6cbaf10b64c7a | <|skeleton|>
class SparseFascicleFit:
def __init__(self, model, beta, S0, iso):
"""Initalize a SparseFascicleFit class instance Parameters ---------- model : a SparseFascicleModel object. beta : ndarray The parameters of fit to data. S0 : ndarray The mean non-diffusion-weighted signal. iso : IsotropicFit c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SparseFascicleFit:
def __init__(self, model, beta, S0, iso):
"""Initalize a SparseFascicleFit class instance Parameters ---------- model : a SparseFascicleModel object. beta : ndarray The parameters of fit to data. S0 : ndarray The mean non-diffusion-weighted signal. iso : IsotropicFit class instance ... | the_stack_v2_python_sparse | env/lib/python3.6/site-packages/dipy/reconst/sfm.py | Raniac/NEURO-LEARN | train | 9 | |
8fc4ad8eb0af74968a7f7bec0dd034117fdc371b | [
"data, n_samples = preclean_X(data, feature_names, feature_types)\npredict_fn, n_classes, _ = determine_classes(model, data, n_samples)\nif 3 <= n_classes:\n raise Exception('multiclass PDP not supported')\npredict_fn = unify_predict_fn(predict_fn, data, 1 if n_classes == 2 else -1)\ndata, self.feature_names_in_... | <|body_start_0|>
data, n_samples = preclean_X(data, feature_names, feature_types)
predict_fn, n_classes, _ = determine_classes(model, data, n_samples)
if 3 <= n_classes:
raise Exception('multiclass PDP not supported')
predict_fn = unify_predict_fn(predict_fn, data, 1 if n_cla... | Partial dependence plots as defined in Friedman's paper on "Greedy function approximation: a gradient boosting machine". Friedman, Jerome H. "Greedy function approximation: a gradient boosting machine." Annals of statistics (2001): 1189-1232. | PartialDependence | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PartialDependence:
"""Partial dependence plots as defined in Friedman's paper on "Greedy function approximation: a gradient boosting machine". Friedman, Jerome H. "Greedy function approximation: a gradient boosting machine." Annals of statistics (2001): 1189-1232."""
def __init__(self, model... | stack_v2_sparse_classes_36k_train_010669 | 8,611 | permissive | [
{
"docstring": "Initializes class. Args: model: model or prediction function of model (predict_proba for classification or predict for regression) data: Data used to initialize PartialDependence with. feature_names: List of feature names. feature_types: List of feature types. num_points: Number of grid points f... | 2 | stack_v2_sparse_classes_30k_train_009225 | Implement the Python class `PartialDependence` described below.
Class description:
Partial dependence plots as defined in Friedman's paper on "Greedy function approximation: a gradient boosting machine". Friedman, Jerome H. "Greedy function approximation: a gradient boosting machine." Annals of statistics (2001): 1189... | Implement the Python class `PartialDependence` described below.
Class description:
Partial dependence plots as defined in Friedman's paper on "Greedy function approximation: a gradient boosting machine". Friedman, Jerome H. "Greedy function approximation: a gradient boosting machine." Annals of statistics (2001): 1189... | e6f38ea195aecbbd9d28c7183a83c65ada16e1ae | <|skeleton|>
class PartialDependence:
"""Partial dependence plots as defined in Friedman's paper on "Greedy function approximation: a gradient boosting machine". Friedman, Jerome H. "Greedy function approximation: a gradient boosting machine." Annals of statistics (2001): 1189-1232."""
def __init__(self, model... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PartialDependence:
"""Partial dependence plots as defined in Friedman's paper on "Greedy function approximation: a gradient boosting machine". Friedman, Jerome H. "Greedy function approximation: a gradient boosting machine." Annals of statistics (2001): 1189-1232."""
def __init__(self, model, data, featu... | the_stack_v2_python_sparse | python/interpret-core/interpret/blackbox/_partialdependence.py | interpretml/interpret | train | 3,731 |
5e5bd9dc82485414db223679dada794371e3389e | [
"request = make_wsgi_request('sites/')\nresponse = views.api_sites(request)\nresults = json.loads(response.content.decode('utf-8'))\nfast_lookup = {}\nfor site_rcd in results:\n fast_lookup[site_rcd['URL']] = site_rcd\nself.assertEqual(TownnewsSite.objects.count(), len(fast_lookup))\nfor site in TownnewsSite.obj... | <|body_start_0|>
request = make_wsgi_request('sites/')
response = views.api_sites(request)
results = json.loads(response.content.decode('utf-8'))
fast_lookup = {}
for site_rcd in results:
fast_lookup[site_rcd['URL']] = site_rcd
self.assertEqual(TownnewsSite.ob... | Unit tests for api/sites/ URLs. | api_sites_TestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class api_sites_TestCase:
"""Unit tests for api/sites/ URLs."""
def test_all(self):
"""Unit test for :py:func:`papers.views.api_sites` with no paper specified."""
<|body_0|>
def test_paper(self):
"""Unit test for :py:func:`papers.views.api_sites` with a specified :py:c... | stack_v2_sparse_classes_36k_train_010670 | 5,689 | no_license | [
{
"docstring": "Unit test for :py:func:`papers.views.api_sites` with no paper specified.",
"name": "test_all",
"signature": "def test_all(self)"
},
{
"docstring": "Unit test for :py:func:`papers.views.api_sites` with a specified :py:class:`papers.models.NewsPaper` name.",
"name": "test_paper... | 2 | null | Implement the Python class `api_sites_TestCase` described below.
Class description:
Unit tests for api/sites/ URLs.
Method signatures and docstrings:
- def test_all(self): Unit test for :py:func:`papers.views.api_sites` with no paper specified.
- def test_paper(self): Unit test for :py:func:`papers.views.api_sites` w... | Implement the Python class `api_sites_TestCase` described below.
Class description:
Unit tests for api/sites/ URLs.
Method signatures and docstrings:
- def test_all(self): Unit test for :py:func:`papers.views.api_sites` with no paper specified.
- def test_paper(self): Unit test for :py:func:`papers.views.api_sites` w... | cd4238a0c27bfc5a4f487d68e6c756035e053203 | <|skeleton|>
class api_sites_TestCase:
"""Unit tests for api/sites/ URLs."""
def test_all(self):
"""Unit test for :py:func:`papers.views.api_sites` with no paper specified."""
<|body_0|>
def test_paper(self):
"""Unit test for :py:func:`papers.views.api_sites` with a specified :py:c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class api_sites_TestCase:
"""Unit tests for api/sites/ URLs."""
def test_all(self):
"""Unit test for :py:func:`papers.views.api_sites` with no paper specified."""
request = make_wsgi_request('sites/')
response = views.api_sites(request)
results = json.loads(response.content.deco... | the_stack_v2_python_sparse | papers/test_views.py | alflanagan/utl_lookup | train | 0 |
e1f9a97d2ec1f236e39a894dd63ec7f9c3c3173a | [
"self.time_lapse_polygons = time_lapse_polygons\nself.raster_template = raster_template\nself.facility_id = facility_id\nself.from_break = from_break\nself.to_break = to_break\nself.scratch_folder = scratch_folder\nself._create_job_folder()\nself.scratch_gdb = None\nself.setup_logger('PercAccPoly')\nself.job_result... | <|body_start_0|>
self.time_lapse_polygons = time_lapse_polygons
self.raster_template = raster_template
self.facility_id = facility_id
self.from_break = from_break
self.to_break = to_break
self.scratch_folder = scratch_folder
self._create_job_folder()
self.... | Calculate percent access polygons for the designated facility, from break, to break combo. | ParallelCounter | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParallelCounter:
"""Calculate percent access polygons for the designated facility, from break, to break combo."""
def __init__(self, time_lapse_polygons, raster_template, facility_id, from_break, to_break, scratch_folder):
"""Initialize the parallel counter for the given inputs. Args... | stack_v2_sparse_classes_36k_train_010671 | 14,182 | permissive | [
{
"docstring": "Initialize the parallel counter for the given inputs. Args: time_lapse_polygons (feature class catalog path): Time lapse polygons raster_template (feature class catalog path): Raster-like polygons template facility_id (int): ID of the Service Area facility to select for processing this chunk fro... | 5 | stack_v2_sparse_classes_30k_train_021551 | Implement the Python class `ParallelCounter` described below.
Class description:
Calculate percent access polygons for the designated facility, from break, to break combo.
Method signatures and docstrings:
- def __init__(self, time_lapse_polygons, raster_template, facility_id, from_break, to_break, scratch_folder): I... | Implement the Python class `ParallelCounter` described below.
Class description:
Calculate percent access polygons for the designated facility, from break, to break combo.
Method signatures and docstrings:
- def __init__(self, time_lapse_polygons, raster_template, facility_id, from_break, to_break, scratch_folder): I... | 47cbc3de67a7b1bf9255e07e88cba7b051db0505 | <|skeleton|>
class ParallelCounter:
"""Calculate percent access polygons for the designated facility, from break, to break combo."""
def __init__(self, time_lapse_polygons, raster_template, facility_id, from_break, to_break, scratch_folder):
"""Initialize the parallel counter for the given inputs. Args... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParallelCounter:
"""Calculate percent access polygons for the designated facility, from break, to break combo."""
def __init__(self, time_lapse_polygons, raster_template, facility_id, from_break, to_break, scratch_folder):
"""Initialize the parallel counter for the given inputs. Args: time_lapse_... | the_stack_v2_python_sparse | transit-network-analysis-tools/parallel_cpap.py | Esri/public-transit-tools | train | 155 |
fba66e210888bb8b0bc12dad9fd7b36b63ac85e3 | [
"self.epoch = 1\nself.alpha = alpha\nself.vae = vae\nself.vae_loss = vae_loss\nself.path = path",
"stable = 10\nnew_alpha = 0.0001\nif self.epoch > stable and K.get_value(self.alpha) > 1e-08:\n new_alpha = K.get_value(self.alpha) / 2\n K.set_value(self.alpha, new_alpha)\n self.vae.compile('adam', loss=se... | <|body_start_0|>
self.epoch = 1
self.alpha = alpha
self.vae = vae
self.vae_loss = vae_loss
self.path = path
<|end_body_0|>
<|body_start_1|>
stable = 10
new_alpha = 0.0001
if self.epoch > stable and K.get_value(self.alpha) > 1e-08:
new_alpha = ... | changeAlpha | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class changeAlpha:
def __init__(self, alpha, vae, vae_loss, path):
"""Initialization function epoch: epoch number, initialized at 1 alpha: value of the KL coefficient vae: network trained vae_loss: loss used to train the vae path: savepath for the value of alpha"""
<|body_0|>
def ... | stack_v2_sparse_classes_36k_train_010672 | 2,836 | permissive | [
{
"docstring": "Initialization function epoch: epoch number, initialized at 1 alpha: value of the KL coefficient vae: network trained vae_loss: loss used to train the vae path: savepath for the value of alpha",
"name": "__init__",
"signature": "def __init__(self, alpha, vae, vae_loss, path)"
},
{
... | 2 | stack_v2_sparse_classes_30k_val_001006 | Implement the Python class `changeAlpha` described below.
Class description:
Implement the changeAlpha class.
Method signatures and docstrings:
- def __init__(self, alpha, vae, vae_loss, path): Initialization function epoch: epoch number, initialized at 1 alpha: value of the KL coefficient vae: network trained vae_lo... | Implement the Python class `changeAlpha` described below.
Class description:
Implement the changeAlpha class.
Method signatures and docstrings:
- def __init__(self, alpha, vae, vae_loss, path): Initialization function epoch: epoch number, initialized at 1 alpha: value of the KL coefficient vae: network trained vae_lo... | f1c0c965de72eb182478527f00ac4cdfde07fe25 | <|skeleton|>
class changeAlpha:
def __init__(self, alpha, vae, vae_loss, path):
"""Initialization function epoch: epoch number, initialized at 1 alpha: value of the KL coefficient vae: network trained vae_loss: loss used to train the vae path: savepath for the value of alpha"""
<|body_0|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class changeAlpha:
def __init__(self, alpha, vae, vae_loss, path):
"""Initialization function epoch: epoch number, initialized at 1 alpha: value of the KL coefficient vae: network trained vae_loss: loss used to train the vae path: savepath for the value of alpha"""
self.epoch = 1
self.alpha ... | the_stack_v2_python_sparse | scripts/tools_for_VAE/tools_for_VAE/callbacks.py | LSSTDESC/DeblenderVAE | train | 5 | |
4f236bcb1c4a1071c549ac271fb7184ebb8bea5a | [
"if len(milestones) != len(sizes) - 1:\n raise TypeError('Sizes must include initial size and thus has one element more than miltstones.')\nself.targets = sorted(zip((0, *milestones), sizes), key=lambda x: x[0], reverse=True)",
"for t in self.targets:\n if step >= t[0]:\n return t[1]\nreturn self.tar... | <|body_start_0|>
if len(milestones) != len(sizes) - 1:
raise TypeError('Sizes must include initial size and thus has one element more than miltstones.')
self.targets = sorted(zip((0, *milestones), sizes), key=lambda x: x[0], reverse=True)
<|end_body_0|>
<|body_start_1|>
for t in sel... | Scheduler return size when milestone is reached | SizeStepScheduler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SizeStepScheduler:
"""Scheduler return size when milestone is reached"""
def __init__(self, milestones: Sequence[int], sizes: Union[Sequence[int], Sequence[Sequence[int]]]):
"""Args: milestones: contains number of iterations where size should be changed sizes: sizes corresponding to ... | stack_v2_sparse_classes_36k_train_010673 | 11,105 | permissive | [
{
"docstring": "Args: milestones: contains number of iterations where size should be changed sizes: sizes corresponding to milestones",
"name": "__init__",
"signature": "def __init__(self, milestones: Sequence[int], sizes: Union[Sequence[int], Sequence[Sequence[int]]])"
},
{
"docstring": "Return... | 2 | stack_v2_sparse_classes_30k_train_008108 | Implement the Python class `SizeStepScheduler` described below.
Class description:
Scheduler return size when milestone is reached
Method signatures and docstrings:
- def __init__(self, milestones: Sequence[int], sizes: Union[Sequence[int], Sequence[Sequence[int]]]): Args: milestones: contains number of iterations wh... | Implement the Python class `SizeStepScheduler` described below.
Class description:
Scheduler return size when milestone is reached
Method signatures and docstrings:
- def __init__(self, milestones: Sequence[int], sizes: Union[Sequence[int], Sequence[Sequence[int]]]): Args: milestones: contains number of iterations wh... | ab6fbcfe7215c2a5b8e401b70909f6a32d0d167b | <|skeleton|>
class SizeStepScheduler:
"""Scheduler return size when milestone is reached"""
def __init__(self, milestones: Sequence[int], sizes: Union[Sequence[int], Sequence[Sequence[int]]]):
"""Args: milestones: contains number of iterations where size should be changed sizes: sizes corresponding to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SizeStepScheduler:
"""Scheduler return size when milestone is reached"""
def __init__(self, milestones: Sequence[int], sizes: Union[Sequence[int], Sequence[Sequence[int]]]):
"""Args: milestones: contains number of iterations where size should be changed sizes: sizes corresponding to milestones"""... | the_stack_v2_python_sparse | rising/transforms/spatial.py | PhoenixDL/rising | train | 318 |
b1b5cd1433c2470b4c6d250b63a9930f45d62d02 | [
"request = RequestOptions(query.url)\nrequest.method = HttpMethod.Post\nrequest.ensure_header('Content-Type', 'application/json')\nrequest.ensure_header('Accept', 'application/json')\nrequest.data = self._prepare_payload(query)\nreturn request",
"for sub_qry, sub_resp in self._extract_response(response, query):\n... | <|body_start_0|>
request = RequestOptions(query.url)
request.method = HttpMethod.Post
request.ensure_header('Content-Type', 'application/json')
request.ensure_header('Accept', 'application/json')
request.data = self._prepare_payload(query)
return request
<|end_body_0|>
<... | JSON batch request | ODataV4BatchRequest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ODataV4BatchRequest:
"""JSON batch request"""
def build_request(self, query):
"""Builds a batch request :type query: office365.runtime.queries.batch.BatchQuery"""
<|body_0|>
def process_response(self, response, query):
"""Parses an HTTP response. :type response: ... | stack_v2_sparse_classes_36k_train_010674 | 2,930 | permissive | [
{
"docstring": "Builds a batch request :type query: office365.runtime.queries.batch.BatchQuery",
"name": "build_request",
"signature": "def build_request(self, query)"
},
{
"docstring": "Parses an HTTP response. :type response: requests.Response :type query: office365.runtime.queries.batch.Batch... | 5 | stack_v2_sparse_classes_30k_train_001569 | Implement the Python class `ODataV4BatchRequest` described below.
Class description:
JSON batch request
Method signatures and docstrings:
- def build_request(self, query): Builds a batch request :type query: office365.runtime.queries.batch.BatchQuery
- def process_response(self, response, query): Parses an HTTP respo... | Implement the Python class `ODataV4BatchRequest` described below.
Class description:
JSON batch request
Method signatures and docstrings:
- def build_request(self, query): Builds a batch request :type query: office365.runtime.queries.batch.BatchQuery
- def process_response(self, response, query): Parses an HTTP respo... | cbd245d1af8d69e013c469cfc2a9851f51c91417 | <|skeleton|>
class ODataV4BatchRequest:
"""JSON batch request"""
def build_request(self, query):
"""Builds a batch request :type query: office365.runtime.queries.batch.BatchQuery"""
<|body_0|>
def process_response(self, response, query):
"""Parses an HTTP response. :type response: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ODataV4BatchRequest:
"""JSON batch request"""
def build_request(self, query):
"""Builds a batch request :type query: office365.runtime.queries.batch.BatchQuery"""
request = RequestOptions(query.url)
request.method = HttpMethod.Post
request.ensure_header('Content-Type', 'ap... | the_stack_v2_python_sparse | office365/runtime/odata/v4/batch_request.py | vgrem/Office365-REST-Python-Client | train | 1,006 |
cddb41a9ce7c3c418e15b9d610dd649c1cd961e7 | [
"study_id = filter_params.pop('study_id', None)\nparticipant_id = filter_params.pop('participant_id', None)\nq = FamilyRelationship.query_all_relationships(participant_kf_id=participant_id, model_filter_params=filter_params)\nif study_id:\n from dataservice.api.participant.models import Participant\n q = q.fi... | <|body_start_0|>
study_id = filter_params.pop('study_id', None)
participant_id = filter_params.pop('participant_id', None)
q = FamilyRelationship.query_all_relationships(participant_kf_id=participant_id, model_filter_params=filter_params)
if study_id:
from dataservice.api.par... | FamilyRelationship REST API | FamilyRelationshipListAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FamilyRelationshipListAPI:
"""FamilyRelationship REST API"""
def get(self, filter_params, after, limit):
"""Get all family_relationships --- description: Get all family_relationships template: path: get_list.yml properties: resource: FamilyRelationship"""
<|body_0|>
def ... | stack_v2_sparse_classes_36k_train_010675 | 5,385 | permissive | [
{
"docstring": "Get all family_relationships --- description: Get all family_relationships template: path: get_list.yml properties: resource: FamilyRelationship",
"name": "get",
"signature": "def get(self, filter_params, after, limit)"
},
{
"docstring": "Create a new family_relationship --- temp... | 2 | null | Implement the Python class `FamilyRelationshipListAPI` described below.
Class description:
FamilyRelationship REST API
Method signatures and docstrings:
- def get(self, filter_params, after, limit): Get all family_relationships --- description: Get all family_relationships template: path: get_list.yml properties: res... | Implement the Python class `FamilyRelationshipListAPI` described below.
Class description:
FamilyRelationship REST API
Method signatures and docstrings:
- def get(self, filter_params, after, limit): Get all family_relationships --- description: Get all family_relationships template: path: get_list.yml properties: res... | 36ee3fc3d1ba9d1a177274d051fb175c56dd898e | <|skeleton|>
class FamilyRelationshipListAPI:
"""FamilyRelationship REST API"""
def get(self, filter_params, after, limit):
"""Get all family_relationships --- description: Get all family_relationships template: path: get_list.yml properties: resource: FamilyRelationship"""
<|body_0|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FamilyRelationshipListAPI:
"""FamilyRelationship REST API"""
def get(self, filter_params, after, limit):
"""Get all family_relationships --- description: Get all family_relationships template: path: get_list.yml properties: resource: FamilyRelationship"""
study_id = filter_params.pop('stu... | the_stack_v2_python_sparse | dataservice/api/family_relationship/resources.py | kids-first/kf-api-dataservice | train | 9 |
f18f4b2be7baa4f301be37cba5854acbb61f5478 | [
"table = self.table = {}\nfor i, word in enumerate(words):\n table[word] = table[word] + [i] if word in table else [i]",
"p1 = 0\np2 = 0\nres = 2 ** 31 - 1\nlst1 = self.table[word1]\nlst2 = self.table[word2]\nwhile p1 < len(lst1) and p2 < len(lst2):\n res = min(res, abs(lst1[p1] - lst2[p2]))\n if lst1[p1... | <|body_start_0|>
table = self.table = {}
for i, word in enumerate(words):
table[word] = table[word] + [i] if word in table else [i]
<|end_body_0|>
<|body_start_1|>
p1 = 0
p2 = 0
res = 2 ** 31 - 1
lst1 = self.table[word1]
lst2 = self.table[word2]
... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_010676 | 1,825 | no_license | [
{
"docstring": "initialize your data structure here. :type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": "Adds a word into the data structure. :type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortes... | 2 | null | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | a041962eeab9192799ad7f74b4bbd3e4f74933d0 | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
table = self.table = {}
for i, word in enumerate(words):
table[word] = table[word] + [i] if word in table else [i]
def shortest(self, word1, word2):
"""Ad... | the_stack_v2_python_sparse | codes/244. Shortest Word Distance II.py | zcgu/leetcode | train | 1 | |
13e0c372fb6ae46c74b95fde7d92b4e96178cb9f | [
"day, month, year = str_date.split('.')\nDate.day = int(day)\nDate.month = int(month)\nDate.year = int(year)",
"if scale.lower() == 'day':\n result = Date.day\nelif scale.lower() == 'month':\n result = Date.month\nelif scale.lower() == 'year':\n result = Date.year\nelse:\n result = -1\nreturn result",... | <|body_start_0|>
day, month, year = str_date.split('.')
Date.day = int(day)
Date.month = int(month)
Date.year = int(year)
<|end_body_0|>
<|body_start_1|>
if scale.lower() == 'day':
result = Date.day
elif scale.lower() == 'month':
result = Date.mon... | Класс дата нашей эры (видимо ээто будет синглтон) | Date | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Date:
"""Класс дата нашей эры (видимо ээто будет синглтон)"""
def __init__(self, str_date):
"""делаем из строки числа и заводим свойства класа :param str_date: сторка с датой"""
<|body_0|>
def to_int(cls, scale):
"""перевод шкалы в int :param scale: шкала интовое... | stack_v2_sparse_classes_36k_train_010677 | 2,341 | no_license | [
{
"docstring": "делаем из строки числа и заводим свойства класа :param str_date: сторка с датой",
"name": "__init__",
"signature": "def __init__(self, str_date)"
},
{
"docstring": "перевод шкалы в int :param scale: шкала интовое значение которой хотим получить :return: щкала привденая в int",
... | 3 | stack_v2_sparse_classes_30k_train_005128 | Implement the Python class `Date` described below.
Class description:
Класс дата нашей эры (видимо ээто будет синглтон)
Method signatures and docstrings:
- def __init__(self, str_date): делаем из строки числа и заводим свойства класа :param str_date: сторка с датой
- def to_int(cls, scale): перевод шкалы в int :param... | Implement the Python class `Date` described below.
Class description:
Класс дата нашей эры (видимо ээто будет синглтон)
Method signatures and docstrings:
- def __init__(self, str_date): делаем из строки числа и заводим свойства класа :param str_date: сторка с датой
- def to_int(cls, scale): перевод шкалы в int :param... | 57c79f021606453de2c2626deb9ec48720927b36 | <|skeleton|>
class Date:
"""Класс дата нашей эры (видимо ээто будет синглтон)"""
def __init__(self, str_date):
"""делаем из строки числа и заводим свойства класа :param str_date: сторка с датой"""
<|body_0|>
def to_int(cls, scale):
"""перевод шкалы в int :param scale: шкала интовое... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Date:
"""Класс дата нашей эры (видимо ээто будет синглтон)"""
def __init__(self, str_date):
"""делаем из строки числа и заводим свойства класа :param str_date: сторка с датой"""
day, month, year = str_date.split('.')
Date.day = int(day)
Date.month = int(month)
Date... | the_stack_v2_python_sparse | lessons/lesson8/lesson8_1.py | Alexidis/python_basics | train | 0 |
eec45e2f079cf9cee3b69e75401bc71597575f0c | [
"available_taxon_slugs: List[str] = []\nfor attr in attributes:\n available_taxon_slugs.extend(attr.field_map)\nreturn available_taxon_slugs",
"if 'attributes' in values:\n attributes: List[FdqModelAttribute] = values['attributes']\n taxon_slugs = cls._get_available_attrs_taxon_slugs(attributes)\n tax... | <|body_start_0|>
available_taxon_slugs: List[str] = []
for attr in attributes:
available_taxon_slugs.extend(attr.field_map)
return available_taxon_slugs
<|end_body_0|>
<|body_start_1|>
if 'attributes' in values:
attributes: List[FdqModelAttribute] = values['attri... | FdqModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FdqModel:
def _get_available_attrs_taxon_slugs(cls, attributes: List[FdqModelAttribute]) -> List[str]:
"""Gets list of available taxon slugs for given attributes"""
<|body_0|>
def validate_unique_taxon_slugs(cls, values):
"""Validate that each taxon slug is used at m... | stack_v2_sparse_classes_36k_train_010678 | 8,280 | permissive | [
{
"docstring": "Gets list of available taxon slugs for given attributes",
"name": "_get_available_attrs_taxon_slugs",
"signature": "def _get_available_attrs_taxon_slugs(cls, attributes: List[FdqModelAttribute]) -> List[str]"
},
{
"docstring": "Validate that each taxon slug is used at most once i... | 5 | stack_v2_sparse_classes_30k_train_009910 | Implement the Python class `FdqModel` described below.
Class description:
Implement the FdqModel class.
Method signatures and docstrings:
- def _get_available_attrs_taxon_slugs(cls, attributes: List[FdqModelAttribute]) -> List[str]: Gets list of available taxon slugs for given attributes
- def validate_unique_taxon_s... | Implement the Python class `FdqModel` described below.
Class description:
Implement the FdqModel class.
Method signatures and docstrings:
- def _get_available_attrs_taxon_slugs(cls, attributes: List[FdqModelAttribute]) -> List[str]: Gets list of available taxon slugs for given attributes
- def validate_unique_taxon_s... | 210f037280793d5cb3b6d9d3e7ba3e22ca9b8bbc | <|skeleton|>
class FdqModel:
def _get_available_attrs_taxon_slugs(cls, attributes: List[FdqModelAttribute]) -> List[str]:
"""Gets list of available taxon slugs for given attributes"""
<|body_0|>
def validate_unique_taxon_slugs(cls, values):
"""Validate that each taxon slug is used at m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FdqModel:
def _get_available_attrs_taxon_slugs(cls, attributes: List[FdqModelAttribute]) -> List[str]:
"""Gets list of available taxon slugs for given attributes"""
available_taxon_slugs: List[str] = []
for attr in attributes:
available_taxon_slugs.extend(attr.field_map)
... | the_stack_v2_python_sparse | src/panoramic/cli/husky/core/federated/model/models.py | panoramichq/panoramic-cli | train | 5 | |
b6aa73e7a5fd0259e5719a364a4a913122f6d1ac | [
"if 'surname' in request.params:\n redirect(url('now_name', surname=request.params['surname']))\nelse:\n return render('now/index.xml')",
"schedule = [time(7, 55), time(8, 55), time(10, 0), time(10, 55), time(12, 0), time(12, 55), time(13, 50), time(14, 45)]\nnow = datetime.now().time()\nif now < schedule[0... | <|body_start_0|>
if 'surname' in request.params:
redirect(url('now_name', surname=request.params['surname']))
else:
return render('now/index.xml')
<|end_body_0|>
<|body_start_1|>
schedule = [time(7, 55), time(8, 55), time(10, 0), time(10, 55), time(12, 0), time(12, 55), ... | NowController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NowController:
def index(self):
"""Render index page or redirect to now or now_id actions if surname is available in the request's params."""
<|body_0|>
def current_order(self):
"""Return the current lesson order."""
<|body_1|>
def now(self, surname):
... | stack_v2_sparse_classes_36k_train_010679 | 2,786 | no_license | [
{
"docstring": "Render index page or redirect to now or now_id actions if surname is available in the request's params.",
"name": "index",
"signature": "def index(self)"
},
{
"docstring": "Return the current lesson order.",
"name": "current_order",
"signature": "def current_order(self)"
... | 4 | stack_v2_sparse_classes_30k_train_017826 | Implement the Python class `NowController` described below.
Class description:
Implement the NowController class.
Method signatures and docstrings:
- def index(self): Render index page or redirect to now or now_id actions if surname is available in the request's params.
- def current_order(self): Return the current l... | Implement the Python class `NowController` described below.
Class description:
Implement the NowController class.
Method signatures and docstrings:
- def index(self): Render index page or redirect to now or now_id actions if surname is available in the request's params.
- def current_order(self): Return the current l... | 327ef2fd4f65db471c408a26095439630c53139e | <|skeleton|>
class NowController:
def index(self):
"""Render index page or redirect to now or now_id actions if surname is available in the request's params."""
<|body_0|>
def current_order(self):
"""Return the current lesson order."""
<|body_1|>
def now(self, surname):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NowController:
def index(self):
"""Render index page or redirect to now or now_id actions if surname is available in the request's params."""
if 'surname' in request.params:
redirect(url('now_name', surname=request.params['surname']))
else:
return render('now/in... | the_stack_v2_python_sparse | sis/controllers/now.py | kuba/SIS | train | 0 | |
73e477ed7b980d5707c1f21b4e08c4bf66ac31a8 | [
"super(Application, self).__init__(master)\nself.grid()\nself.create_widgets()",
"Label(self, text='Charecter creation params:').grid(row=0, column=0, columnspan=2, sticky=W)\nLabel(self, text='Name: ').grid(row=1, column=0, sticky=W)\nself.person_ent = Entry(self)\nself.person_ent.grid(row=1, column=1, sticky=W)... | <|body_start_0|>
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
<|end_body_0|>
<|body_start_1|>
Label(self, text='Charecter creation params:').grid(row=0, column=0, columnspan=2, sticky=W)
Label(self, text='Name: ').grid(row=1, column=0, sticky=W)
... | GUI app that generates a story based on user inputs | Application | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""GUI app that generates a story based on user inputs"""
def __init__(self, master):
"""Frame initiation"""
<|body_0|>
def create_widgets(self):
"""generates controls"""
<|body_1|>
def tell_story(self):
"""put generated story in... | stack_v2_sparse_classes_36k_train_010680 | 4,235 | no_license | [
{
"docstring": "Frame initiation",
"name": "__init__",
"signature": "def __init__(self, master)"
},
{
"docstring": "generates controls",
"name": "create_widgets",
"signature": "def create_widgets(self)"
},
{
"docstring": "put generated story into text area",
"name": "tell_sto... | 3 | stack_v2_sparse_classes_30k_val_000610 | Implement the Python class `Application` described below.
Class description:
GUI app that generates a story based on user inputs
Method signatures and docstrings:
- def __init__(self, master): Frame initiation
- def create_widgets(self): generates controls
- def tell_story(self): put generated story into text area | Implement the Python class `Application` described below.
Class description:
GUI app that generates a story based on user inputs
Method signatures and docstrings:
- def __init__(self, master): Frame initiation
- def create_widgets(self): generates controls
- def tell_story(self): put generated story into text area
<... | 19343c985f368770dc01ce415506506d62a23285 | <|skeleton|>
class Application:
"""GUI app that generates a story based on user inputs"""
def __init__(self, master):
"""Frame initiation"""
<|body_0|>
def create_widgets(self):
"""generates controls"""
<|body_1|>
def tell_story(self):
"""put generated story in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Application:
"""GUI app that generates a story based on user inputs"""
def __init__(self, master):
"""Frame initiation"""
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
"""generates controls"""
Lab... | the_stack_v2_python_sparse | gui/mad_lib.py | gofr1/python-learning | train | 0 |
8bcd795a9f88132501d8b487be49fe075728c5c6 | [
"if not flags.FLAGS.is_parsed():\n flags.FLAGS.mark_as_parsed()\nself.fake_data_dir = os.path.join(platforms_util.get_test_data_dir(), 'fake_tf_record_data')\nself.output_dir = output_dir\nif root_data_dir is None:\n self.data_dir = '/readahead/200M/placer/prod/home/distbelief/imagenet-tensorflow/imagenet-201... | <|body_start_0|>
if not flags.FLAGS.is_parsed():
flags.FLAGS.mark_as_parsed()
self.fake_data_dir = os.path.join(platforms_util.get_test_data_dir(), 'fake_tf_record_data')
self.output_dir = output_dir
if root_data_dir is None:
self.data_dir = '/readahead/200M/place... | Base class for all benchmarks in this file. | BenchmarkBase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BenchmarkBase:
"""Base class for all benchmarks in this file."""
def __init__(self, output_dir=None, root_data_dir=None, **kwargs):
"""Base class for all benchmarks in this file. Args: output_dir: directory where to output e.g. log files root_data_dir: directory under which to look f... | stack_v2_sparse_classes_36k_train_010681 | 36,235 | permissive | [
{
"docstring": "Base class for all benchmarks in this file. Args: output_dir: directory where to output e.g. log files root_data_dir: directory under which to look for dataset **kwargs: arbitrary named arguments. This is needed to make the constructor forward compatible in case PerfZero provides more named argu... | 4 | stack_v2_sparse_classes_30k_train_005553 | Implement the Python class `BenchmarkBase` described below.
Class description:
Base class for all benchmarks in this file.
Method signatures and docstrings:
- def __init__(self, output_dir=None, root_data_dir=None, **kwargs): Base class for all benchmarks in this file. Args: output_dir: directory where to output e.g.... | Implement the Python class `BenchmarkBase` described below.
Class description:
Base class for all benchmarks in this file.
Method signatures and docstrings:
- def __init__(self, output_dir=None, root_data_dir=None, **kwargs): Base class for all benchmarks in this file. Args: output_dir: directory where to output e.g.... | c8e97df0d4d3d0c1020b98391c526df12371fc30 | <|skeleton|>
class BenchmarkBase:
"""Base class for all benchmarks in this file."""
def __init__(self, output_dir=None, root_data_dir=None, **kwargs):
"""Base class for all benchmarks in this file. Args: output_dir: directory where to output e.g. log files root_data_dir: directory under which to look f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BenchmarkBase:
"""Base class for all benchmarks in this file."""
def __init__(self, output_dir=None, root_data_dir=None, **kwargs):
"""Base class for all benchmarks in this file. Args: output_dir: directory where to output e.g. log files root_data_dir: directory under which to look for dataset **... | the_stack_v2_python_sparse | scripts/tf_cnn_benchmarks/leading_indicators_test.py | tensorflow/benchmarks | train | 1,182 |
0e65042051c5a071ff6c8e970b53355aca94820c | [
"self._attr_supported_features = SirenEntityFeature.TURN_ON | SirenEntityFeature.TURN_OFF | SirenEntityFeature.DURATION | SirenEntityFeature.VOLUME_SET | SirenEntityFeature.TONES\nself._attr_available_tones: list[int | str] | dict[int, str] | None = {WARNING_DEVICE_MODE_BURGLAR: 'Burglar', WARNING_DEVICE_MODE_FIRE:... | <|body_start_0|>
self._attr_supported_features = SirenEntityFeature.TURN_ON | SirenEntityFeature.TURN_OFF | SirenEntityFeature.DURATION | SirenEntityFeature.VOLUME_SET | SirenEntityFeature.TONES
self._attr_available_tones: list[int | str] | dict[int, str] | None = {WARNING_DEVICE_MODE_BURGLAR: 'Burglar'... | Representation of a ZHA siren. | ZHASiren | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZHASiren:
"""Representation of a ZHA siren."""
def __init__(self, unique_id: str, zha_device: ZHADevice, cluster_handlers: list[ClusterHandler], **kwargs) -> None:
"""Init this siren."""
<|body_0|>
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn on ... | stack_v2_sparse_classes_36k_train_010682 | 5,956 | permissive | [
{
"docstring": "Init this siren.",
"name": "__init__",
"signature": "def __init__(self, unique_id: str, zha_device: ZHADevice, cluster_handlers: list[ClusterHandler], **kwargs) -> None"
},
{
"docstring": "Turn on siren.",
"name": "async_turn_on",
"signature": "async def async_turn_on(sel... | 4 | null | Implement the Python class `ZHASiren` described below.
Class description:
Representation of a ZHA siren.
Method signatures and docstrings:
- def __init__(self, unique_id: str, zha_device: ZHADevice, cluster_handlers: list[ClusterHandler], **kwargs) -> None: Init this siren.
- async def async_turn_on(self, **kwargs: A... | Implement the Python class `ZHASiren` described below.
Class description:
Representation of a ZHA siren.
Method signatures and docstrings:
- def __init__(self, unique_id: str, zha_device: ZHADevice, cluster_handlers: list[ClusterHandler], **kwargs) -> None: Init this siren.
- async def async_turn_on(self, **kwargs: A... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ZHASiren:
"""Representation of a ZHA siren."""
def __init__(self, unique_id: str, zha_device: ZHADevice, cluster_handlers: list[ClusterHandler], **kwargs) -> None:
"""Init this siren."""
<|body_0|>
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn on ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZHASiren:
"""Representation of a ZHA siren."""
def __init__(self, unique_id: str, zha_device: ZHADevice, cluster_handlers: list[ClusterHandler], **kwargs) -> None:
"""Init this siren."""
self._attr_supported_features = SirenEntityFeature.TURN_ON | SirenEntityFeature.TURN_OFF | SirenEntity... | the_stack_v2_python_sparse | homeassistant/components/zha/siren.py | home-assistant/core | train | 35,501 |
73369719d1b6e81c208100fbf27cd79de9ab5fdf | [
"if isinstance(key, int):\n return Routing(key)\nif key not in Routing._member_map_:\n extend_enum(Routing, key, default)\nreturn Routing[key]",
"if not (isinstance(value, int) and 0 <= value <= 255):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nif 5 <= value <= 252:\n extend_en... | <|body_start_0|>
if isinstance(key, int):
return Routing(key)
if key not in Routing._member_map_:
extend_enum(Routing, key, default)
return Routing[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <= value <= 255):
raise Value... | [Routing] IPv6 Routing Types | Routing | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Routing:
"""[Routing] IPv6 Routing Types"""
def get(key, default=-1):
"""Backport support for original codes."""
<|body_0|>
def _missing_(cls, value):
"""Lookup function used when value is not found."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_010683 | 1,523 | permissive | [
{
"docstring": "Backport support for original codes.",
"name": "get",
"signature": "def get(key, default=-1)"
},
{
"docstring": "Lookup function used when value is not found.",
"name": "_missing_",
"signature": "def _missing_(cls, value)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000704 | Implement the Python class `Routing` described below.
Class description:
[Routing] IPv6 Routing Types
Method signatures and docstrings:
- def get(key, default=-1): Backport support for original codes.
- def _missing_(cls, value): Lookup function used when value is not found. | Implement the Python class `Routing` described below.
Class description:
[Routing] IPv6 Routing Types
Method signatures and docstrings:
- def get(key, default=-1): Backport support for original codes.
- def _missing_(cls, value): Lookup function used when value is not found.
<|skeleton|>
class Routing:
"""[Routi... | 90cd07d67df28d5c5ab0585bc60f467a78d9db33 | <|skeleton|>
class Routing:
"""[Routing] IPv6 Routing Types"""
def get(key, default=-1):
"""Backport support for original codes."""
<|body_0|>
def _missing_(cls, value):
"""Lookup function used when value is not found."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Routing:
"""[Routing] IPv6 Routing Types"""
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Routing(key)
if key not in Routing._member_map_:
extend_enum(Routing, key, default)
return Routing[key]
... | the_stack_v2_python_sparse | pcapkit/const/ipv6/routing.py | stjordanis/PyPCAPKit | train | 0 |
8bc3656021dd7152f460937bec6cd225d2611d69 | [
"super(MixedParameterTests, self).setUp()\nself.p_On = [self.constructor(Name='d', Prefix='-', Value=True), self.constructor(Name='d', Prefix='-', Value=5), self.constructor(Name='d', Prefix='-', Value=[1]), self.constructor(Name='d', Prefix='-', Value=None), self.constructor(Name='d', Prefix='-', Value='F')]\nself... | <|body_start_0|>
super(MixedParameterTests, self).setUp()
self.p_On = [self.constructor(Name='d', Prefix='-', Value=True), self.constructor(Name='d', Prefix='-', Value=5), self.constructor(Name='d', Prefix='-', Value=[1]), self.constructor(Name='d', Prefix='-', Value=None), self.constructor(Name='d', Pr... | Tests of the MixedParameter class | MixedParameterTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MixedParameterTests:
"""Tests of the MixedParameter class"""
def setUp(self):
"""Setup some variables for the tests to use"""
<|body_0|>
def test_on(self):
"""Parameter: on functions as expected"""
<|body_1|>
def test_init_defaults(self):
"""... | stack_v2_sparse_classes_36k_train_010684 | 20,121 | no_license | [
{
"docstring": "Setup some variables for the tests to use",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Parameter: on functions as expected",
"name": "test_on",
"signature": "def test_on(self)"
},
{
"docstring": "MixedParameter: init functions as expected w... | 4 | null | Implement the Python class `MixedParameterTests` described below.
Class description:
Tests of the MixedParameter class
Method signatures and docstrings:
- def setUp(self): Setup some variables for the tests to use
- def test_on(self): Parameter: on functions as expected
- def test_init_defaults(self): MixedParameter:... | Implement the Python class `MixedParameterTests` described below.
Class description:
Tests of the MixedParameter class
Method signatures and docstrings:
- def setUp(self): Setup some variables for the tests to use
- def test_on(self): Parameter: on functions as expected
- def test_init_defaults(self): MixedParameter:... | b49442bd793a743188a43809903dc140512420b7 | <|skeleton|>
class MixedParameterTests:
"""Tests of the MixedParameter class"""
def setUp(self):
"""Setup some variables for the tests to use"""
<|body_0|>
def test_on(self):
"""Parameter: on functions as expected"""
<|body_1|>
def test_init_defaults(self):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MixedParameterTests:
"""Tests of the MixedParameter class"""
def setUp(self):
"""Setup some variables for the tests to use"""
super(MixedParameterTests, self).setUp()
self.p_On = [self.constructor(Name='d', Prefix='-', Value=True), self.constructor(Name='d', Prefix='-', Value=5), ... | the_stack_v2_python_sparse | old_cogent_tests/app/test_parameters.py | pycogent/old-cogent | train | 0 |
3e1d29d71c2db6d45a617bc416102f1aab1d0e00 | [
"self.__url = Config.EPSG_URL\nself.__log = log\nself.fileName = fileName\nself.prjFileName = None\nself.spatialReferenceWKT = None\nself.spatialReferenceEPSG = None\nself.response = None\nself.jsondata = None",
"try:\n code = 0\n file_name_no_extension = os.path.splitext(self.fileName)[0]\n self.prjFile... | <|body_start_0|>
self.__url = Config.EPSG_URL
self.__log = log
self.fileName = fileName
self.prjFileName = None
self.spatialReferenceWKT = None
self.spatialReferenceEPSG = None
self.response = None
self.jsondata = None
<|end_body_0|>
<|body_start_1|>
... | API for get the spatial geospatial reference for given EPSG | SpatialReference | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpatialReference:
"""API for get the spatial geospatial reference for given EPSG"""
def __init__(self, log, fileName):
"""Constructor :param log: logger object :param filename: Work file name"""
<|body_0|>
def checkSpatialReference(self):
"""Obtain EPSG and WKT f... | stack_v2_sparse_classes_36k_train_010685 | 7,773 | permissive | [
{
"docstring": "Constructor :param log: logger object :param filename: Work file name",
"name": "__init__",
"signature": "def __init__(self, log, fileName)"
},
{
"docstring": "Obtain EPSG and WKT from prj file :returns:Status Result",
"name": "checkSpatialReference",
"signature": "def ch... | 5 | null | Implement the Python class `SpatialReference` described below.
Class description:
API for get the spatial geospatial reference for given EPSG
Method signatures and docstrings:
- def __init__(self, log, fileName): Constructor :param log: logger object :param filename: Work file name
- def checkSpatialReference(self): ... | Implement the Python class `SpatialReference` described below.
Class description:
API for get the spatial geospatial reference for given EPSG
Method signatures and docstrings:
- def __init__(self, log, fileName): Constructor :param log: logger object :param filename: Work file name
- def checkSpatialReference(self): ... | 9764fcb86d3898b232c4cc333dab75ebe41cd421 | <|skeleton|>
class SpatialReference:
"""API for get the spatial geospatial reference for given EPSG"""
def __init__(self, log, fileName):
"""Constructor :param log: logger object :param filename: Work file name"""
<|body_0|>
def checkSpatialReference(self):
"""Obtain EPSG and WKT f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpatialReference:
"""API for get the spatial geospatial reference for given EPSG"""
def __init__(self, log, fileName):
"""Constructor :param log: logger object :param filename: Work file name"""
self.__url = Config.EPSG_URL
self.__log = log
self.fileName = fileName
... | the_stack_v2_python_sparse | PlanheatMappingModule/PlanHeatDMM/restApi/spatial_reference.py | Planheat/Planheat-Tool | train | 2 |
e9630c956879babc185c76c590abaff6285ade25 | [
"if isinstance(other, ArbitrationIdParts):\n return bool(other.function_code == self.function_code and other.node_id == self.node_id and (other.originating_node_id == self.originating_node_id) and (other.message_id == self.message_id))\nreturn False",
"def _safe_to_str(enum_type: Type[Enum], val: int) -> str:\... | <|body_start_0|>
if isinstance(other, ArbitrationIdParts):
return bool(other.function_code == self.function_code and other.node_id == self.node_id and (other.originating_node_id == self.originating_node_id) and (other.message_id == self.message_id))
return False
<|end_body_0|>
<|body_start_... | A bit field of the arbitration id parts. | ArbitrationIdParts | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArbitrationIdParts:
"""A bit field of the arbitration id parts."""
def __eq__(self, other: object) -> bool:
"""Check equality."""
<|body_0|>
def __repr__(self) -> str:
"""Return string representation of class."""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_010686 | 2,550 | permissive | [
{
"docstring": "Check equality.",
"name": "__eq__",
"signature": "def __eq__(self, other: object) -> bool"
},
{
"docstring": "Return string representation of class.",
"name": "__repr__",
"signature": "def __repr__(self) -> str"
}
] | 2 | stack_v2_sparse_classes_30k_train_017820 | Implement the Python class `ArbitrationIdParts` described below.
Class description:
A bit field of the arbitration id parts.
Method signatures and docstrings:
- def __eq__(self, other: object) -> bool: Check equality.
- def __repr__(self) -> str: Return string representation of class. | Implement the Python class `ArbitrationIdParts` described below.
Class description:
A bit field of the arbitration id parts.
Method signatures and docstrings:
- def __eq__(self, other: object) -> bool: Check equality.
- def __repr__(self) -> str: Return string representation of class.
<|skeleton|>
class ArbitrationI... | 026b523c8c9e5d45910c490efb89194d72595be9 | <|skeleton|>
class ArbitrationIdParts:
"""A bit field of the arbitration id parts."""
def __eq__(self, other: object) -> bool:
"""Check equality."""
<|body_0|>
def __repr__(self) -> str:
"""Return string representation of class."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArbitrationIdParts:
"""A bit field of the arbitration id parts."""
def __eq__(self, other: object) -> bool:
"""Check equality."""
if isinstance(other, ArbitrationIdParts):
return bool(other.function_code == self.function_code and other.node_id == self.node_id and (other.origin... | the_stack_v2_python_sparse | hardware/opentrons_hardware/firmware_bindings/arbitration_id.py | Opentrons/opentrons | train | 326 |
561c157f063f37bc7391613d93a574ad4802aead | [
"self.parent = parent\nself.win = Toplevel()\nself.win.transient(parent)\nself.win.title(title)\nself.add_buttons(message)\nself.win.grab_set()\nself.win.protocol('WM_DELETE_WINDOW', self.cancel)\nself.win.geometry('+%d+%d' % (parent.winfo_rootx() + 50, parent.winfo_rooty() + 50))\nself.win.bind('<Return>', self... | <|body_start_0|>
self.parent = parent
self.win = Toplevel()
self.win.transient(parent)
self.win.title(title)
self.add_buttons(message)
self.win.grab_set()
self.win.protocol('WM_DELETE_WINDOW', self.cancel)
self.win.geometry('+%d+%d' % (parent.winfo_rootx()... | askyesnocancel | [
"MIT",
"Apache-2.0",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class askyesnocancel:
def __init__(self, title='Dialog', message='Message', parent=None):
"""Display a Yes,No,Cancel dialog"""
<|body_0|>
def add_buttons(self, message):
"""Add the buttons"""
<|body_1|>
def yes(self):
"""Return teh yes value"""
... | stack_v2_sparse_classes_36k_train_010687 | 13,430 | permissive | [
{
"docstring": "Display a Yes,No,Cancel dialog",
"name": "__init__",
"signature": "def __init__(self, title='Dialog', message='Message', parent=None)"
},
{
"docstring": "Add the buttons",
"name": "add_buttons",
"signature": "def add_buttons(self, message)"
},
{
"docstring": "Retu... | 6 | null | Implement the Python class `askyesnocancel` described below.
Class description:
Implement the askyesnocancel class.
Method signatures and docstrings:
- def __init__(self, title='Dialog', message='Message', parent=None): Display a Yes,No,Cancel dialog
- def add_buttons(self, message): Add the buttons
- def yes(self): ... | Implement the Python class `askyesnocancel` described below.
Class description:
Implement the askyesnocancel class.
Method signatures and docstrings:
- def __init__(self, title='Dialog', message='Message', parent=None): Display a Yes,No,Cancel dialog
- def add_buttons(self, message): Add the buttons
- def yes(self): ... | 983795788089ca5093474ba144340e02666fc6cc | <|skeleton|>
class askyesnocancel:
def __init__(self, title='Dialog', message='Message', parent=None):
"""Display a Yes,No,Cancel dialog"""
<|body_0|>
def add_buttons(self, message):
"""Add the buttons"""
<|body_1|>
def yes(self):
"""Return teh yes value"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class askyesnocancel:
def __init__(self, title='Dialog', message='Message', parent=None):
"""Display a Yes,No,Cancel dialog"""
self.parent = parent
self.win = Toplevel()
self.win.transient(parent)
self.win.title(title)
self.add_buttons(message)
self.win.grab_s... | the_stack_v2_python_sparse | PEATDB/Dialogs.py | tubapala/peat | train | 0 | |
8db267cd96c592043aff3d74b1c300aa773bb56d | [
"ans = 0\nwhile n > 0:\n n &= n - 1\n ans += 1\nreturn ans",
"x = [0] * (num + 1)\nfor i in range(1, num + 1):\n x[i] = self.hammingWeight(i)\nreturn x"
] | <|body_start_0|>
ans = 0
while n > 0:
n &= n - 1
ans += 1
return ans
<|end_body_0|>
<|body_start_1|>
x = [0] * (num + 1)
for i in range(1, num + 1):
x[i] = self.hammingWeight(i)
return x
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hammingWeight(self, n: int) -> int:
"""bit manipulation: n & (n - 1) flip the rightmost 1 into 0 n & ~(n - 1) or n & (-n) get out rigthmost 1 with trailing zeros, e.g., rightmost 1's index"""
<|body_0|>
def countBits(self, num: int) -> List[int]:
"""Q19... | stack_v2_sparse_classes_36k_train_010688 | 1,788 | no_license | [
{
"docstring": "bit manipulation: n & (n - 1) flip the rightmost 1 into 0 n & ~(n - 1) or n & (-n) get out rigthmost 1 with trailing zeros, e.g., rightmost 1's index",
"name": "hammingWeight",
"signature": "def hammingWeight(self, n: int) -> int"
},
{
"docstring": "Q191",
"name": "countBits"... | 2 | stack_v2_sparse_classes_30k_train_005904 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hammingWeight(self, n: int) -> int: bit manipulation: n & (n - 1) flip the rightmost 1 into 0 n & ~(n - 1) or n & (-n) get out rigthmost 1 with trailing zeros, e.g., rightmos... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hammingWeight(self, n: int) -> int: bit manipulation: n & (n - 1) flip the rightmost 1 into 0 n & ~(n - 1) or n & (-n) get out rigthmost 1 with trailing zeros, e.g., rightmos... | 6043134736452a6f4704b62857d0aed2e9571164 | <|skeleton|>
class Solution:
def hammingWeight(self, n: int) -> int:
"""bit manipulation: n & (n - 1) flip the rightmost 1 into 0 n & ~(n - 1) or n & (-n) get out rigthmost 1 with trailing zeros, e.g., rightmost 1's index"""
<|body_0|>
def countBits(self, num: int) -> List[int]:
"""Q19... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def hammingWeight(self, n: int) -> int:
"""bit manipulation: n & (n - 1) flip the rightmost 1 into 0 n & ~(n - 1) or n & (-n) get out rigthmost 1 with trailing zeros, e.g., rightmost 1's index"""
ans = 0
while n > 0:
n &= n - 1
ans += 1
return ... | the_stack_v2_python_sparse | src/0300-0399/0338.count.bits.py | gyang274/leetcode | train | 1 | |
1f469c4a7678bd681ee263ed81c12bfcf5d203d3 | [
"if not A:\n return -1\nn = len(A)\nsortedA, index = zip(*sorted(((a, i) for i, a in enumerate(A))))\nindex_max = [index[-1]] * n\nfor i in range(n - 2, -1, -1):\n index_max[i] = max(index[i], index_max[i + 1])\nres = 0\nfor i, j in zip(index, index_max):\n res = max(res, j - i)\nreturn res",
"if not A:\... | <|body_start_0|>
if not A:
return -1
n = len(A)
sortedA, index = zip(*sorted(((a, i) for i, a in enumerate(A))))
index_max = [index[-1]] * n
for i in range(n - 2, -1, -1):
index_max[i] = max(index[i], index_max[i + 1])
res = 0
for i, j in z... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maximumGap(self, A):
"""Time Complexity: O(nlogn)"""
<|body_0|>
def naiveMaximumGap(self, A):
"""Time Complexity: O(n*n)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not A:
return -1
n = len(A)
sortedA... | stack_v2_sparse_classes_36k_train_010689 | 2,223 | permissive | [
{
"docstring": "Time Complexity: O(nlogn)",
"name": "maximumGap",
"signature": "def maximumGap(self, A)"
},
{
"docstring": "Time Complexity: O(n*n)",
"name": "naiveMaximumGap",
"signature": "def naiveMaximumGap(self, A)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009359 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximumGap(self, A): Time Complexity: O(nlogn)
- def naiveMaximumGap(self, A): Time Complexity: O(n*n) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximumGap(self, A): Time Complexity: O(nlogn)
- def naiveMaximumGap(self, A): Time Complexity: O(n*n)
<|skeleton|>
class Solution:
def maximumGap(self, A):
"""... | 77bc551a03a2a3e3808e50016ece14adb5cfbd96 | <|skeleton|>
class Solution:
def maximumGap(self, A):
"""Time Complexity: O(nlogn)"""
<|body_0|>
def naiveMaximumGap(self, A):
"""Time Complexity: O(n*n)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maximumGap(self, A):
"""Time Complexity: O(nlogn)"""
if not A:
return -1
n = len(A)
sortedA, index = zip(*sorted(((a, i) for i, a in enumerate(A))))
index_max = [index[-1]] * n
for i in range(n - 2, -1, -1):
index_max[i] = m... | the_stack_v2_python_sparse | quizzes/interviewbit/programming/arrays/max_distance.py | JiniousChoi/encyclopedia-in-code | train | 2 | |
a905071c08010b848a2f724a92b6d66768ff291e | [
"self.dq = collections.deque([])\nself.size = size\nself.sumval = 0",
"if len(self.dq) < self.size:\n self.sumval += val\n self.dq.append(val)\n return float(self.sumval) / float(len(self.dq))\nelse:\n v = self.dq.popleft()\n self.sumval -= v\n self.sumval += val\n self.dq.append(val)\n re... | <|body_start_0|>
self.dq = collections.deque([])
self.size = size
self.sumval = 0
<|end_body_0|>
<|body_start_1|>
if len(self.dq) < self.size:
self.sumval += val
self.dq.append(val)
return float(self.sumval) / float(len(self.dq))
else:
... | MovingAverage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.dq = collections.deque([])
... | stack_v2_sparse_classes_36k_train_010690 | 816 | permissive | [
{
"docstring": "Initialize your data structure here. :type size: int",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": ":type val: int :rtype: float",
"name": "next",
"signature": "def next(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001148 | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float
<|skeleton|>
class MovingAverage:
... | 86f1cb98de801f58c39d9a48ce9de12df7303d20 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
self.dq = collections.deque([])
self.size = size
self.sumval = 0
def next(self, val):
""":type val: int :rtype: float"""
if len(self.dq) < self.size:
... | the_stack_v2_python_sparse | 346-Moving-Average-from-Data-Stream/solution.py | Tanych/CodeTracking | train | 0 | |
4cdcd2254e219ca22f778cf162069424188aa01a | [
"super().__init__()\nself.in_dim = in_dim\nself.out_dim = out_dim\nself.min_var = min_var\nself.network = VanillaNN(in_dim, 2 * out_dim, hidden_dims, non_linearity)\nself.restrict_var = restrict_var\nif initial_sigma is not None:\n self.network.layers[-1].bias.data = torch.cat([1e-06 * torch.randn(out_dim), np.l... | <|body_start_0|>
super().__init__()
self.in_dim = in_dim
self.out_dim = out_dim
self.min_var = min_var
self.network = VanillaNN(in_dim, 2 * out_dim, hidden_dims, non_linearity)
self.restrict_var = restrict_var
if initial_sigma is not None:
self.network... | A `vanilla' NN whose output is the natural parameters of a normal distribution over y (as opposed to a point estimate of y). Variance is fixed. | ProbabilisticVanillaNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProbabilisticVanillaNN:
"""A `vanilla' NN whose output is the natural parameters of a normal distribution over y (as opposed to a point estimate of y). Variance is fixed."""
def __init__(self, in_dim, out_dim, hidden_dims, non_linearity=F.relu, min_var=0.01, initial_sigma=None, restrict_var=... | stack_v2_sparse_classes_36k_train_010691 | 16,175 | no_license | [
{
"docstring": ":param in_dim: (int) Dimensionality of the input. :param out_dim: (int) Dimensionality of the target for which a distribution is being obtained. :param hidden_dims: (list of ints) Architecture of the network. :param non_linearity: Non-linear activation function to apply after each linear transfo... | 2 | stack_v2_sparse_classes_30k_train_020112 | Implement the Python class `ProbabilisticVanillaNN` described below.
Class description:
A `vanilla' NN whose output is the natural parameters of a normal distribution over y (as opposed to a point estimate of y). Variance is fixed.
Method signatures and docstrings:
- def __init__(self, in_dim, out_dim, hidden_dims, n... | Implement the Python class `ProbabilisticVanillaNN` described below.
Class description:
A `vanilla' NN whose output is the natural parameters of a normal distribution over y (as opposed to a point estimate of y). Variance is fixed.
Method signatures and docstrings:
- def __init__(self, in_dim, out_dim, hidden_dims, n... | de60f831ee082ab2ae232c498cf2755da7c14c27 | <|skeleton|>
class ProbabilisticVanillaNN:
"""A `vanilla' NN whose output is the natural parameters of a normal distribution over y (as opposed to a point estimate of y). Variance is fixed."""
def __init__(self, in_dim, out_dim, hidden_dims, non_linearity=F.relu, min_var=0.01, initial_sigma=None, restrict_var=... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProbabilisticVanillaNN:
"""A `vanilla' NN whose output is the natural parameters of a normal distribution over y (as opposed to a point estimate of y). Variance is fixed."""
def __init__(self, in_dim, out_dim, hidden_dims, non_linearity=F.relu, min_var=0.01, initial_sigma=None, restrict_var=True):
... | the_stack_v2_python_sparse | models/networks/np_networks.py | PenelopeJones/neural_processes | train | 4 |
db48684ec477ee2ba653646955f644ad32eb1b2c | [
"self.word2prob = word2prob\nself.arora_a = arora_a\nself.glove_name = glove_name\nself.glove_dim = glove_dim\nself.glove_cache = glove_cache\nself.first_sv = first_sv\nif self.first_sv is not None:\n self.first_sv = torch.tensor(self.first_sv)\nself.min_word_prob = min(word2prob.values())\nself.tt_embs = None\n... | <|body_start_0|>
self.word2prob = word2prob
self.arora_a = arora_a
self.glove_name = glove_name
self.glove_dim = glove_dim
self.glove_cache = glove_cache
self.first_sv = first_sv
if self.first_sv is not None:
self.first_sv = torch.tensor(self.first_sv)... | A class to produce Arora-style sentence embeddings sent_emb(s) where s is a sentence. Also gives relatedness scores cos_sim(word_emb(w), sent_emb(s)) for words w with GloVe embeddings word_emb(w). See: "A Simple But Tough-To-Beat Baseline For Sentence Embeddings", Arora et al, 2017, https://openreview.net/pdf?id=SyK00v... | SentenceEmbedder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SentenceEmbedder:
"""A class to produce Arora-style sentence embeddings sent_emb(s) where s is a sentence. Also gives relatedness scores cos_sim(word_emb(w), sent_emb(s)) for words w with GloVe embeddings word_emb(w). See: "A Simple But Tough-To-Beat Baseline For Sentence Embeddings", Arora et al... | stack_v2_sparse_classes_36k_train_010692 | 16,277 | permissive | [
{
"docstring": "Inputs: word2prob: dict mapping words to their unigram probs arora_a: a float. Is the constant (called \"a\" in the paper) used to compute Arora sentence embeddings. glove_name: the version of GloVe to use, e.g. '840B' glove_dim: the dimension of the GloVe embeddings to use, e.g. 300 first_sv: n... | 5 | stack_v2_sparse_classes_30k_train_016969 | Implement the Python class `SentenceEmbedder` described below.
Class description:
A class to produce Arora-style sentence embeddings sent_emb(s) where s is a sentence. Also gives relatedness scores cos_sim(word_emb(w), sent_emb(s)) for words w with GloVe embeddings word_emb(w). See: "A Simple But Tough-To-Beat Baselin... | Implement the Python class `SentenceEmbedder` described below.
Class description:
A class to produce Arora-style sentence embeddings sent_emb(s) where s is a sentence. Also gives relatedness scores cos_sim(word_emb(w), sent_emb(s)) for words w with GloVe embeddings word_emb(w). See: "A Simple But Tough-To-Beat Baselin... | e2d2c613ac4075ce023d6b4acb0a5eddac4e7837 | <|skeleton|>
class SentenceEmbedder:
"""A class to produce Arora-style sentence embeddings sent_emb(s) where s is a sentence. Also gives relatedness scores cos_sim(word_emb(w), sent_emb(s)) for words w with GloVe embeddings word_emb(w). See: "A Simple But Tough-To-Beat Baseline For Sentence Embeddings", Arora et al... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SentenceEmbedder:
"""A class to produce Arora-style sentence embeddings sent_emb(s) where s is a sentence. Also gives relatedness scores cos_sim(word_emb(w), sent_emb(s)) for words w with GloVe embeddings word_emb(w). See: "A Simple But Tough-To-Beat Baseline For Sentence Embeddings", Arora et al, 2017, https... | the_stack_v2_python_sparse | projects/adaptive_learning/scripts/arora.py | hengyicai/Adaptive_Multi-curricula_Learning_for_Dialog | train | 19 |
bc07131ea149006a74120c4bfb2dedbaef8abd60 | [
"monitor_nodes: List[str] = values.get('monitor_nodes', [])\nrecord_nodes: List[str] = values.get('record_nodes', [])\noverlapping = set(monitor_nodes) & set(record_nodes)\nif len(overlapping):\n raise ValueError('Same node ids found in OPC_MONITOR_NODES and OPC_RECORD_NODES environment variables')\nreturn value... | <|body_start_0|>
monitor_nodes: List[str] = values.get('monitor_nodes', [])
record_nodes: List[str] = values.get('record_nodes', [])
overlapping = set(monitor_nodes) & set(record_nodes)
if len(overlapping):
raise ValueError('Same node ids found in OPC_MONITOR_NODES and OPC_RE... | OPC-UA related configuration options. | OPCSettings | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OPCSettings:
"""OPC-UA related configuration options."""
def check_nodes_overlapping(cls: 'OPCSettings', values: Dict[str, Any]) -> Dict[str, Any]:
"""Validates that monitored node ids and recorded node ids do not ovelap."""
<|body_0|>
def check_cert_and_key_set(cls: 'OP... | stack_v2_sparse_classes_36k_train_010693 | 6,638 | permissive | [
{
"docstring": "Validates that monitored node ids and recorded node ids do not ovelap.",
"name": "check_nodes_overlapping",
"signature": "def check_nodes_overlapping(cls: 'OPCSettings', values: Dict[str, Any]) -> Dict[str, Any]"
},
{
"docstring": "Validates that both or none of certificate and p... | 2 | stack_v2_sparse_classes_30k_train_006404 | Implement the Python class `OPCSettings` described below.
Class description:
OPC-UA related configuration options.
Method signatures and docstrings:
- def check_nodes_overlapping(cls: 'OPCSettings', values: Dict[str, Any]) -> Dict[str, Any]: Validates that monitored node ids and recorded node ids do not ovelap.
- def... | Implement the Python class `OPCSettings` described below.
Class description:
OPC-UA related configuration options.
Method signatures and docstrings:
- def check_nodes_overlapping(cls: 'OPCSettings', values: Dict[str, Any]) -> Dict[str, Any]: Validates that monitored node ids and recorded node ids do not ovelap.
- def... | 9e3370a7656b415058acf2d39a690a72f6eb343f | <|skeleton|>
class OPCSettings:
"""OPC-UA related configuration options."""
def check_nodes_overlapping(cls: 'OPCSettings', values: Dict[str, Any]) -> Dict[str, Any]:
"""Validates that monitored node ids and recorded node ids do not ovelap."""
<|body_0|>
def check_cert_and_key_set(cls: 'OP... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OPCSettings:
"""OPC-UA related configuration options."""
def check_nodes_overlapping(cls: 'OPCSettings', values: Dict[str, Any]) -> Dict[str, Any]:
"""Validates that monitored node ids and recorded node ids do not ovelap."""
monitor_nodes: List[str] = values.get('monitor_nodes', [])
... | the_stack_v2_python_sparse | src/opcua_webhmi_bridge/config.py | renovate-tests/opcua-webhmi-bridge | train | 0 |
2cab56798225c472786e89e5ef2ff87cab852ad3 | [
"size = len(piles)\ndp = [[[0, 0] for _ in range(size)] for _ in range(size)]\nfor i in range(size):\n dp[i][i][0] = piles[i]\nfor L in range(2, size + 1):\n for i in range(size - L + 1):\n j = L + i - 1\n left = piles[i] + dp[i + 1][j][1]\n right = piles[j] + dp[i][j - 1][1]\n if ... | <|body_start_0|>
size = len(piles)
dp = [[[0, 0] for _ in range(size)] for _ in range(size)]
for i in range(size):
dp[i][i][0] = piles[i]
for L in range(2, size + 1):
for i in range(size - L + 1):
j = L + i - 1
left = piles[i] + dp[... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def stoneGame(self, piles: List[int]) -> bool:
"""斜着遍历"""
<|body_0|>
def stoneGame_1(self, piles: List[int]) -> bool:
"""也可以对列从左往右遍历,对行从下往上遍历,来填dp表"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
size = len(piles)
dp = [[[0, 0] for... | stack_v2_sparse_classes_36k_train_010694 | 1,942 | no_license | [
{
"docstring": "斜着遍历",
"name": "stoneGame",
"signature": "def stoneGame(self, piles: List[int]) -> bool"
},
{
"docstring": "也可以对列从左往右遍历,对行从下往上遍历,来填dp表",
"name": "stoneGame_1",
"signature": "def stoneGame_1(self, piles: List[int]) -> bool"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def stoneGame(self, piles: List[int]) -> bool: 斜着遍历
- def stoneGame_1(self, piles: List[int]) -> bool: 也可以对列从左往右遍历,对行从下往上遍历,来填dp表 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def stoneGame(self, piles: List[int]) -> bool: 斜着遍历
- def stoneGame_1(self, piles: List[int]) -> bool: 也可以对列从左往右遍历,对行从下往上遍历,来填dp表
<|skeleton|>
class Solution:
def stoneGame... | 3508e1ce089131b19603c3206aab4cf43023bb19 | <|skeleton|>
class Solution:
def stoneGame(self, piles: List[int]) -> bool:
"""斜着遍历"""
<|body_0|>
def stoneGame_1(self, piles: List[int]) -> bool:
"""也可以对列从左往右遍历,对行从下往上遍历,来填dp表"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def stoneGame(self, piles: List[int]) -> bool:
"""斜着遍历"""
size = len(piles)
dp = [[[0, 0] for _ in range(size)] for _ in range(size)]
for i in range(size):
dp[i][i][0] = piles[i]
for L in range(2, size + 1):
for i in range(size - L + 1)... | the_stack_v2_python_sparse | algorithm/leetcode/dp/24-石子游戏.py | lxconfig/UbuntuCode_bak | train | 0 | |
e5308cbb43f3477e9ad8a6d29c14daac171cb072 | [
"xor = len(nums)\nfor i in range(0, len(nums)):\n xor = xor ^ i ^ nums[i]\nreturn xor",
"n = len(nums)\nideal_total = n * (n + 1) / 2\ntotal = 0\nfor num in nums:\n total += num\nreturn ideal_total - total"
] | <|body_start_0|>
xor = len(nums)
for i in range(0, len(nums)):
xor = xor ^ i ^ nums[i]
return xor
<|end_body_0|>
<|body_start_1|>
n = len(nums)
ideal_total = n * (n + 1) / 2
total = 0
for num in nums:
total += num
return ideal_tota... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def missingNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def missingNumberClassic(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
xor = len(nums)
for i in r... | stack_v2_sparse_classes_36k_train_010695 | 984 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "missingNumber",
"signature": "def missingNumber(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "missingNumberClassic",
"signature": "def missingNumberClassic(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012005 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def missingNumber(self, nums): :type nums: List[int] :rtype: int
- def missingNumberClassic(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def missingNumber(self, nums): :type nums: List[int] :rtype: int
- def missingNumberClassic(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def ... | 664ca26b70ddc7461f2428c28ed13b632fc1f8fd | <|skeleton|>
class Solution:
def missingNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def missingNumberClassic(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def missingNumber(self, nums):
""":type nums: List[int] :rtype: int"""
xor = len(nums)
for i in range(0, len(nums)):
xor = xor ^ i ^ nums[i]
return xor
def missingNumberClassic(self, nums):
""":type nums: List[int] :rtype: int"""
n = l... | the_stack_v2_python_sparse | missing_number.py | sshukla31/leetcode | train | 0 | |
cb73cea591e0d168961d515e34ec60e34661ebfb | [
"if not input_action_string:\n return None\naction_string = input_action_string.strip().lower()\nfor action_num, verb in enumerate(self.VERBS):\n if action_string.startswith(verb):\n return self.__from_clean_string(action_num, action_string)\nreturn None",
"action = GameAction(action_num)\nwords = st... | <|body_start_0|>
if not input_action_string:
return None
action_string = input_action_string.strip().lower()
for action_num, verb in enumerate(self.VERBS):
if action_string.startswith(verb):
return self.__from_clean_string(action_num, action_string)
... | Parser for translating actions to/from strings | TheAiGameActionBuilder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TheAiGameActionBuilder:
"""Parser for translating actions to/from strings"""
def from_string(self, input_action_string):
"""Returns the appropriate game action, or None for invalid strings"""
<|body_0|>
def __from_clean_string(self, action_num, string):
"""Given ... | stack_v2_sparse_classes_36k_train_010696 | 8,250 | permissive | [
{
"docstring": "Returns the appropriate game action, or None for invalid strings",
"name": "from_string",
"signature": "def from_string(self, input_action_string)"
},
{
"docstring": "Given a string that starts with a verb, return the GameAction",
"name": "__from_clean_string",
"signature... | 3 | stack_v2_sparse_classes_30k_train_015303 | Implement the Python class `TheAiGameActionBuilder` described below.
Class description:
Parser for translating actions to/from strings
Method signatures and docstrings:
- def from_string(self, input_action_string): Returns the appropriate game action, or None for invalid strings
- def __from_clean_string(self, action... | Implement the Python class `TheAiGameActionBuilder` described below.
Class description:
Parser for translating actions to/from strings
Method signatures and docstrings:
- def from_string(self, input_action_string): Returns the appropriate game action, or None for invalid strings
- def __from_clean_string(self, action... | 5e7241efac1b0757f39c28f6d485f4d79960095b | <|skeleton|>
class TheAiGameActionBuilder:
"""Parser for translating actions to/from strings"""
def from_string(self, input_action_string):
"""Returns the appropriate game action, or None for invalid strings"""
<|body_0|>
def __from_clean_string(self, action_num, string):
"""Given ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TheAiGameActionBuilder:
"""Parser for translating actions to/from strings"""
def from_string(self, input_action_string):
"""Returns the appropriate game action, or None for invalid strings"""
if not input_action_string:
return None
action_string = input_action_string.s... | the_stack_v2_python_sparse | pokeher/theaigame.py | gnmerritt/poker | train | 5 |
02f98c17d1ffaaf97c2c8b34dec061e7eccb934b | [
"video_idx, frames_idx = self.get_clip_location(idx)\nmask_folder = self.mask_paths[video_idx]\nif mask_folder == '':\n return None\nframes = self.clips[video_idx][frames_idx]\nmask_frames = sorted(Path(mask_folder).glob('*.bmp'))\nmask_paths = [mask_frames[idx] for idx in frames.int()]\nmasks = np.stack([cv2.im... | <|body_start_0|>
video_idx, frames_idx = self.get_clip_location(idx)
mask_folder = self.mask_paths[video_idx]
if mask_folder == '':
return None
frames = self.clips[video_idx][frames_idx]
mask_frames = sorted(Path(mask_folder).glob('*.bmp'))
mask_paths = [mask_... | Clips class for UCSDped dataset. | UCSDpedClipsIndexer | [
"CC-BY-SA-4.0",
"CC-BY-SA-3.0",
"CC-BY-NC-SA-4.0",
"Python-2.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UCSDpedClipsIndexer:
"""Clips class for UCSDped dataset."""
def get_mask(self, idx) -> np.ndarray | None:
"""Retrieve the masks from the file system."""
<|body_0|>
def _compute_frame_pts(self) -> None:
"""Retrieve the number of frames in each video."""
<|... | stack_v2_sparse_classes_36k_train_010697 | 11,841 | permissive | [
{
"docstring": "Retrieve the masks from the file system.",
"name": "get_mask",
"signature": "def get_mask(self, idx) -> np.ndarray | None"
},
{
"docstring": "Retrieve the number of frames in each video.",
"name": "_compute_frame_pts",
"signature": "def _compute_frame_pts(self) -> None"
... | 3 | null | Implement the Python class `UCSDpedClipsIndexer` described below.
Class description:
Clips class for UCSDped dataset.
Method signatures and docstrings:
- def get_mask(self, idx) -> np.ndarray | None: Retrieve the masks from the file system.
- def _compute_frame_pts(self) -> None: Retrieve the number of frames in each... | Implement the Python class `UCSDpedClipsIndexer` described below.
Class description:
Clips class for UCSDped dataset.
Method signatures and docstrings:
- def get_mask(self, idx) -> np.ndarray | None: Retrieve the masks from the file system.
- def _compute_frame_pts(self) -> None: Retrieve the number of frames in each... | 4abfa93dcfcb98771bc768b334c929ff9a02ce8b | <|skeleton|>
class UCSDpedClipsIndexer:
"""Clips class for UCSDped dataset."""
def get_mask(self, idx) -> np.ndarray | None:
"""Retrieve the masks from the file system."""
<|body_0|>
def _compute_frame_pts(self) -> None:
"""Retrieve the number of frames in each video."""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UCSDpedClipsIndexer:
"""Clips class for UCSDped dataset."""
def get_mask(self, idx) -> np.ndarray | None:
"""Retrieve the masks from the file system."""
video_idx, frames_idx = self.get_clip_location(idx)
mask_folder = self.mask_paths[video_idx]
if mask_folder == '':
... | the_stack_v2_python_sparse | src/anomalib/data/ucsd_ped.py | openvinotoolkit/anomalib | train | 2,325 |
b1a624d72820bcb199f7aec710250b19ac043705 | [
"xyz['cx'] = xyz.u - cx\nxyz['cy'] = xyz.v - cy\nxyz['cr'] = np.hypot(xyz.cx, xyz.cy)\nxyz['cth'] = np.unwrap(constrain_angle(np.arctan2(-cy, -cx) - np.arctan2(xyz.cy, xyz.cx)), discont=1.8 * pi)\nif np.abs(xyz['cth'].min() - 2 * pi) < 5 * degrees:\n xyz['cth'] -= 2 * pi\nydata = xyz.cr * xyz.cth\nodrdata = odr.... | <|body_start_0|>
xyz['cx'] = xyz.u - cx
xyz['cy'] = xyz.v - cy
xyz['cr'] = np.hypot(xyz.cx, xyz.cy)
xyz['cth'] = np.unwrap(constrain_angle(np.arctan2(-cy, -cx) - np.arctan2(xyz.cy, xyz.cx)), discont=1.8 * pi)
if np.abs(xyz['cth'].min() - 2 * pi) < 5 * degrees:
xyz['ct... | Provides methods to perform a linear fit to the data to find an initial guess for the Monte Carlo parameters. Two methods are provided: 1) `linear_prefit` -- This calculates r-phi and performs the linear fit. 2) `guess_parameters` -- This uses the results of the linear fit to guess the starting point for the Monte Carl... | LinearPrefitMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearPrefitMixin:
"""Provides methods to perform a linear fit to the data to find an initial guess for the Monte Carlo parameters. Two methods are provided: 1) `linear_prefit` -- This calculates r-phi and performs the linear fit. 2) `guess_parameters` -- This uses the results of the linear fit t... | stack_v2_sparse_classes_36k_train_010698 | 11,898 | no_license | [
{
"docstring": "Performs the linear prefit. The linear fit is performed using the SciPy ODR library, which does orthogonal distance regression. This means that the minimized quantity is the orthogonal distance between the line and each data point, rather than the distance along one of the coordinate directions.... | 2 | stack_v2_sparse_classes_30k_train_021192 | Implement the Python class `LinearPrefitMixin` described below.
Class description:
Provides methods to perform a linear fit to the data to find an initial guess for the Monte Carlo parameters. Two methods are provided: 1) `linear_prefit` -- This calculates r-phi and performs the linear fit. 2) `guess_parameters` -- Th... | Implement the Python class `LinearPrefitMixin` described below.
Class description:
Provides methods to perform a linear fit to the data to find an initial guess for the Monte Carlo parameters. Two methods are provided: 1) `linear_prefit` -- This calculates r-phi and performs the linear fit. 2) `guess_parameters` -- Th... | 8809d26c8659a02cabe4735df732b6f0a4d647bf | <|skeleton|>
class LinearPrefitMixin:
"""Provides methods to perform a linear fit to the data to find an initial guess for the Monte Carlo parameters. Two methods are provided: 1) `linear_prefit` -- This calculates r-phi and performs the linear fit. 2) `guess_parameters` -- This uses the results of the linear fit t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinearPrefitMixin:
"""Provides methods to perform a linear fit to the data to find an initial guess for the Monte Carlo parameters. Two methods are provided: 1) `linear_prefit` -- This calculates r-phi and performs the linear fit. 2) `guess_parameters` -- This uses the results of the linear fit to guess the s... | the_stack_v2_python_sparse | pytpc/fitting/mixins.py | ATTPC/pytpc | train | 1 |
f293e995798043f7762271848af4a97fd2196df8 | [
"suites = []\nfor s in cls.SUITES:\n s['tests'] = cls._get_tests(s)\n s['approxRunTime'] = cls._get_average_run_time(suite_model)\n suites.append(s)\nreturn suites",
"suite_file_name = '{}.py'.format(str(suite['id']).replace('.', os.path.sep))\nwith open(suite_file_name) as f:\n file_contents = f.read... | <|body_start_0|>
suites = []
for s in cls.SUITES:
s['tests'] = cls._get_tests(s)
s['approxRunTime'] = cls._get_average_run_time(suite_model)
suites.append(s)
return suites
<|end_body_0|>
<|body_start_1|>
suite_file_name = '{}.py'.format(str(suite['id'... | Available test suites provider | SuiteProvider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuiteProvider:
"""Available test suites provider"""
def get_list(cls, suite_model) -> list:
"""Return list of available test suites"""
<|body_0|>
def _get_tests(cls, suite: dict):
"""Get suite available tests"""
<|body_1|>
def _get_average_run_time(c... | stack_v2_sparse_classes_36k_train_010699 | 2,492 | no_license | [
{
"docstring": "Return list of available test suites",
"name": "get_list",
"signature": "def get_list(cls, suite_model) -> list"
},
{
"docstring": "Get suite available tests",
"name": "_get_tests",
"signature": "def _get_tests(cls, suite: dict)"
},
{
"docstring": "Get suite avera... | 3 | stack_v2_sparse_classes_30k_train_020499 | Implement the Python class `SuiteProvider` described below.
Class description:
Available test suites provider
Method signatures and docstrings:
- def get_list(cls, suite_model) -> list: Return list of available test suites
- def _get_tests(cls, suite: dict): Get suite available tests
- def _get_average_run_time(cls, ... | Implement the Python class `SuiteProvider` described below.
Class description:
Available test suites provider
Method signatures and docstrings:
- def get_list(cls, suite_model) -> list: Return list of available test suites
- def _get_tests(cls, suite: dict): Get suite available tests
- def _get_average_run_time(cls, ... | 4b9c65cf06912fe92d94b3989e0220aae3a31db4 | <|skeleton|>
class SuiteProvider:
"""Available test suites provider"""
def get_list(cls, suite_model) -> list:
"""Return list of available test suites"""
<|body_0|>
def _get_tests(cls, suite: dict):
"""Get suite available tests"""
<|body_1|>
def _get_average_run_time(c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SuiteProvider:
"""Available test suites provider"""
def get_list(cls, suite_model) -> list:
"""Return list of available test suites"""
suites = []
for s in cls.SUITES:
s['tests'] = cls._get_tests(s)
s['approxRunTime'] = cls._get_average_run_time(suite_model... | the_stack_v2_python_sparse | project/applications/platform-tests/app/suite_provider.py | trustedanalytics/platform-tests | train | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.