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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9c7489a39f8cc7e2e4a75b56cc6f46afe9351584 | [
"lst1 = self.travel(root1, [])\nlst2 = self.travel(root2, [])\nif len(lst1) != len(lst2):\n return False\nfor i in range(len(lst1)):\n if lst1[i] != lst2[i]:\n return False\nreturn True",
"if not root:\n return\nif not root.left and (not root.right):\n store_lst.append(root.val)\nself.travel(ro... | <|body_start_0|>
lst1 = self.travel(root1, [])
lst2 = self.travel(root2, [])
if len(lst1) != len(lst2):
return False
for i in range(len(lst1)):
if lst1[i] != lst2[i]:
return False
return True
<|end_body_0|>
<|body_start_1|>
if not ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def leafSimilar(self, root1, root2):
""":type root1: TreeNode :type root2: TreeNode :rtype: bool"""
<|body_0|>
def travel(self, root, store_lst):
""":param root: :param store_lst: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ls... | stack_v2_sparse_classes_36k_train_015800 | 1,034 | no_license | [
{
"docstring": ":type root1: TreeNode :type root2: TreeNode :rtype: bool",
"name": "leafSimilar",
"signature": "def leafSimilar(self, root1, root2)"
},
{
"docstring": ":param root: :param store_lst: :return:",
"name": "travel",
"signature": "def travel(self, root, store_lst)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def leafSimilar(self, root1, root2): :type root1: TreeNode :type root2: TreeNode :rtype: bool
- def travel(self, root, store_lst): :param root: :param store_lst: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def leafSimilar(self, root1, root2): :type root1: TreeNode :type root2: TreeNode :rtype: bool
- def travel(self, root, store_lst): :param root: :param store_lst: :return:
<|skel... | a75310a96d2b165b15d5ee10ec409a17cdc880ba | <|skeleton|>
class Solution:
def leafSimilar(self, root1, root2):
""":type root1: TreeNode :type root2: TreeNode :rtype: bool"""
<|body_0|>
def travel(self, root, store_lst):
""":param root: :param store_lst: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def leafSimilar(self, root1, root2):
""":type root1: TreeNode :type root2: TreeNode :rtype: bool"""
lst1 = self.travel(root1, [])
lst2 = self.travel(root2, [])
if len(lst1) != len(lst2):
return False
for i in range(len(lst1)):
if lst1[i... | the_stack_v2_python_sparse | leetcode/tree/code/872.py | skyxyz-lang/CS_Note | train | 0 | |
ba28ecd2c4f99542cfa2330745801482f67ad76f | [
"furniture = Furniture('2222', 'Chair', '$200', '$150', 'Wood', 'Small')\nself.assertEqual('2222', furniture.product_code)\nself.assertEqual('Chair', furniture.description)\nself.assertEqual('$200', furniture.market_price)\nself.assertEqual('$150', furniture.rental_price)\nself.assertEqual('Wood', furniture.materia... | <|body_start_0|>
furniture = Furniture('2222', 'Chair', '$200', '$150', 'Wood', 'Small')
self.assertEqual('2222', furniture.product_code)
self.assertEqual('Chair', furniture.description)
self.assertEqual('$200', furniture.market_price)
self.assertEqual('$150', furniture.rental_pr... | Unit tests the Furniture class | FurnitureTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FurnitureTest:
"""Unit tests the Furniture class"""
def test_add_furniture(self):
"""creates an object of the Furniture class"""
<|body_0|>
def test_return_dict(self):
"""calls the return_as_dictionary function on the Furniture class"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_015801 | 10,292 | no_license | [
{
"docstring": "creates an object of the Furniture class",
"name": "test_add_furniture",
"signature": "def test_add_furniture(self)"
},
{
"docstring": "calls the return_as_dictionary function on the Furniture class",
"name": "test_return_dict",
"signature": "def test_return_dict(self)"
... | 2 | null | Implement the Python class `FurnitureTest` described below.
Class description:
Unit tests the Furniture class
Method signatures and docstrings:
- def test_add_furniture(self): creates an object of the Furniture class
- def test_return_dict(self): calls the return_as_dictionary function on the Furniture class | Implement the Python class `FurnitureTest` described below.
Class description:
Unit tests the Furniture class
Method signatures and docstrings:
- def test_add_furniture(self): creates an object of the Furniture class
- def test_return_dict(self): calls the return_as_dictionary function on the Furniture class
<|skele... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class FurnitureTest:
"""Unit tests the Furniture class"""
def test_add_furniture(self):
"""creates an object of the Furniture class"""
<|body_0|>
def test_return_dict(self):
"""calls the return_as_dictionary function on the Furniture class"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FurnitureTest:
"""Unit tests the Furniture class"""
def test_add_furniture(self):
"""creates an object of the Furniture class"""
furniture = Furniture('2222', 'Chair', '$200', '$150', 'Wood', 'Small')
self.assertEqual('2222', furniture.product_code)
self.assertEqual('Chair... | the_stack_v2_python_sparse | students/David_Baylor/lesson01/Assignment/test_unit.py | JavaRod/SP_Python220B_2019 | train | 1 |
7e8a847ffe1caab01e41e75634a5814aba7029be | [
"super(backWarp, self).__init__()\nW, H = (int(dim[0] / 2), int(dim[1] / 2))\ngridX, gridY = np.meshgrid(np.arange(W), np.arange(H))\nself.W = W\nself.H = H\nself.gridX = torch.tensor(gridX, requires_grad=False).to(device)\nself.gridY = torch.tensor(gridY, requires_grad=False).to(device)",
"u = flow[:, 0, :, :]\n... | <|body_start_0|>
super(backWarp, self).__init__()
W, H = (int(dim[0] / 2), int(dim[1] / 2))
gridX, gridY = np.meshgrid(np.arange(W), np.arange(H))
self.W = W
self.H = H
self.gridX = torch.tensor(gridX, requires_grad=False).to(device)
self.gridY = torch.tensor(grid... | A class for creating a backwarping object. This is used for backwarping to an image: Given optical flow from frame I0 to I1 --> F_0_1 and frame I1, it generates I0 <-- backwarp(F_0_1, I1). ... Methods ------- forward(x) Returns output tensor after passing input `img` and `flow` to the backwarping block. | backWarp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class backWarp:
"""A class for creating a backwarping object. This is used for backwarping to an image: Given optical flow from frame I0 to I1 --> F_0_1 and frame I1, it generates I0 <-- backwarp(F_0_1, I1). ... Methods ------- forward(x) Returns output tensor after passing input `img` and `flow` to th... | stack_v2_sparse_classes_36k_train_015802 | 12,372 | permissive | [
{
"docstring": "Parameters ---------- W : int width of the image. H : int height of the image. device : device computation device (cpu/cuda).",
"name": "__init__",
"signature": "def __init__(self, dim, device)"
},
{
"docstring": "Returns output tensor after passing input `img` and `flow` to the ... | 2 | stack_v2_sparse_classes_30k_train_009593 | Implement the Python class `backWarp` described below.
Class description:
A class for creating a backwarping object. This is used for backwarping to an image: Given optical flow from frame I0 to I1 --> F_0_1 and frame I1, it generates I0 <-- backwarp(F_0_1, I1). ... Methods ------- forward(x) Returns output tensor aft... | Implement the Python class `backWarp` described below.
Class description:
A class for creating a backwarping object. This is used for backwarping to an image: Given optical flow from frame I0 to I1 --> F_0_1 and frame I1, it generates I0 <-- backwarp(F_0_1, I1). ... Methods ------- forward(x) Returns output tensor aft... | c43e93483ce7c75c689f3ab01f21279700e52031 | <|skeleton|>
class backWarp:
"""A class for creating a backwarping object. This is used for backwarping to an image: Given optical flow from frame I0 to I1 --> F_0_1 and frame I1, it generates I0 <-- backwarp(F_0_1, I1). ... Methods ------- forward(x) Returns output tensor after passing input `img` and `flow` to th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class backWarp:
"""A class for creating a backwarping object. This is used for backwarping to an image: Given optical flow from frame I0 to I1 --> F_0_1 and frame I1, it generates I0 <-- backwarp(F_0_1, I1). ... Methods ------- forward(x) Returns output tensor after passing input `img` and `flow` to the backwarping... | the_stack_v2_python_sparse | data/dataloader.py | xilongzhou/MaskDnGAN | train | 0 |
603ff58f6b74cde8a2e55861f2782c285b3c39ae | [
"self._size = size\nself._window = [None] * self._size\nself._len = 0\nself._ix = 0\nself._sum = 0",
"if self._window[self._ix]:\n self._sum -= self._window[self._ix]\nself._window[self._ix] = val\nself._ix = (self._ix + 1) % self._size\nself._sum += val\nself._len = min(self._size, self._len + 1)\nreturn self... | <|body_start_0|>
self._size = size
self._window = [None] * self._size
self._len = 0
self._ix = 0
self._sum = 0
<|end_body_0|>
<|body_start_1|>
if self._window[self._ix]:
self._sum -= self._window[self._ix]
self._window[self._ix] = val
self._ix... | MovingAverage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage:
def __init__(self, size: int):
"""Space: O(size)"""
<|body_0|>
def next(self, val: int) -> float:
"""O(1)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self._size = size
self._window = [None] * self._size
self._len =... | stack_v2_sparse_classes_36k_train_015803 | 596 | no_license | [
{
"docstring": "Space: O(size)",
"name": "__init__",
"signature": "def __init__(self, size: int)"
},
{
"docstring": "O(1)",
"name": "next",
"signature": "def next(self, val: int) -> float"
}
] | 2 | stack_v2_sparse_classes_30k_train_004303 | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size: int): Space: O(size)
- def next(self, val: int) -> float: O(1) | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size: int): Space: O(size)
- def next(self, val: int) -> float: O(1)
<|skeleton|>
class MovingAverage:
def __init__(self, size: int):
"... | 9a20e1835652f5e6c33ef5c238f622e81f84ca26 | <|skeleton|>
class MovingAverage:
def __init__(self, size: int):
"""Space: O(size)"""
<|body_0|>
def next(self, val: int) -> float:
"""O(1)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MovingAverage:
def __init__(self, size: int):
"""Space: O(size)"""
self._size = size
self._window = [None] * self._size
self._len = 0
self._ix = 0
self._sum = 0
def next(self, val: int) -> float:
"""O(1)"""
if self._window[self._ix]:
... | the_stack_v2_python_sparse | leetcode/p0346_moving_average_from_data_stream.py | weak-head/leetcode | train | 0 | |
b1b8755221603ac8f8b14d52348ff53d5e68c71e | [
"url = self.l + read_yaml()[7]['url1']\ntoken = readconfig('token')\nresult = set_show_fields(url=url, header={'Authorization': token})\nprint(result)\nreturn result",
"url = self.l + read_yaml()[7]['url2']\nresult = get_show_fields(url=url, header=self.header)\na = result['data']\nprint(a)\nreturn result"
] | <|body_start_0|>
url = self.l + read_yaml()[7]['url1']
token = readconfig('token')
result = set_show_fields(url=url, header={'Authorization': token})
print(result)
return result
<|end_body_0|>
<|body_start_1|>
url = self.l + read_yaml()[7]['url2']
result = get_sh... | TestSetShowFields | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSetShowFields:
def test_set_showfields(self):
"""修改联系人自定义列表头,接口地址:/api/scrm/setShowFields"""
<|body_0|>
def test_get_showfields(self):
"""获取联系人自定义列表头,接口地址:/api/scrm/getShowFields"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
url = self.l + rea... | stack_v2_sparse_classes_36k_train_015804 | 791 | no_license | [
{
"docstring": "修改联系人自定义列表头,接口地址:/api/scrm/setShowFields",
"name": "test_set_showfields",
"signature": "def test_set_showfields(self)"
},
{
"docstring": "获取联系人自定义列表头,接口地址:/api/scrm/getShowFields",
"name": "test_get_showfields",
"signature": "def test_get_showfields(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010733 | Implement the Python class `TestSetShowFields` described below.
Class description:
Implement the TestSetShowFields class.
Method signatures and docstrings:
- def test_set_showfields(self): 修改联系人自定义列表头,接口地址:/api/scrm/setShowFields
- def test_get_showfields(self): 获取联系人自定义列表头,接口地址:/api/scrm/getShowFields | Implement the Python class `TestSetShowFields` described below.
Class description:
Implement the TestSetShowFields class.
Method signatures and docstrings:
- def test_set_showfields(self): 修改联系人自定义列表头,接口地址:/api/scrm/setShowFields
- def test_get_showfields(self): 获取联系人自定义列表头,接口地址:/api/scrm/getShowFields
<|skeleton|>
... | 75f18afa6d74cb1916a2496d1a1f267bf8ddb93c | <|skeleton|>
class TestSetShowFields:
def test_set_showfields(self):
"""修改联系人自定义列表头,接口地址:/api/scrm/setShowFields"""
<|body_0|>
def test_get_showfields(self):
"""获取联系人自定义列表头,接口地址:/api/scrm/getShowFields"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestSetShowFields:
def test_set_showfields(self):
"""修改联系人自定义列表头,接口地址:/api/scrm/setShowFields"""
url = self.l + read_yaml()[7]['url1']
token = readconfig('token')
result = set_show_fields(url=url, header={'Authorization': token})
print(result)
return result
... | the_stack_v2_python_sparse | Test_case/test_5setshowfields.py | jiangna123000/api_test_case | train | 0 | |
eda96b4b10c902f1750390a30f3fa0108e3c704c | [
"if not email:\n raise ValueError('Must have an email address')\nif not name:\n raise ValueError('Must have a name')\nuser = self.model(email=self.normalize_email(email), name=name)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(email=self.normalize_email(ema... | <|body_start_0|>
if not email:
raise ValueError('Must have an email address')
if not name:
raise ValueError('Must have a name')
user = self.model(email=self.normalize_email(email), name=name)
user.set_password(password)
user.save(using=self._db)
re... | MyUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyUserManager:
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email and password."""
<|body_0|>
def create_superuser(self, email, name, password):
"""Creates and saves a superuser with the given email and password."""
... | stack_v2_sparse_classes_36k_train_015805 | 3,252 | no_license | [
{
"docstring": "Creates and saves a User with the given email and password.",
"name": "create_user",
"signature": "def create_user(self, email, name, password=None)"
},
{
"docstring": "Creates and saves a superuser with the given email and password.",
"name": "create_superuser",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_012271 | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, email, name, password=None): Creates and saves a User with the given email and password.
- def create_superuser(self, email, name, password): Crea... | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, email, name, password=None): Creates and saves a User with the given email and password.
- def create_superuser(self, email, name, password): Crea... | bf7f9c06168198e9ba07ffc56cb69c7dd2a38629 | <|skeleton|>
class MyUserManager:
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email and password."""
<|body_0|>
def create_superuser(self, email, name, password):
"""Creates and saves a superuser with the given email and password."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyUserManager:
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email and password."""
if not email:
raise ValueError('Must have an email address')
if not name:
raise ValueError('Must have a name')
user = self... | the_stack_v2_python_sparse | users/models.py | PRAYFRME/EWUConnect | train | 4 | |
6d1eef30587aea8adc045e4b0df934f51e2d203b | [
"super(TelegramIO, self).__init__()\nself.token = token\nself.chat_id = chat_id\nself.session = session = Session()\nself.text = self.__class__.__name__\ntry:\n res = session.post(self.API + '%s/sendMessage' % self.token, data={'text': '`' + self.text + '`', 'chat_id': self.chat_id, 'parse_mode': 'MarkdownV2'})\... | <|body_start_0|>
super(TelegramIO, self).__init__()
self.token = token
self.chat_id = chat_id
self.session = session = Session()
self.text = self.__class__.__name__
try:
res = session.post(self.API + '%s/sendMessage' % self.token, data={'text': '`' + self.text... | Non-blocking file-like IO using a Telegram Bot. | TelegramIO | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TelegramIO:
"""Non-blocking file-like IO using a Telegram Bot."""
def __init__(self, token, chat_id):
"""Creates a new message in the given `chat_id`."""
<|body_0|>
def write(self, s):
"""Replaces internal `message_id`'s text with `s`."""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k_train_015806 | 4,085 | permissive | [
{
"docstring": "Creates a new message in the given `chat_id`.",
"name": "__init__",
"signature": "def __init__(self, token, chat_id)"
},
{
"docstring": "Replaces internal `message_id`'s text with `s`.",
"name": "write",
"signature": "def write(self, s)"
}
] | 2 | null | Implement the Python class `TelegramIO` described below.
Class description:
Non-blocking file-like IO using a Telegram Bot.
Method signatures and docstrings:
- def __init__(self, token, chat_id): Creates a new message in the given `chat_id`.
- def write(self, s): Replaces internal `message_id`'s text with `s`. | Implement the Python class `TelegramIO` described below.
Class description:
Non-blocking file-like IO using a Telegram Bot.
Method signatures and docstrings:
- def __init__(self, token, chat_id): Creates a new message in the given `chat_id`.
- def write(self, s): Replaces internal `message_id`'s text with `s`.
<|ske... | 39efe4007fba2b12b75c72f7795827a1f74d640b | <|skeleton|>
class TelegramIO:
"""Non-blocking file-like IO using a Telegram Bot."""
def __init__(self, token, chat_id):
"""Creates a new message in the given `chat_id`."""
<|body_0|>
def write(self, s):
"""Replaces internal `message_id`'s text with `s`."""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TelegramIO:
"""Non-blocking file-like IO using a Telegram Bot."""
def __init__(self, token, chat_id):
"""Creates a new message in the given `chat_id`."""
super(TelegramIO, self).__init__()
self.token = token
self.chat_id = chat_id
self.session = session = Session()... | the_stack_v2_python_sparse | venv/Lib/site-packages/tqdm/contrib/telegram.py | tpike3/SugarScape | train | 11 |
d58d20abc941e8ba66937fd7d4d385d1c8ecdb26 | [
"a = super().get_actor(actor, aid)\nif a is None:\n if aid in self.monitors:\n return self.monitors[aid]\n elif aid in self.managed_actors:\n return self.managed_actors[aid]\n elif aid in self.registered:\n return self.registered[aid]\n else:\n for m in self.monitors.values()... | <|body_start_0|>
a = super().get_actor(actor, aid)
if a is None:
if aid in self.monitors:
return self.monitors[aid]
elif aid in self.managed_actors:
return self.managed_actors[aid]
elif aid in self.registered:
return sel... | Concurrency implementation for the ``arbiter`` | ArbiterConcurrency | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArbiterConcurrency:
"""Concurrency implementation for the ``arbiter``"""
def get_actor(self, actor, aid, check_monitor=True):
"""Given an actor unique id return the actor proxy."""
<|body_0|>
def create_mailbox(self, actor, loop):
"""Override :meth:`.Concurrency.... | stack_v2_sparse_classes_36k_train_015807 | 14,375 | no_license | [
{
"docstring": "Given an actor unique id return the actor proxy.",
"name": "get_actor",
"signature": "def get_actor(self, actor, aid, check_monitor=True)"
},
{
"docstring": "Override :meth:`.Concurrency.create_mailbox` to create the mailbox server.",
"name": "create_mailbox",
"signature"... | 2 | null | Implement the Python class `ArbiterConcurrency` described below.
Class description:
Concurrency implementation for the ``arbiter``
Method signatures and docstrings:
- def get_actor(self, actor, aid, check_monitor=True): Given an actor unique id return the actor proxy.
- def create_mailbox(self, actor, loop): Override... | Implement the Python class `ArbiterConcurrency` described below.
Class description:
Concurrency implementation for the ``arbiter``
Method signatures and docstrings:
- def get_actor(self, actor, aid, check_monitor=True): Given an actor unique id return the actor proxy.
- def create_mailbox(self, actor, loop): Override... | f37ed822b5863a5a11b09550dd32a73d68e7070b | <|skeleton|>
class ArbiterConcurrency:
"""Concurrency implementation for the ``arbiter``"""
def get_actor(self, actor, aid, check_monitor=True):
"""Given an actor unique id return the actor proxy."""
<|body_0|>
def create_mailbox(self, actor, loop):
"""Override :meth:`.Concurrency.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArbiterConcurrency:
"""Concurrency implementation for the ``arbiter``"""
def get_actor(self, actor, aid, check_monitor=True):
"""Given an actor unique id return the actor proxy."""
a = super().get_actor(actor, aid)
if a is None:
if aid in self.monitors:
... | the_stack_v2_python_sparse | venv/lib/python3.7/site-packages/pulsar/async/concurrency.py | ravisjoshi/python_snippets | train | 1 |
b90f1a88ebd0e56a2f0dda3f415de66afbbc0bf7 | [
"if 'type' in vals:\n if vals['type'] == 'sol_special':\n vals['current_amount'] = vals['amount']\nreturn super(enrich_category, self).create(vals)",
"if len(self.env['payment.enrich'].search([('enrich_category', '=', self.id), ('state', '!=', 'draft')])) > 0:\n raise exceptions.ValidationError(_('Ca... | <|body_start_0|>
if 'type' in vals:
if vals['type'] == 'sol_special':
vals['current_amount'] = vals['amount']
return super(enrich_category, self).create(vals)
<|end_body_0|>
<|body_start_1|>
if len(self.env['payment.enrich'].search([('enrich_category', '=', self.id),... | To manage enrich category | enrich_category | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class enrich_category:
"""To manage enrich category"""
def create(self, vals):
"""create operation @return: super create() method"""
<|body_0|>
def unlink(self):
"""delete the enrich category record if record in draft state, and create log message to the deleted record... | stack_v2_sparse_classes_36k_train_015808 | 32,018 | no_license | [
{
"docstring": "create operation @return: super create() method",
"name": "create",
"signature": "def create(self, vals)"
},
{
"docstring": "delete the enrich category record if record in draft state, and create log message to the deleted record. @return: super unlink() method",
"name": "unl... | 5 | stack_v2_sparse_classes_30k_train_004133 | Implement the Python class `enrich_category` described below.
Class description:
To manage enrich category
Method signatures and docstrings:
- def create(self, vals): create operation @return: super create() method
- def unlink(self): delete the enrich category record if record in draft state, and create log message ... | Implement the Python class `enrich_category` described below.
Class description:
To manage enrich category
Method signatures and docstrings:
- def create(self, vals): create operation @return: super create() method
- def unlink(self): delete the enrich category record if record in draft state, and create log message ... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class enrich_category:
"""To manage enrich category"""
def create(self, vals):
"""create operation @return: super create() method"""
<|body_0|>
def unlink(self):
"""delete the enrich category record if record in draft state, and create log message to the deleted record... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class enrich_category:
"""To manage enrich category"""
def create(self, vals):
"""create operation @return: super create() method"""
if 'type' in vals:
if vals['type'] == 'sol_special':
vals['current_amount'] = vals['amount']
return super(enrich_category, sel... | the_stack_v2_python_sparse | v_11/EBS-SVN/branches/ebs/enrich/models/enrich.py | musabahmed/baba | train | 0 |
1e4f9bbdb4a588afbde1174286cd83b793bc9738 | [
"self.n_estimators = n_estimators\nself.random = random\nself.split = split\nself.meta_model = list(map(lambda x: copy.deepcopy(meta_model), range(n_estimators)))\nself.model = model",
"dataset_blend_feature = np.zeros((x_pred.shape[0], self.n_estimators))\nfor index, estimator in enumerate(self.meta_model):\n ... | <|body_start_0|>
self.n_estimators = n_estimators
self.random = random
self.split = split
self.meta_model = list(map(lambda x: copy.deepcopy(meta_model), range(n_estimators)))
self.model = model
<|end_body_0|>
<|body_start_1|>
dataset_blend_feature = np.zeros((x_pred.sha... | Stacking | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stacking:
def __init__(self, n_estimators, meta_model, model, split=0.8, random=0):
""":param n_estimators: 元模型的数量 :param random: 随机数种子 :param split: 训练集和测试集分割比例,训练集用于元模型进行训练,测试集用于元模型生成给决策模型的数据"""
<|body_0|>
def predict(self, x_pred):
"""把元模型的输出作为最终模型的特征 :param x_pre... | stack_v2_sparse_classes_36k_train_015809 | 2,589 | no_license | [
{
"docstring": ":param n_estimators: 元模型的数量 :param random: 随机数种子 :param split: 训练集和测试集分割比例,训练集用于元模型进行训练,测试集用于元模型生成给决策模型的数据",
"name": "__init__",
"signature": "def __init__(self, n_estimators, meta_model, model, split=0.8, random=0)"
},
{
"docstring": "把元模型的输出作为最终模型的特征 :param x_pred: 原始数据 :return... | 3 | stack_v2_sparse_classes_30k_train_020842 | Implement the Python class `Stacking` described below.
Class description:
Implement the Stacking class.
Method signatures and docstrings:
- def __init__(self, n_estimators, meta_model, model, split=0.8, random=0): :param n_estimators: 元模型的数量 :param random: 随机数种子 :param split: 训练集和测试集分割比例,训练集用于元模型进行训练,测试集用于元模型生成给决策模型的... | Implement the Python class `Stacking` described below.
Class description:
Implement the Stacking class.
Method signatures and docstrings:
- def __init__(self, n_estimators, meta_model, model, split=0.8, random=0): :param n_estimators: 元模型的数量 :param random: 随机数种子 :param split: 训练集和测试集分割比例,训练集用于元模型进行训练,测试集用于元模型生成给决策模型的... | 1e8d30add10ae46043b76e664e4250a3e2b22e3f | <|skeleton|>
class Stacking:
def __init__(self, n_estimators, meta_model, model, split=0.8, random=0):
""":param n_estimators: 元模型的数量 :param random: 随机数种子 :param split: 训练集和测试集分割比例,训练集用于元模型进行训练,测试集用于元模型生成给决策模型的数据"""
<|body_0|>
def predict(self, x_pred):
"""把元模型的输出作为最终模型的特征 :param x_pre... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Stacking:
def __init__(self, n_estimators, meta_model, model, split=0.8, random=0):
""":param n_estimators: 元模型的数量 :param random: 随机数种子 :param split: 训练集和测试集分割比例,训练集用于元模型进行训练,测试集用于元模型生成给决策模型的数据"""
self.n_estimators = n_estimators
self.random = random
self.split = split
... | the_stack_v2_python_sparse | ensemble_learning/algorithm/stacking.py | cherryMonth/machine_learning | train | 2 | |
b0ae18193055e40a5d1cdedc0db4ad428a7cc9c8 | [
"def error(msg):\n return FetchResponse(status=FetchResponse.Status.ERROR, error_message=msg)\nhash_algo = _HASH_ALGO_MAPPING[request.hash_algo]\nif not impl.is_valid_hash_digest(hash_algo, request.file_hash):\n return error('Invalid hash digest format')\nservice = impl.get_cas_service()\nif service is None o... | <|body_start_0|>
def error(msg):
return FetchResponse(status=FetchResponse.Status.ERROR, error_message=msg)
hash_algo = _HASH_ALGO_MAPPING[request.hash_algo]
if not impl.is_valid_hash_digest(hash_algo, request.file_hash):
return error('Invalid hash digest format')
... | Content addressable storage API. | CASServiceApi | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CASServiceApi:
"""Content addressable storage API."""
def fetch(self, request):
"""Returns a signed URL that can be used to fetch an object."""
<|body_0|>
def begin_upload(self, request):
"""Initiates an upload operation if file is missing. Once initiated the cli... | stack_v2_sparse_classes_36k_train_015810 | 8,463 | permissive | [
{
"docstring": "Returns a signed URL that can be used to fetch an object.",
"name": "fetch",
"signature": "def fetch(self, request)"
},
{
"docstring": "Initiates an upload operation if file is missing. Once initiated the client is then responsible for uploading the file to temporary location (re... | 3 | stack_v2_sparse_classes_30k_train_019325 | Implement the Python class `CASServiceApi` described below.
Class description:
Content addressable storage API.
Method signatures and docstrings:
- def fetch(self, request): Returns a signed URL that can be used to fetch an object.
- def begin_upload(self, request): Initiates an upload operation if file is missing. O... | Implement the Python class `CASServiceApi` described below.
Class description:
Content addressable storage API.
Method signatures and docstrings:
- def fetch(self, request): Returns a signed URL that can be used to fetch an object.
- def begin_upload(self, request): Initiates an upload operation if file is missing. O... | 09064105713603f7bf75c772e8354800a1bfa256 | <|skeleton|>
class CASServiceApi:
"""Content addressable storage API."""
def fetch(self, request):
"""Returns a signed URL that can be used to fetch an object."""
<|body_0|>
def begin_upload(self, request):
"""Initiates an upload operation if file is missing. Once initiated the cli... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CASServiceApi:
"""Content addressable storage API."""
def fetch(self, request):
"""Returns a signed URL that can be used to fetch an object."""
def error(msg):
return FetchResponse(status=FetchResponse.Status.ERROR, error_message=msg)
hash_algo = _HASH_ALGO_MAPPING[req... | the_stack_v2_python_sparse | appengine/chrome_infra_packages/cas/api.py | mcgreevy/chromium-infra | train | 1 |
39365c2c3046c14a833e4408ffa54e4112c3a9bf | [
"self.n_head = n_head\nself.d_k = self.d_v = d_k = d_v = d_model // n_head\nself.dropout = dropout\nvs_layer = tf.keras.layers.Dense(d_v, use_bias=False)\nself.qs_layers = [_dense_layer(d_k, use_bias=False) for _ in range(n_head)]\nself.ks_layers = [_dense_layer(d_k, use_bias=False) for _ in range(n_head)]\nself.vs... | <|body_start_0|>
self.n_head = n_head
self.d_k = self.d_v = d_k = d_v = d_model // n_head
self.dropout = dropout
vs_layer = tf.keras.layers.Dense(d_v, use_bias=False)
self.qs_layers = [_dense_layer(d_k, use_bias=False) for _ in range(n_head)]
self.ks_layers = [_dense_laye... | Defines interpretable multi-head attention layer. Attributes: n_head: The number of heads for attention layer. d_k: The key and query dimensionality per head. d_v: The value dimensionality. dropout: The dropout rate to apply qs_layers: The list of query layers across heads. ks_layers: The list of key layers across head... | InterpretableMultiHeadAttention | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterpretableMultiHeadAttention:
"""Defines interpretable multi-head attention layer. Attributes: n_head: The number of heads for attention layer. d_k: The key and query dimensionality per head. d_v: The value dimensionality. dropout: The dropout rate to apply qs_layers: The list of query layers ... | stack_v2_sparse_classes_36k_train_015811 | 19,798 | permissive | [
{
"docstring": "Initialises layer. Args: n_head: The number of heads. d_model: The dimensionality of TFT state. dropout: The dropout rate to be applied to the output.",
"name": "__init__",
"signature": "def __init__(self, n_head, d_model, dropout)"
},
{
"docstring": "Applies interpretable multih... | 2 | stack_v2_sparse_classes_30k_train_007657 | Implement the Python class `InterpretableMultiHeadAttention` described below.
Class description:
Defines interpretable multi-head attention layer. Attributes: n_head: The number of heads for attention layer. d_k: The key and query dimensionality per head. d_v: The value dimensionality. dropout: The dropout rate to app... | Implement the Python class `InterpretableMultiHeadAttention` described below.
Class description:
Defines interpretable multi-head attention layer. Attributes: n_head: The number of heads for attention layer. d_k: The key and query dimensionality per head. d_v: The value dimensionality. dropout: The dropout rate to app... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class InterpretableMultiHeadAttention:
"""Defines interpretable multi-head attention layer. Attributes: n_head: The number of heads for attention layer. d_k: The key and query dimensionality per head. d_v: The value dimensionality. dropout: The dropout rate to apply qs_layers: The list of query layers ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InterpretableMultiHeadAttention:
"""Defines interpretable multi-head attention layer. Attributes: n_head: The number of heads for attention layer. d_k: The key and query dimensionality per head. d_v: The value dimensionality. dropout: The dropout rate to apply qs_layers: The list of query layers across heads.... | the_stack_v2_python_sparse | saf/models/tft_layers.py | Jimmy-INL/google-research | train | 1 |
d6e6a87fbd68bb7fc0dcafc5bbeac23b90f5de19 | [
"if page_url is None or html_cont is None:\n return\nsoup = BeautifulSoup(html_cont, 'lxml', from_encoding='utf-8')\nnew_data = self._get_new_data(soup)\nreturn new_data",
"data = []\nfor mulu in soup.find_all(class_='mulu'):\n h2 = mulu.find('h2')\n if h2 != None:\n h2_title = h2.string\n ... | <|body_start_0|>
if page_url is None or html_cont is None:
return
soup = BeautifulSoup(html_cont, 'lxml', from_encoding='utf-8')
new_data = self._get_new_data(soup)
return new_data
<|end_body_0|>
<|body_start_1|>
data = []
for mulu in soup.find_all(class_='mu... | HtmlParse | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HtmlParse:
def parser(self, page_url, html_cont):
"""用于解析网页内容,抽取url和数据 :param page_url: 下载页面的url :param html_cont: 下载网页的内容 :return:"""
<|body_0|>
def _get_new_data(self, soup):
"""抽取有效数据 :param page_url: 下载页面的url :param soup: soup :return: 返回有效数据{}"""
<|body_... | stack_v2_sparse_classes_36k_train_015812 | 1,926 | no_license | [
{
"docstring": "用于解析网页内容,抽取url和数据 :param page_url: 下载页面的url :param html_cont: 下载网页的内容 :return:",
"name": "parser",
"signature": "def parser(self, page_url, html_cont)"
},
{
"docstring": "抽取有效数据 :param page_url: 下载页面的url :param soup: soup :return: 返回有效数据{}",
"name": "_get_new_data",
"sign... | 2 | stack_v2_sparse_classes_30k_train_021018 | Implement the Python class `HtmlParse` described below.
Class description:
Implement the HtmlParse class.
Method signatures and docstrings:
- def parser(self, page_url, html_cont): 用于解析网页内容,抽取url和数据 :param page_url: 下载页面的url :param html_cont: 下载网页的内容 :return:
- def _get_new_data(self, soup): 抽取有效数据 :param page_url: 下... | Implement the Python class `HtmlParse` described below.
Class description:
Implement the HtmlParse class.
Method signatures and docstrings:
- def parser(self, page_url, html_cont): 用于解析网页内容,抽取url和数据 :param page_url: 下载页面的url :param html_cont: 下载网页的内容 :return:
- def _get_new_data(self, soup): 抽取有效数据 :param page_url: 下... | 82cd7e39c2accb5f123769c16e66d7234e9a4121 | <|skeleton|>
class HtmlParse:
def parser(self, page_url, html_cont):
"""用于解析网页内容,抽取url和数据 :param page_url: 下载页面的url :param html_cont: 下载网页的内容 :return:"""
<|body_0|>
def _get_new_data(self, soup):
"""抽取有效数据 :param page_url: 下载页面的url :param soup: soup :return: 返回有效数据{}"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HtmlParse:
def parser(self, page_url, html_cont):
"""用于解析网页内容,抽取url和数据 :param page_url: 下载页面的url :param html_cont: 下载网页的内容 :return:"""
if page_url is None or html_cont is None:
return
soup = BeautifulSoup(html_cont, 'lxml', from_encoding='utf-8')
new_data = self._ge... | the_stack_v2_python_sparse | Internet worm/data_store_without_db/daomu_plus/HtmlParse.py | Katherinelove/python | train | 0 | |
e787cae8165a331813e1c1fa881c09b0f0895231 | [
"result = ''\nfor i, (numeric, roman) in enumerate(TO_ROMAN):\n current = number // numeric\n if current:\n if str(number)[0] == '4':\n result += roman + TO_ROMAN[i - 1][1]\n number -= numeric + TO_ROMAN[i - 1][0]\n elif str(number)[0] == '9':\n result += TO_ROMA... | <|body_start_0|>
result = ''
for i, (numeric, roman) in enumerate(TO_ROMAN):
current = number // numeric
if current:
if str(number)[0] == '4':
result += roman + TO_ROMAN[i - 1][1]
number -= numeric + TO_ROMAN[i - 1][0]
... | Roman-Numeric and Numeric-Roman converter | RomanNumerals | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RomanNumerals:
"""Roman-Numeric and Numeric-Roman converter"""
def to_roman(number):
"""Converts numeric to roman Args: number (int): Numeric Returns: str: Roman Examples: >>> RomanNumerals.to_roman(8) 'VIII'"""
<|body_0|>
def from_roman(number):
"""Converts roma... | stack_v2_sparse_classes_36k_train_015813 | 2,597 | no_license | [
{
"docstring": "Converts numeric to roman Args: number (int): Numeric Returns: str: Roman Examples: >>> RomanNumerals.to_roman(8) 'VIII'",
"name": "to_roman",
"signature": "def to_roman(number)"
},
{
"docstring": "Converts roman to numeric Args: number (str): Roman Returns: int: Numeric Examples... | 2 | stack_v2_sparse_classes_30k_train_007956 | Implement the Python class `RomanNumerals` described below.
Class description:
Roman-Numeric and Numeric-Roman converter
Method signatures and docstrings:
- def to_roman(number): Converts numeric to roman Args: number (int): Numeric Returns: str: Roman Examples: >>> RomanNumerals.to_roman(8) 'VIII'
- def from_roman(n... | Implement the Python class `RomanNumerals` described below.
Class description:
Roman-Numeric and Numeric-Roman converter
Method signatures and docstrings:
- def to_roman(number): Converts numeric to roman Args: number (int): Numeric Returns: str: Roman Examples: >>> RomanNumerals.to_roman(8) 'VIII'
- def from_roman(n... | bcfd15aba49f87c0a64cf840e96df06ef5ec9162 | <|skeleton|>
class RomanNumerals:
"""Roman-Numeric and Numeric-Roman converter"""
def to_roman(number):
"""Converts numeric to roman Args: number (int): Numeric Returns: str: Roman Examples: >>> RomanNumerals.to_roman(8) 'VIII'"""
<|body_0|>
def from_roman(number):
"""Converts roma... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RomanNumerals:
"""Roman-Numeric and Numeric-Roman converter"""
def to_roman(number):
"""Converts numeric to roman Args: number (int): Numeric Returns: str: Roman Examples: >>> RomanNumerals.to_roman(8) 'VIII'"""
result = ''
for i, (numeric, roman) in enumerate(TO_ROMAN):
... | the_stack_v2_python_sparse | python2/kyu_4/roman_numerals_helper.py | wangerde/codewars | train | 0 |
d2d592d3ecb224608f13f4e89ae27264652d4913 | [
"count = 0\nflag = 1\nwhile flag <= n:\n if n & flag:\n count += 1\n flag = flag << 1\n print(flag)\nprint(count)\nreturn count",
"count = 0\nwhile n:\n count += 1\n n = n - 1 & n\nreturn count"
] | <|body_start_0|>
count = 0
flag = 1
while flag <= n:
if n & flag:
count += 1
flag = flag << 1
print(flag)
print(count)
return count
<|end_body_0|>
<|body_start_1|>
count = 0
while n:
count += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hammingWeight(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def hammingWeight2(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
count = 0
flag = 1
while flag <= n:
... | stack_v2_sparse_classes_36k_train_015814 | 606 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "hammingWeight",
"signature": "def hammingWeight(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "hammingWeight2",
"signature": "def hammingWeight2(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009642 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hammingWeight(self, n): :type n: int :rtype: int
- def hammingWeight2(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hammingWeight(self, n): :type n: int :rtype: int
- def hammingWeight2(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def hammingWeight(self, n):
... | 38eec6f07fdc16658372490cd8c68dcb3d88a77f | <|skeleton|>
class Solution:
def hammingWeight(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def hammingWeight2(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def hammingWeight(self, n):
""":type n: int :rtype: int"""
count = 0
flag = 1
while flag <= n:
if n & flag:
count += 1
flag = flag << 1
print(flag)
print(count)
return count
def hammingWeight2(se... | the_stack_v2_python_sparse | offer/15.py | gebijiaxiaowang/leetcode | train | 0 | |
a5b0584ea5548fdd57e313ef050bec4723fb3293 | [
"result = []\nfor c in range(C):\n for r in range(R):\n result.append([abs(r - r0), abs(c - c0)])\nreturn result",
"from collections import defaultdict\ndistance = defaultdict(list)\nfor r in range(R):\n for c in range(C):\n distance[abs(r - r0) + abs(c - c0)].append([r, c])\nresult = []\nfor ... | <|body_start_0|>
result = []
for c in range(C):
for r in range(R):
result.append([abs(r - r0), abs(c - c0)])
return result
<|end_body_0|>
<|body_start_1|>
from collections import defaultdict
distance = defaultdict(list)
for r in range(R):
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _allCellsDistOrder(self, R, C, r0, c0):
""":type R: int :type C: int :type r0: int :type c0: int :rtype: List[List[int]]"""
<|body_0|>
def allCellsDistOrder(self, R, C, r0, c0):
""":type R: int :type C: int :type r0: int :type c0: int :rtype: List[List[... | stack_v2_sparse_classes_36k_train_015815 | 2,764 | permissive | [
{
"docstring": ":type R: int :type C: int :type r0: int :type c0: int :rtype: List[List[int]]",
"name": "_allCellsDistOrder",
"signature": "def _allCellsDistOrder(self, R, C, r0, c0)"
},
{
"docstring": ":type R: int :type C: int :type r0: int :type c0: int :rtype: List[List[int]]",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_007322 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _allCellsDistOrder(self, R, C, r0, c0): :type R: int :type C: int :type r0: int :type c0: int :rtype: List[List[int]]
- def allCellsDistOrder(self, R, C, r0, c0): :type R: in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _allCellsDistOrder(self, R, C, r0, c0): :type R: int :type C: int :type r0: int :type c0: int :rtype: List[List[int]]
- def allCellsDistOrder(self, R, C, r0, c0): :type R: in... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _allCellsDistOrder(self, R, C, r0, c0):
""":type R: int :type C: int :type r0: int :type c0: int :rtype: List[List[int]]"""
<|body_0|>
def allCellsDistOrder(self, R, C, r0, c0):
""":type R: int :type C: int :type r0: int :type c0: int :rtype: List[List[... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def _allCellsDistOrder(self, R, C, r0, c0):
""":type R: int :type C: int :type r0: int :type c0: int :rtype: List[List[int]]"""
result = []
for c in range(C):
for r in range(R):
result.append([abs(r - r0), abs(c - c0)])
return result
d... | the_stack_v2_python_sparse | 1030.matrix-cells-in-distance-order.py | windard/leeeeee | train | 0 | |
f0fdc703bec438b7888bd3eda6197aa328da1791 | [
"query = TimesQuery(model, identity)\ntimes = query.fetch()\nreturn times",
"times = TimesChangedSerializer(data=request.data)\nif not times.is_valid():\n raise ValidationError(times.errors)\nvd = times.validated_data\nquery = Query(vd.get('model')).identity(vd.get('identity')).time(vd.get('time'))\nrecords = ... | <|body_start_0|>
query = TimesQuery(model, identity)
times = query.fetch()
return times
<|end_body_0|>
<|body_start_1|>
times = TimesChangedSerializer(data=request.data)
if not times.is_valid():
raise ValidationError(times.errors)
vd = times.validated_data
... | View set for searching, viewing objects. | ObjectViewSet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectViewSet:
"""View set for searching, viewing objects."""
def _times(self, model, identity):
"""Get times a specific instance of a model has changed. :param model: Name of the model :type model: str :param identity: Identity of the instance :type identity: str :returns: List of t... | stack_v2_sparse_classes_36k_train_015816 | 9,625 | permissive | [
{
"docstring": "Get times a specific instance of a model has changed. :param model: Name of the model :type model: str :param identity: Identity of the instance :type identity: str :returns: List of times the instance has changed. :rtype: list",
"name": "_times",
"signature": "def _times(self, model, id... | 3 | stack_v2_sparse_classes_30k_train_019395 | Implement the Python class `ObjectViewSet` described below.
Class description:
View set for searching, viewing objects.
Method signatures and docstrings:
- def _times(self, model, identity): Get times a specific instance of a model has changed. :param model: Name of the model :type model: str :param identity: Identit... | Implement the Python class `ObjectViewSet` described below.
Class description:
View set for searching, viewing objects.
Method signatures and docstrings:
- def _times(self, model, identity): Get times a specific instance of a model has changed. :param model: Name of the model :type model: str :param identity: Identit... | aaab76706c8268d3ff3e87c275baee9dd4714314 | <|skeleton|>
class ObjectViewSet:
"""View set for searching, viewing objects."""
def _times(self, model, identity):
"""Get times a specific instance of a model has changed. :param model: Name of the model :type model: str :param identity: Identity of the instance :type identity: str :returns: List of t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObjectViewSet:
"""View set for searching, viewing objects."""
def _times(self, model, identity):
"""Get times a specific instance of a model has changed. :param model: Name of the model :type model: str :param identity: Identity of the instance :type identity: str :returns: List of times the inst... | the_stack_v2_python_sparse | web/api/views.py | rcbops/FleetDeploymentReporting | train | 1 |
3911f7185aac3929ed43dc52ff80c3b894a367ee | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.win32LobAppFileSystemRule'.casefold():\n ... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | A base complex type to store the detection or requirement rule data for a Win32 LOB app. | Win32LobAppRule | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Win32LobAppRule:
"""A base complex type to store the detection or requirement rule data for a Win32 LOB app."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Win32LobAppRule:
"""Creates a new instance of the appropriate class based on discriminator valu... | stack_v2_sparse_classes_36k_train_015817 | 4,926 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Win32LobAppRule",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_val... | 3 | stack_v2_sparse_classes_30k_train_001908 | Implement the Python class `Win32LobAppRule` described below.
Class description:
A base complex type to store the detection or requirement rule data for a Win32 LOB app.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Win32LobAppRule: Creates a new inst... | Implement the Python class `Win32LobAppRule` described below.
Class description:
A base complex type to store the detection or requirement rule data for a Win32 LOB app.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Win32LobAppRule: Creates a new inst... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class Win32LobAppRule:
"""A base complex type to store the detection or requirement rule data for a Win32 LOB app."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Win32LobAppRule:
"""Creates a new instance of the appropriate class based on discriminator valu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Win32LobAppRule:
"""A base complex type to store the detection or requirement rule data for a Win32 LOB app."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Win32LobAppRule:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse... | the_stack_v2_python_sparse | msgraph/generated/models/win32_lob_app_rule.py | microsoftgraph/msgraph-sdk-python | train | 135 |
d0a255411a230af0281973e113be18237613bbdd | [
"dev = self.selectedDevice(c)\nif voltage is not None:\n yield dev.setVoltage(voltage)\nreturnValue(dev.voltage)",
"dev = self.selectedDevice(c)\nif current is not None:\n yield dev.setCurrent(current)\nreturnValue(dev.current)",
"dev = self.selectedDevice(c)\nif output is not None:\n yield dev.setOutp... | <|body_start_0|>
dev = self.selectedDevice(c)
if voltage is not None:
yield dev.setVoltage(voltage)
returnValue(dev.voltage)
<|end_body_0|>
<|body_start_1|>
dev = self.selectedDevice(c)
if current is not None:
yield dev.setCurrent(current)
returnV... | Provides basic CW control for Agilent Signal Generators | AgilentServer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AgilentServer:
"""Provides basic CW control for Agilent Signal Generators"""
def voltage(self, c, voltage=None):
"""Get or set the CW frequency."""
<|body_0|>
def current(self, c, current=None):
"""Get or set the CW frequency."""
<|body_1|>
def outpu... | stack_v2_sparse_classes_36k_train_015818 | 3,497 | no_license | [
{
"docstring": "Get or set the CW frequency.",
"name": "voltage",
"signature": "def voltage(self, c, voltage=None)"
},
{
"docstring": "Get or set the CW frequency.",
"name": "current",
"signature": "def current(self, c, current=None)"
},
{
"docstring": "Get or set the output stat... | 3 | stack_v2_sparse_classes_30k_test_000546 | Implement the Python class `AgilentServer` described below.
Class description:
Provides basic CW control for Agilent Signal Generators
Method signatures and docstrings:
- def voltage(self, c, voltage=None): Get or set the CW frequency.
- def current(self, c, current=None): Get or set the CW frequency.
- def output_st... | Implement the Python class `AgilentServer` described below.
Class description:
Provides basic CW control for Agilent Signal Generators
Method signatures and docstrings:
- def voltage(self, c, voltage=None): Get or set the CW frequency.
- def current(self, c, current=None): Get or set the CW frequency.
- def output_st... | c6f3bd71be51a6e300346e5c2765e2ef7502ebd6 | <|skeleton|>
class AgilentServer:
"""Provides basic CW control for Agilent Signal Generators"""
def voltage(self, c, voltage=None):
"""Get or set the CW frequency."""
<|body_0|>
def current(self, c, current=None):
"""Get or set the CW frequency."""
<|body_1|>
def outpu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AgilentServer:
"""Provides basic CW control for Agilent Signal Generators"""
def voltage(self, c, voltage=None):
"""Get or set the CW frequency."""
dev = self.selectedDevice(c)
if voltage is not None:
yield dev.setVoltage(voltage)
returnValue(dev.voltage)
... | the_stack_v2_python_sparse | gpibservers/agilent_N5747A.py | Muuuun/Haeffner-Lab-LabRAD-Tools | train | 0 |
1ed2473611bd5fcb87a321c383f9d256d068ec83 | [
"self.setup_connection(host=mgmt_ip, user=username, passwd=password)\nchanges = {}\nwith Device(conn=self.conn, auth=self.auth) as device:\n self.validate_supports_rbridge(device, rbridge_id=rbridge_id)\n self.logger.info('successfully connected to %s to Delete VRRPe group', self.host)\n changes['pre_check... | <|body_start_0|>
self.setup_connection(host=mgmt_ip, user=username, passwd=password)
changes = {}
with Device(conn=self.conn, auth=self.auth) as device:
self.validate_supports_rbridge(device, rbridge_id=rbridge_id)
self.logger.info('successfully connected to %s to Delete ... | Implements the logic to delete vrrpe configuration on VDX and SLX devices . This action achieves the below functionality 1.Verify whether the vrrpe group exists in the switch or not. 2.Delete vrrpe group on the vlan | DeleteVrrpe | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteVrrpe:
"""Implements the logic to delete vrrpe configuration on VDX and SLX devices . This action achieves the below functionality 1.Verify whether the vrrpe group exists in the switch or not. 2.Delete vrrpe group on the vlan"""
def run(self, mgmt_ip, username, password, vlan_id, rbrid... | stack_v2_sparse_classes_36k_train_015819 | 5,440 | permissive | [
{
"docstring": "Run helper methods to implement the desired state.",
"name": "run",
"signature": "def run(self, mgmt_ip, username, password, vlan_id, rbridge_id, vrrpe_group, ip_version)"
},
{
"docstring": "validate vlan_id and ve",
"name": "_validate_if_ve_exists",
"signature": "def _va... | 3 | stack_v2_sparse_classes_30k_train_016787 | Implement the Python class `DeleteVrrpe` described below.
Class description:
Implements the logic to delete vrrpe configuration on VDX and SLX devices . This action achieves the below functionality 1.Verify whether the vrrpe group exists in the switch or not. 2.Delete vrrpe group on the vlan
Method signatures and doc... | Implement the Python class `DeleteVrrpe` described below.
Class description:
Implements the logic to delete vrrpe configuration on VDX and SLX devices . This action achieves the below functionality 1.Verify whether the vrrpe group exists in the switch or not. 2.Delete vrrpe group on the vlan
Method signatures and doc... | 9eb85b0c29c0d18a10bc27b173a97a6e2a0275b1 | <|skeleton|>
class DeleteVrrpe:
"""Implements the logic to delete vrrpe configuration on VDX and SLX devices . This action achieves the below functionality 1.Verify whether the vrrpe group exists in the switch or not. 2.Delete vrrpe group on the vlan"""
def run(self, mgmt_ip, username, password, vlan_id, rbrid... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeleteVrrpe:
"""Implements the logic to delete vrrpe configuration on VDX and SLX devices . This action achieves the below functionality 1.Verify whether the vrrpe group exists in the switch or not. 2.Delete vrrpe group on the vlan"""
def run(self, mgmt_ip, username, password, vlan_id, rbridge_id, vrrpe_... | the_stack_v2_python_sparse | actions/delete_vrrpe.py | nmaludy/stackstorm-network_essentials | train | 0 |
123e5b5c1b11e053571532f5b77d82d1821601e2 | [
"freshCnt = 0\nfor r in grid:\n freshCnt += r.count(1)\nif freshCnt == 0:\n return 0\nres = 0\nwhile freshCnt != 0:\n grid, rottenCnt = self.after1min(grid)\n if rottenCnt == 0:\n return -1\n res, freshCnt = (res + 1, freshCnt - rottenCnt)\nreturn res",
"rot = set()\nfor i in range(len(grid)... | <|body_start_0|>
freshCnt = 0
for r in grid:
freshCnt += r.count(1)
if freshCnt == 0:
return 0
res = 0
while freshCnt != 0:
grid, rottenCnt = self.after1min(grid)
if rottenCnt == 0:
return -1
res, freshCn... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def orangesRotting(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_0|>
def after1min(self, grid):
"""update the grid and return the rotten oranges in next min"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
freshCnt = 0
... | stack_v2_sparse_classes_36k_train_015820 | 1,586 | no_license | [
{
"docstring": ":type grid: List[List[int]] :rtype: int",
"name": "orangesRotting",
"signature": "def orangesRotting(self, grid)"
},
{
"docstring": "update the grid and return the rotten oranges in next min",
"name": "after1min",
"signature": "def after1min(self, grid)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def orangesRotting(self, grid): :type grid: List[List[int]] :rtype: int
- def after1min(self, grid): update the grid and return the rotten oranges in next min | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def orangesRotting(self, grid): :type grid: List[List[int]] :rtype: int
- def after1min(self, grid): update the grid and return the rotten oranges in next min
<|skeleton|>
class... | b4da922c4e8406c486760639b71e3ec50283ca43 | <|skeleton|>
class Solution:
def orangesRotting(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_0|>
def after1min(self, grid):
"""update the grid and return the rotten oranges in next min"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def orangesRotting(self, grid):
""":type grid: List[List[int]] :rtype: int"""
freshCnt = 0
for r in grid:
freshCnt += r.count(1)
if freshCnt == 0:
return 0
res = 0
while freshCnt != 0:
grid, rottenCnt = self.after1mi... | the_stack_v2_python_sparse | current_session/python/994.py | YJL33/LeetCode | train | 3 | |
158a4170808b14d6834fa11fd09f319ba613d1fe | [
"self.persons = persons\nself.times = times\nself.length = len(self.persons)\nmapping = collections.defaultdict(int)\nself.status = []\nprev = [-1, 0]\nfor index, person in enumerate(self.persons):\n mapping[person] += 1\n if mapping[person] > prev[1]:\n self.status.append(person)\n prev[0], pre... | <|body_start_0|>
self.persons = persons
self.times = times
self.length = len(self.persons)
mapping = collections.defaultdict(int)
self.status = []
prev = [-1, 0]
for index, person in enumerate(self.persons):
mapping[person] += 1
if mapping[... | TopVotedCandidate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopVotedCandidate:
def __init__(self, persons, times):
""":type persons: List[int] :type times: List[int]"""
<|body_0|>
def q(self, t):
""":type t: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.persons = persons
self.t... | stack_v2_sparse_classes_36k_train_015821 | 1,436 | no_license | [
{
"docstring": ":type persons: List[int] :type times: List[int]",
"name": "__init__",
"signature": "def __init__(self, persons, times)"
},
{
"docstring": ":type t: int :rtype: int",
"name": "q",
"signature": "def q(self, t)"
}
] | 2 | null | Implement the Python class `TopVotedCandidate` described below.
Class description:
Implement the TopVotedCandidate class.
Method signatures and docstrings:
- def __init__(self, persons, times): :type persons: List[int] :type times: List[int]
- def q(self, t): :type t: int :rtype: int | Implement the Python class `TopVotedCandidate` described below.
Class description:
Implement the TopVotedCandidate class.
Method signatures and docstrings:
- def __init__(self, persons, times): :type persons: List[int] :type times: List[int]
- def q(self, t): :type t: int :rtype: int
<|skeleton|>
class TopVotedCandi... | 238995bd23c8a6c40c6035890e94baa2473d4bbc | <|skeleton|>
class TopVotedCandidate:
def __init__(self, persons, times):
""":type persons: List[int] :type times: List[int]"""
<|body_0|>
def q(self, t):
""":type t: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TopVotedCandidate:
def __init__(self, persons, times):
""":type persons: List[int] :type times: List[int]"""
self.persons = persons
self.times = times
self.length = len(self.persons)
mapping = collections.defaultdict(int)
self.status = []
prev = [-1, 0]
... | the_stack_v2_python_sparse | problems/N911_Online_Election.py | wan-catherine/Leetcode | train | 5 | |
400159ce61c454be91a7494025a7fde5424784cc | [
"self.user = User.objects.create_user(username='test', password='testpassword')\nself.client.login(username='test', password='testpassword')\npage = self.client.get('/profile/')\nself.assertTemplateUsed('profile.html')\nself.assertTrue(hasattr(self.user, 'userprofile'), True)\nself.assertTrue(hasattr(self.user.user... | <|body_start_0|>
self.user = User.objects.create_user(username='test', password='testpassword')
self.client.login(username='test', password='testpassword')
page = self.client.get('/profile/')
self.assertTemplateUsed('profile.html')
self.assertTrue(hasattr(self.user, 'userprofile'... | TestProfilePage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestProfilePage:
def test_profile_page(self):
"""testing profile page and if user model gets a profile as per extended model"""
<|body_0|>
def test_update_profile_updates_correctly(self):
"""testing edit profile"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_015822 | 8,082 | no_license | [
{
"docstring": "testing profile page and if user model gets a profile as per extended model",
"name": "test_profile_page",
"signature": "def test_profile_page(self)"
},
{
"docstring": "testing edit profile",
"name": "test_update_profile_updates_correctly",
"signature": "def test_update_p... | 2 | stack_v2_sparse_classes_30k_train_009655 | Implement the Python class `TestProfilePage` described below.
Class description:
Implement the TestProfilePage class.
Method signatures and docstrings:
- def test_profile_page(self): testing profile page and if user model gets a profile as per extended model
- def test_update_profile_updates_correctly(self): testing ... | Implement the Python class `TestProfilePage` described below.
Class description:
Implement the TestProfilePage class.
Method signatures and docstrings:
- def test_profile_page(self): testing profile page and if user model gets a profile as per extended model
- def test_update_profile_updates_correctly(self): testing ... | c25fe47d386357d929242e2a6dd36666328195b0 | <|skeleton|>
class TestProfilePage:
def test_profile_page(self):
"""testing profile page and if user model gets a profile as per extended model"""
<|body_0|>
def test_update_profile_updates_correctly(self):
"""testing edit profile"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestProfilePage:
def test_profile_page(self):
"""testing profile page and if user model gets a profile as per extended model"""
self.user = User.objects.create_user(username='test', password='testpassword')
self.client.login(username='test', password='testpassword')
page = self... | the_stack_v2_python_sparse | accounts/tests.py | SalvatoreFiengo/myecommerce | train | 0 | |
957d1156ec560bbec583cde8a123231ef0151415 | [
"res = {}\nfor vehi in self.browse(cr, uid, ids, context=context):\n res[vehi['id']] = len(vehi.vehi_participants_ids)\nreturn res",
"if context is None:\n context = {}\nif context.get('name'):\n transport_obj = self.pool.get('student.transport')\n transport_data = transport_obj.browse(cr, uid, contex... | <|body_start_0|>
res = {}
for vehi in self.browse(cr, uid, ids, context=context):
res[vehi['id']] = len(vehi.vehi_participants_ids)
return res
<|end_body_0|>
<|body_start_1|>
if context is None:
context = {}
if context.get('name'):
transport_o... | transport_vehicle | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class transport_vehicle:
def _participants(self, cr, uid, ids, name, vals, context=None):
"""This method calculate total participants @param self : Object Pointer @param cr : Database Cursor @param uid : Current Logged in User @param ids : Current Records @param name : Functional field's name ... | stack_v2_sparse_classes_36k_train_015823 | 21,327 | no_license | [
{
"docstring": "This method calculate total participants @param self : Object Pointer @param cr : Database Cursor @param uid : Current Logged in User @param ids : Current Records @param name : Functional field's name @param vals : Other arguments @param context : standard Dictionary @return : Dictionary having ... | 2 | stack_v2_sparse_classes_30k_train_010270 | Implement the Python class `transport_vehicle` described below.
Class description:
Implement the transport_vehicle class.
Method signatures and docstrings:
- def _participants(self, cr, uid, ids, name, vals, context=None): This method calculate total participants @param self : Object Pointer @param cr : Database Curs... | Implement the Python class `transport_vehicle` described below.
Class description:
Implement the transport_vehicle class.
Method signatures and docstrings:
- def _participants(self, cr, uid, ids, name, vals, context=None): This method calculate total participants @param self : Object Pointer @param cr : Database Curs... | c5a5678379649ccdf57a9d55b09b30436428b430 | <|skeleton|>
class transport_vehicle:
def _participants(self, cr, uid, ids, name, vals, context=None):
"""This method calculate total participants @param self : Object Pointer @param cr : Database Cursor @param uid : Current Logged in User @param ids : Current Records @param name : Functional field's name ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class transport_vehicle:
def _participants(self, cr, uid, ids, name, vals, context=None):
"""This method calculate total participants @param self : Object Pointer @param cr : Database Cursor @param uid : Current Logged in User @param ids : Current Records @param name : Functional field's name @param vals : ... | the_stack_v2_python_sparse | education/school_transport/transport.py | adahra/addons | train | 1 | |
55068435c46ff3dd74862439b431d785c0d28311 | [
"x0, y0 = pos\nx1, x2 = (x0 - length / 2.0, x0 + length / 2.0)\ny1, y2 = (y0 - height, y0)\nself.cv = cv\nself.item = cv.create_rectangle(x1, y1, x2, y2, fill='#%02x%02x%02x' % colour)",
"x1, y1, x2, y2 = self.cv.coords(self.item)\nx0, y0 = ((x1 + x2) / 2, y2)\ndx, dy = (x - x0, y - y0)\nd = (dx ** 2 + dy ** 2) *... | <|body_start_0|>
x0, y0 = pos
x1, x2 = (x0 - length / 2.0, x0 + length / 2.0)
y1, y2 = (y0 - height, y0)
self.cv = cv
self.item = cv.create_rectangle(x1, y1, x2, y2, fill='#%02x%02x%02x' % colour)
<|end_body_0|>
<|body_start_1|>
x1, y1, x2, y2 = self.cv.coords(self.item)... | Movable Rectangle on a Tkinter Canvas | Disk | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Disk:
"""Movable Rectangle on a Tkinter Canvas"""
def __init__(self, cv, pos, length, height, colour):
"""creates disc on given Canvas cv at given position"""
<|body_0|>
def move_to(self, x, y, speed):
"""moves bottom center of disc to position (x,y). speed is in... | stack_v2_sparse_classes_36k_train_015824 | 7,720 | no_license | [
{
"docstring": "creates disc on given Canvas cv at given position",
"name": "__init__",
"signature": "def __init__(self, cv, pos, length, height, colour)"
},
{
"docstring": "moves bottom center of disc to position (x,y). speed is intended to assume values from 1 to 10",
"name": "move_to",
... | 2 | stack_v2_sparse_classes_30k_train_005412 | Implement the Python class `Disk` described below.
Class description:
Movable Rectangle on a Tkinter Canvas
Method signatures and docstrings:
- def __init__(self, cv, pos, length, height, colour): creates disc on given Canvas cv at given position
- def move_to(self, x, y, speed): moves bottom center of disc to positi... | Implement the Python class `Disk` described below.
Class description:
Movable Rectangle on a Tkinter Canvas
Method signatures and docstrings:
- def __init__(self, cv, pos, length, height, colour): creates disc on given Canvas cv at given position
- def move_to(self, x, y, speed): moves bottom center of disc to positi... | dd721e096f8445aee48e69c3a3ebf6501aecc95b | <|skeleton|>
class Disk:
"""Movable Rectangle on a Tkinter Canvas"""
def __init__(self, cv, pos, length, height, colour):
"""creates disc on given Canvas cv at given position"""
<|body_0|>
def move_to(self, x, y, speed):
"""moves bottom center of disc to position (x,y). speed is in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Disk:
"""Movable Rectangle on a Tkinter Canvas"""
def __init__(self, cv, pos, length, height, colour):
"""creates disc on given Canvas cv at given position"""
x0, y0 = pos
x1, x2 = (x0 - length / 2.0, x0 + length / 2.0)
y1, y2 = (y0 - height, y0)
self.cv = cv
... | the_stack_v2_python_sparse | image_misc/src/hanoi.py | aroberge/py-fun | train | 0 |
354417f419c182af3db025484e259a548b1764bb | [
"super(FocalLoss, self).__init__()\nassert use_sigmoid is True, 'Only sigmoid focal loss supported now.'\nself.use_sigmoid = use_sigmoid\nself.gamma = gamma\nself.alpha = alpha\nself.reduction = reduction\nself.loss_weight = loss_weight",
"assert reduction_override in (None, 'none', 'mean', 'sum')\nreduction = re... | <|body_start_0|>
super(FocalLoss, self).__init__()
assert use_sigmoid is True, 'Only sigmoid focal loss supported now.'
self.use_sigmoid = use_sigmoid
self.gamma = gamma
self.alpha = alpha
self.reduction = reduction
self.loss_weight = loss_weight
<|end_body_0|>
<... | FocalLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FocalLoss:
def __init__(self, use_sigmoid=True, gamma=2.0, alpha=0.25, reduction='mean', loss_weight=1.0):
"""`Focal Loss <https://arxiv.org/abs/1708.02002>`_ Args: use_sigmoid (bool, optional): Whether to the prediction is used for sigmoid or softmax. Defaults to True. gamma (float, opt... | stack_v2_sparse_classes_36k_train_015825 | 7,616 | permissive | [
{
"docstring": "`Focal Loss <https://arxiv.org/abs/1708.02002>`_ Args: use_sigmoid (bool, optional): Whether to the prediction is used for sigmoid or softmax. Defaults to True. gamma (float, optional): The gamma for calculating the modulating factor. Defaults to 2.0. alpha (float, optional): A balanced form for... | 2 | null | Implement the Python class `FocalLoss` described below.
Class description:
Implement the FocalLoss class.
Method signatures and docstrings:
- def __init__(self, use_sigmoid=True, gamma=2.0, alpha=0.25, reduction='mean', loss_weight=1.0): `Focal Loss <https://arxiv.org/abs/1708.02002>`_ Args: use_sigmoid (bool, option... | Implement the Python class `FocalLoss` described below.
Class description:
Implement the FocalLoss class.
Method signatures and docstrings:
- def __init__(self, use_sigmoid=True, gamma=2.0, alpha=0.25, reduction='mean', loss_weight=1.0): `Focal Loss <https://arxiv.org/abs/1708.02002>`_ Args: use_sigmoid (bool, option... | 3e083be9c807793ec1d6a9ffe091978ee01de02b | <|skeleton|>
class FocalLoss:
def __init__(self, use_sigmoid=True, gamma=2.0, alpha=0.25, reduction='mean', loss_weight=1.0):
"""`Focal Loss <https://arxiv.org/abs/1708.02002>`_ Args: use_sigmoid (bool, optional): Whether to the prediction is used for sigmoid or softmax. Defaults to True. gamma (float, opt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FocalLoss:
def __init__(self, use_sigmoid=True, gamma=2.0, alpha=0.25, reduction='mean', loss_weight=1.0):
"""`Focal Loss <https://arxiv.org/abs/1708.02002>`_ Args: use_sigmoid (bool, optional): Whether to the prediction is used for sigmoid or softmax. Defaults to True. gamma (float, optional): The ga... | the_stack_v2_python_sparse | segmentation/mmseg_custom/models/losses/focal_loss.py | OpenGVLab/InternImage | train | 1,834 | |
e260482940e11314881315ce489a1aaca5e444f0 | [
"course_key = self.course.location.course_key\nbadge_class = BadgeClassFactory.create(course_id=course_key)\nfor dummy in range(3):\n BadgeAssertionFactory.create(user=self.user, badge_class=badge_class)\nfor dummy in range(3):\n BadgeAssertionFactory.create(user=self.user)\nfor dummy in range(6):\n BadgeA... | <|body_start_0|>
course_key = self.course.location.course_key
badge_class = BadgeClassFactory.create(course_id=course_key)
for dummy in range(3):
BadgeAssertionFactory.create(user=self.user, badge_class=badge_class)
for dummy in range(3):
BadgeAssertionFactory.cre... | Test the Badge Assertions view with the course_id filter. | TestUserCourseBadgeAssertions | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestUserCourseBadgeAssertions:
"""Test the Badge Assertions view with the course_id filter."""
def test_get_assertions(self):
"""Verify we can get assertions via the course_id and username."""
<|body_0|>
def test_assertion_structure(self):
"""Verify the badge ass... | stack_v2_sparse_classes_36k_train_015826 | 8,941 | permissive | [
{
"docstring": "Verify we can get assertions via the course_id and username.",
"name": "test_get_assertions",
"signature": "def test_get_assertions(self)"
},
{
"docstring": "Verify the badge assertion structure is as expected when a course is involved.",
"name": "test_assertion_structure",
... | 2 | stack_v2_sparse_classes_30k_train_005088 | Implement the Python class `TestUserCourseBadgeAssertions` described below.
Class description:
Test the Badge Assertions view with the course_id filter.
Method signatures and docstrings:
- def test_get_assertions(self): Verify we can get assertions via the course_id and username.
- def test_assertion_structure(self):... | Implement the Python class `TestUserCourseBadgeAssertions` described below.
Class description:
Test the Badge Assertions view with the course_id filter.
Method signatures and docstrings:
- def test_get_assertions(self): Verify we can get assertions via the course_id and username.
- def test_assertion_structure(self):... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class TestUserCourseBadgeAssertions:
"""Test the Badge Assertions view with the course_id filter."""
def test_get_assertions(self):
"""Verify we can get assertions via the course_id and username."""
<|body_0|>
def test_assertion_structure(self):
"""Verify the badge ass... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestUserCourseBadgeAssertions:
"""Test the Badge Assertions view with the course_id filter."""
def test_get_assertions(self):
"""Verify we can get assertions via the course_id and username."""
course_key = self.course.location.course_key
badge_class = BadgeClassFactory.create(cour... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/badges/api/tests.py | luque/better-ways-of-thinking-about-software | train | 3 |
fe1b68be12c5b5606e3c516dd1543be259d091e3 | [
"data_list = []\nresults = self.query.all()\nformatter = self.request.locale.dates.getFormatter('date', 'short')\nfor result in results:\n data = {}\n data['qid'] = 'm_' + str(result.motion_id)\n data['subject'] = u'M ' + str(result.motion_number) + u' ' + result.short_name\n data['title'] = result.shor... | <|body_start_0|>
data_list = []
results = self.query.all()
formatter = self.request.locale.dates.getFormatter('date', 'short')
for result in results:
data = {}
data['qid'] = 'm_' + str(result.motion_id)
data['subject'] = u'M ' + str(result.motion_numbe... | MotionInStateViewlet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MotionInStateViewlet:
def getData(self):
"""return the data of the query"""
<|body_0|>
def update(self):
"""refresh the query"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
data_list = []
results = self.query.all()
formatter = self.... | stack_v2_sparse_classes_36k_train_015827 | 35,739 | no_license | [
{
"docstring": "return the data of the query",
"name": "getData",
"signature": "def getData(self)"
},
{
"docstring": "refresh the query",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001641 | Implement the Python class `MotionInStateViewlet` described below.
Class description:
Implement the MotionInStateViewlet class.
Method signatures and docstrings:
- def getData(self): return the data of the query
- def update(self): refresh the query | Implement the Python class `MotionInStateViewlet` described below.
Class description:
Implement the MotionInStateViewlet class.
Method signatures and docstrings:
- def getData(self): return the data of the query
- def update(self): refresh the query
<|skeleton|>
class MotionInStateViewlet:
def getData(self):
... | 5cf0ba31dfbff8d2c1b4aa8ab6f69c7a0ae9870d | <|skeleton|>
class MotionInStateViewlet:
def getData(self):
"""return the data of the query"""
<|body_0|>
def update(self):
"""refresh the query"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MotionInStateViewlet:
def getData(self):
"""return the data of the query"""
data_list = []
results = self.query.all()
formatter = self.request.locale.dates.getFormatter('date', 'short')
for result in results:
data = {}
data['qid'] = 'm_' + str(re... | the_stack_v2_python_sparse | bungeni.buildout/branches/bungeni.buildout-refactor-2010-06-02/src/bungeni.main/bungeni/ui/viewlets/workspace.py | malangalanga/bungeni-portal | train | 0 | |
e5c8d135045369bb51f07aa2a9f81b5fe8771623 | [
"self.input1 = \"Burning 'em, if you ain't quick and nimble\\n\"\nself.input2 = 'I go crazy when I hear a cymbal'\nself.expected1 = '0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272'\nself.expected2 = 'a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f'\nself.key = ... | <|body_start_0|>
self.input1 = "Burning 'em, if you ain't quick and nimble\n"
self.input2 = 'I go crazy when I hear a cymbal'
self.expected1 = '0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272'
self.expected2 = 'a282b2f20430a652e2c652a3124333a653e2b2027630c692b... | Challenge05 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Challenge05:
def __init__(self):
"""Init"""
<|body_0|>
def display(self):
"""Display challenge info :return:"""
<|body_1|>
def run(self):
"""Implement repeating key XOR... :return:"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_015828 | 1,837 | no_license | [
{
"docstring": "Init",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Display challenge info :return:",
"name": "display",
"signature": "def display(self)"
},
{
"docstring": "Implement repeating key XOR... :return:",
"name": "run",
"signature": "... | 3 | stack_v2_sparse_classes_30k_train_019271 | Implement the Python class `Challenge05` described below.
Class description:
Implement the Challenge05 class.
Method signatures and docstrings:
- def __init__(self): Init
- def display(self): Display challenge info :return:
- def run(self): Implement repeating key XOR... :return: | Implement the Python class `Challenge05` described below.
Class description:
Implement the Challenge05 class.
Method signatures and docstrings:
- def __init__(self): Init
- def display(self): Display challenge info :return:
- def run(self): Implement repeating key XOR... :return:
<|skeleton|>
class Challenge05:
... | 8e5a5b8216b3ee91b72a7388289bb5658721d375 | <|skeleton|>
class Challenge05:
def __init__(self):
"""Init"""
<|body_0|>
def display(self):
"""Display challenge info :return:"""
<|body_1|>
def run(self):
"""Implement repeating key XOR... :return:"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Challenge05:
def __init__(self):
"""Init"""
self.input1 = "Burning 'em, if you ain't quick and nimble\n"
self.input2 = 'I go crazy when I hear a cymbal'
self.expected1 = '0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272'
self.expected2 = 'a282... | the_stack_v2_python_sparse | challenges/set_01_basics/challenge_05_repeating_key_xor.py | matei/cryptopals | train | 0 | |
3030bcf6cc97377f1470c742dea8ba9624f54fd3 | [
"if root is None:\n return '[null]'\nl = [root]\nresult = []\nwhile len(l) > 0:\n p = l[0]\n if p is None:\n result.append('null')\n else:\n result.append(str(p.val))\n l.append(p.left)\n l.append(p.right)\n l = l[1:]\ni = len(result) - 1\nwhile result[i] == 'null':\n i... | <|body_start_0|>
if root is None:
return '[null]'
l = [root]
result = []
while len(l) > 0:
p = l[0]
if p is None:
result.append('null')
else:
result.append(str(p.val))
l.append(p.left)
... | 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_015829 | 1,600 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 2e0a801b52712330581ac2cb078b40d14cc1aa4d | <|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 root is None:
return '[null]'
l = [root]
result = []
while len(l) > 0:
p = l[0]
if p is None:
result.append... | the_stack_v2_python_sparse | 剑指offer/37.py | AS-ZZY/leetcode | train | 1 | |
82b9ab685d697fa34bd7e3d17c8ec477cd5142ad | [
"super(MetaFairClassifier, self).__init__(tau=tau, sensitive_attr=sensitive_attr, type=type, seed=seed)\nself.tau = tau\nself.sensitive_attr = sensitive_attr\nif type == 'fdr':\n self.obj = FalseDiscovery()\nelif type == 'sr':\n self.obj = StatisticalRate()\nelse:\n raise NotImplementedError(\"Only 'fdr' a... | <|body_start_0|>
super(MetaFairClassifier, self).__init__(tau=tau, sensitive_attr=sensitive_attr, type=type, seed=seed)
self.tau = tau
self.sensitive_attr = sensitive_attr
if type == 'fdr':
self.obj = FalseDiscovery()
elif type == 'sr':
self.obj = Statisti... | The meta algorithm here takes the fairness metric as part of the input and returns a classifier optimized w.r.t. that fairness metric [11]_. References: .. [11] L. E. Celis, L. Huang, V. Keswani, and N. K. Vishnoi. "Classification with Fairness Constraints: A Meta-Algorithm with Provable Guarantees," 2018. | MetaFairClassifier | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetaFairClassifier:
"""The meta algorithm here takes the fairness metric as part of the input and returns a classifier optimized w.r.t. that fairness metric [11]_. References: .. [11] L. E. Celis, L. Huang, V. Keswani, and N. K. Vishnoi. "Classification with Fairness Constraints: A Meta-Algorithm... | stack_v2_sparse_classes_36k_train_015830 | 3,313 | permissive | [
{
"docstring": "Args: tau (double, optional): Fairness penalty parameter. sensitive_attr (str, optional): Name of protected attribute. type (str, optional): The type of fairness metric to be used. Currently \"fdr\" (false discovery rate ratio) and \"sr\" (statistical rate/disparate impact) are supported. To use... | 3 | null | Implement the Python class `MetaFairClassifier` described below.
Class description:
The meta algorithm here takes the fairness metric as part of the input and returns a classifier optimized w.r.t. that fairness metric [11]_. References: .. [11] L. E. Celis, L. Huang, V. Keswani, and N. K. Vishnoi. "Classification with... | Implement the Python class `MetaFairClassifier` described below.
Class description:
The meta algorithm here takes the fairness metric as part of the input and returns a classifier optimized w.r.t. that fairness metric [11]_. References: .. [11] L. E. Celis, L. Huang, V. Keswani, and N. K. Vishnoi. "Classification with... | 6f9972e4a7dbca2402f29b86ea67889143dbeb3e | <|skeleton|>
class MetaFairClassifier:
"""The meta algorithm here takes the fairness metric as part of the input and returns a classifier optimized w.r.t. that fairness metric [11]_. References: .. [11] L. E. Celis, L. Huang, V. Keswani, and N. K. Vishnoi. "Classification with Fairness Constraints: A Meta-Algorithm... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MetaFairClassifier:
"""The meta algorithm here takes the fairness metric as part of the input and returns a classifier optimized w.r.t. that fairness metric [11]_. References: .. [11] L. E. Celis, L. Huang, V. Keswani, and N. K. Vishnoi. "Classification with Fairness Constraints: A Meta-Algorithm with Provabl... | the_stack_v2_python_sparse | aif360/algorithms/inprocessing/meta_fair_classifier.py | Trusted-AI/AIF360 | train | 1,157 |
2943c8e37c72769c0cfddd868ff4552bbc60c7fa | [
"rospy.init_node(node_name)\ncamera_topic = rospy.get_namespace() + 'camera1/image_raw'\nlane_tracking_topic = rospy.get_namespace() + 'lane_detection'\nself.camera_sub = rospy.Subscriber(camera_topic, Image, self._camera_callback)\nself.bridge = CvBridge()\nself._initialize_lane_detector()\nself.lane_tracking_pub ... | <|body_start_0|>
rospy.init_node(node_name)
camera_topic = rospy.get_namespace() + 'camera1/image_raw'
lane_tracking_topic = rospy.get_namespace() + 'lane_detection'
self.camera_sub = rospy.Subscriber(camera_topic, Image, self._camera_callback)
self.bridge = CvBridge()
se... | This class provides the interface between the Lane detection algorithm and the smile mobile robot running in the ROS ecosystem. | Lane_Detection_ROS | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Lane_Detection_ROS:
"""This class provides the interface between the Lane detection algorithm and the smile mobile robot running in the ROS ecosystem."""
def __init__(self, node_name='lane_detector'):
"""Initialize the communication to the image data and run lane detection on it. Par... | stack_v2_sparse_classes_36k_train_015831 | 26,132 | no_license | [
{
"docstring": "Initialize the communication to the image data and run lane detection on it. Parameters: node_name: The name of this ROS lane detection node. Default: lane_detector Returns: N/A",
"name": "__init__",
"signature": "def __init__(self, node_name='lane_detector')"
},
{
"docstring": "... | 4 | stack_v2_sparse_classes_30k_train_004358 | Implement the Python class `Lane_Detection_ROS` described below.
Class description:
This class provides the interface between the Lane detection algorithm and the smile mobile robot running in the ROS ecosystem.
Method signatures and docstrings:
- def __init__(self, node_name='lane_detector'): Initialize the communic... | Implement the Python class `Lane_Detection_ROS` described below.
Class description:
This class provides the interface between the Lane detection algorithm and the smile mobile robot running in the ROS ecosystem.
Method signatures and docstrings:
- def __init__(self, node_name='lane_detector'): Initialize the communic... | e0768f0c9f67acafeaab954b88cb16903461d0fb | <|skeleton|>
class Lane_Detection_ROS:
"""This class provides the interface between the Lane detection algorithm and the smile mobile robot running in the ROS ecosystem."""
def __init__(self, node_name='lane_detector'):
"""Initialize the communication to the image data and run lane detection on it. Par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Lane_Detection_ROS:
"""This class provides the interface between the Lane detection algorithm and the smile mobile robot running in the ROS ecosystem."""
def __init__(self, node_name='lane_detector'):
"""Initialize the communication to the image data and run lane detection on it. Parameters: node... | the_stack_v2_python_sparse | smile_mobile_robot_ws/src/smile_mobile_robot/src/perception/vision/lane_detector.py | Happy-Aztec-Digging-Extraction-System/smile-mobile | train | 0 |
8d186842ae3a41bc6d217034c9ec605047f200d8 | [
"super().__init__(label, parent=parent)\nself.setFocusPolicy(QtCore.Qt.StrongFocus)\nself.setDefault(False)\nself.setAutoDefault(False)\nself.clicked.connect(slot)\nif checkable:\n self.setCheckable(True)\nif width:\n self.setFixedWidth(width)",
"if event.key() == QtCore.Qt.Key_Return or event.key() == QtCo... | <|body_start_0|>
super().__init__(label, parent=parent)
self.setFocusPolicy(QtCore.Qt.StrongFocus)
self.setDefault(False)
self.setAutoDefault(False)
self.clicked.connect(slot)
if checkable:
self.setCheckable(True)
if width:
self.setFixedWid... | A button with associated label and slot function. | NXPushButton | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NXPushButton:
"""A button with associated label and slot function."""
def __init__(self, label, slot, checkable=False, width=None, parent=None):
"""Initialize button Parameters ---------- label : str Text describing the button slot : func Function to be called when the button is pres... | stack_v2_sparse_classes_36k_train_015832 | 43,131 | permissive | [
{
"docstring": "Initialize button Parameters ---------- label : str Text describing the button slot : func Function to be called when the button is pressed parent : QObject, optional Parent of button.",
"name": "__init__",
"signature": "def __init__(self, label, slot, checkable=False, width=None, parent... | 2 | stack_v2_sparse_classes_30k_train_000943 | Implement the Python class `NXPushButton` described below.
Class description:
A button with associated label and slot function.
Method signatures and docstrings:
- def __init__(self, label, slot, checkable=False, width=None, parent=None): Initialize button Parameters ---------- label : str Text describing the button ... | Implement the Python class `NXPushButton` described below.
Class description:
A button with associated label and slot function.
Method signatures and docstrings:
- def __init__(self, label, slot, checkable=False, width=None, parent=None): Initialize button Parameters ---------- label : str Text describing the button ... | 97110aa2ebeff95cc78496bf5396d6b51fc151a7 | <|skeleton|>
class NXPushButton:
"""A button with associated label and slot function."""
def __init__(self, label, slot, checkable=False, width=None, parent=None):
"""Initialize button Parameters ---------- label : str Text describing the button slot : func Function to be called when the button is pres... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NXPushButton:
"""A button with associated label and slot function."""
def __init__(self, label, slot, checkable=False, width=None, parent=None):
"""Initialize button Parameters ---------- label : str Text describing the button slot : func Function to be called when the button is pressed parent : ... | the_stack_v2_python_sparse | src/nexpy/gui/widgets.py | nexpy/nexpy | train | 42 |
acfdcb335c32e36881c60c686687326fa053f4ca | [
"self.model_type = model_type\nself.threshold = threshold\nself.curr_threshold = threshold\nself.fire = fire\nself.refract = refract\nself.t_max = self.fire + self.refract",
"if self.model_type == 'linear':\n if activation_time > 0:\n self.curr_threshold = self.threshold + (1 - self.threshold) * (1 - ac... | <|body_start_0|>
self.model_type = model_type
self.threshold = threshold
self.curr_threshold = threshold
self.fire = fire
self.refract = refract
self.t_max = self.fire + self.refract
<|end_body_0|>
<|body_start_1|>
if self.model_type == 'linear':
if a... | The model that describes how the neuron will fire given that it is activated. Attributes ---------- model_type : str A string describing the type of firing model for this Firing_Model instance threshold : float The value of input at which point the neuron goes from being inactive to active curr_threshold : float The cu... | Threshold_Model | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Threshold_Model:
"""The model that describes how the neuron will fire given that it is activated. Attributes ---------- model_type : str A string describing the type of firing model for this Firing_Model instance threshold : float The value of input at which point the neuron goes from being inact... | stack_v2_sparse_classes_36k_train_015833 | 13,526 | permissive | [
{
"docstring": "Parameters ---------- model_type : str A string describing the type of firing model for this Firing_Model instance threshold : float Defines the value of input at which point the neuron goes from being inactive to active curr_threshold : float Holds the current value of the threshold, which may ... | 2 | stack_v2_sparse_classes_30k_train_018433 | Implement the Python class `Threshold_Model` described below.
Class description:
The model that describes how the neuron will fire given that it is activated. Attributes ---------- model_type : str A string describing the type of firing model for this Firing_Model instance threshold : float The value of input at which... | Implement the Python class `Threshold_Model` described below.
Class description:
The model that describes how the neuron will fire given that it is activated. Attributes ---------- model_type : str A string describing the type of firing model for this Firing_Model instance threshold : float The value of input at which... | 93aa6312ab53e6a71f6ef5dd1fc6b2187d852ee1 | <|skeleton|>
class Threshold_Model:
"""The model that describes how the neuron will fire given that it is activated. Attributes ---------- model_type : str A string describing the type of firing model for this Firing_Model instance threshold : float The value of input at which point the neuron goes from being inact... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Threshold_Model:
"""The model that describes how the neuron will fire given that it is activated. Attributes ---------- model_type : str A string describing the type of firing model for this Firing_Model instance threshold : float The value of input at which point the neuron goes from being inactive to active... | the_stack_v2_python_sparse | neuralnet/neuron_stable_adjust.py | orrenravid1/AML | train | 0 |
bc00d14ce165eb81ec0b2e2f71387f79dc83d9ae | [
"super(BasicDdHy, self).__init__(input_file=input_file, params=params, BaselevelHandlerClass=BaselevelHandlerClass)\nself.K_sp = self.get_parameter_from_exponent('K_sp')\nlinear_diffusivity = self._length_factor ** 2 * self.get_parameter_from_exponent('linear_diffusivity')\nv_s = self.get_parameter_from_exponent('v... | <|body_start_0|>
super(BasicDdHy, self).__init__(input_file=input_file, params=params, BaselevelHandlerClass=BaselevelHandlerClass)
self.K_sp = self.get_parameter_from_exponent('K_sp')
linear_diffusivity = self._length_factor ** 2 * self.get_parameter_from_exponent('linear_diffusivity')
... | A BasicDdHy computes erosion using 1) the hybrid alluvium component with a threshold that varies with cumulative incision depth, the linear diffusion component. | BasicDdHy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicDdHy:
"""A BasicDdHy computes erosion using 1) the hybrid alluvium component with a threshold that varies with cumulative incision depth, the linear diffusion component."""
def __init__(self, input_file=None, params=None, BaselevelHandlerClass=None):
"""Initialize the BasicDdHy"... | stack_v2_sparse_classes_36k_train_015834 | 4,821 | permissive | [
{
"docstring": "Initialize the BasicDdHy",
"name": "__init__",
"signature": "def __init__(self, input_file=None, params=None, BaselevelHandlerClass=None)"
},
{
"docstring": "Advance model for one time-step of duration dt.",
"name": "run_one_step",
"signature": "def run_one_step(self, dt)... | 2 | stack_v2_sparse_classes_30k_train_000310 | Implement the Python class `BasicDdHy` described below.
Class description:
A BasicDdHy computes erosion using 1) the hybrid alluvium component with a threshold that varies with cumulative incision depth, the linear diffusion component.
Method signatures and docstrings:
- def __init__(self, input_file=None, params=Non... | Implement the Python class `BasicDdHy` described below.
Class description:
A BasicDdHy computes erosion using 1) the hybrid alluvium component with a threshold that varies with cumulative incision depth, the linear diffusion component.
Method signatures and docstrings:
- def __init__(self, input_file=None, params=Non... | 1b756477b8a8ab6a8f1275b1b30ec84855c840ea | <|skeleton|>
class BasicDdHy:
"""A BasicDdHy computes erosion using 1) the hybrid alluvium component with a threshold that varies with cumulative incision depth, the linear diffusion component."""
def __init__(self, input_file=None, params=None, BaselevelHandlerClass=None):
"""Initialize the BasicDdHy"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BasicDdHy:
"""A BasicDdHy computes erosion using 1) the hybrid alluvium component with a threshold that varies with cumulative incision depth, the linear diffusion component."""
def __init__(self, input_file=None, params=None, BaselevelHandlerClass=None):
"""Initialize the BasicDdHy"""
su... | the_stack_v2_python_sparse | terrainbento/derived_models/model_018_basicDdHy/model_018_basicDdHy.py | mcflugen/terrainbento | train | 0 |
96bdae9bbbb96eb9bfe7c401b50fbc732eaf0ed5 | [
"self._api = api\nself._url = url\nself._required_sid = required_sid\nself._errors_mapping = errors_mapping\nself._pagination_field = pagination_field\nself._rows_in_page = rows_in_page\nself._return_constructor = return_constructor\nself._min_row: int = 0\nself._max_row: Optional[int] = None\nself._current_row: Op... | <|body_start_0|>
self._api = api
self._url = url
self._required_sid = required_sid
self._errors_mapping = errors_mapping
self._pagination_field = pagination_field
self._rows_in_page = rows_in_page
self._return_constructor = return_constructor
self._min_row... | BaseIterable response. | BaseIterableResponse | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseIterableResponse:
"""BaseIterable response."""
def __init__(self, *, api, url: str, required_sid: bool, errors_mapping: ERROR_MAPPING, pagination_field: str, rows_in_page: int, return_constructor: Callable[..., JSON_RETURN_TYPE]=Box):
"""Respone initialization. :param api: api :p... | stack_v2_sparse_classes_36k_train_015835 | 5,764 | permissive | [
{
"docstring": "Respone initialization. :param api: api :param url: url :param required_sid: require_sid :param errors_mapping: map of error name and exception :param pagination_field: field for pagination :param rows_in_page: number of rows in page :param return_constructor: constructor for return type",
"... | 4 | stack_v2_sparse_classes_30k_train_007782 | Implement the Python class `BaseIterableResponse` described below.
Class description:
BaseIterable response.
Method signatures and docstrings:
- def __init__(self, *, api, url: str, required_sid: bool, errors_mapping: ERROR_MAPPING, pagination_field: str, rows_in_page: int, return_constructor: Callable[..., JSON_RETU... | Implement the Python class `BaseIterableResponse` described below.
Class description:
BaseIterable response.
Method signatures and docstrings:
- def __init__(self, *, api, url: str, required_sid: bool, errors_mapping: ERROR_MAPPING, pagination_field: str, rows_in_page: int, return_constructor: Callable[..., JSON_RETU... | 2618e682d38339439340d86080e8bc6ee6cf21b5 | <|skeleton|>
class BaseIterableResponse:
"""BaseIterable response."""
def __init__(self, *, api, url: str, required_sid: bool, errors_mapping: ERROR_MAPPING, pagination_field: str, rows_in_page: int, return_constructor: Callable[..., JSON_RETURN_TYPE]=Box):
"""Respone initialization. :param api: api :p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseIterableResponse:
"""BaseIterable response."""
def __init__(self, *, api, url: str, required_sid: bool, errors_mapping: ERROR_MAPPING, pagination_field: str, rows_in_page: int, return_constructor: Callable[..., JSON_RETURN_TYPE]=Box):
"""Respone initialization. :param api: api :param url: url... | the_stack_v2_python_sparse | ambra_sdk/service/response/base_response.py | dicomgrid/sdk-python | train | 11 |
8e4db6713d03d23a9f709382647f27ecdc17fd68 | [
"super().__init__()\nself._data = []\nself.setWindowTitle('Pulse Information')\nlayout = qt.QtWidgets.QVBoxLayout()\nself.table = qt.QtWidgets.QTableWidget()\nself.table.setColumnCount(2)\nheader = self.table.horizontalHeader()\nheader.setSectionResizeMode(0, qt.QtWidgets.QHeaderView.ResizeMode.ResizeToContents)\nh... | <|body_start_0|>
super().__init__()
self._data = []
self.setWindowTitle('Pulse Information')
layout = qt.QtWidgets.QVBoxLayout()
self.table = qt.QtWidgets.QTableWidget()
self.table.setColumnCount(2)
header = self.table.horizontalHeader()
header.setSectionR... | Secondary window of the WaveformViewer to inspect the properties of Pulse objects. Is opened upon ctrl (or cmd) clicking on a pulse in the main window of the WaveformViewer. | PulseInformationWindow | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PulseInformationWindow:
"""Secondary window of the WaveformViewer to inspect the properties of Pulse objects. Is opened upon ctrl (or cmd) clicking on a pulse in the main window of the WaveformViewer."""
def __init__(self):
"""Instantiates the Qt Widgets of the main window, sets the ... | stack_v2_sparse_classes_36k_train_015836 | 30,657 | permissive | [
{
"docstring": "Instantiates the Qt Widgets of the main window, sets the layout and connects the relevant signals of the widgets to their slots.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Updates the _data attribute of the class instance with the value of pass_inf... | 4 | null | Implement the Python class `PulseInformationWindow` described below.
Class description:
Secondary window of the WaveformViewer to inspect the properties of Pulse objects. Is opened upon ctrl (or cmd) clicking on a pulse in the main window of the WaveformViewer.
Method signatures and docstrings:
- def __init__(self): ... | Implement the Python class `PulseInformationWindow` described below.
Class description:
Secondary window of the WaveformViewer to inspect the properties of Pulse objects. Is opened upon ctrl (or cmd) clicking on a pulse in the main window of the WaveformViewer.
Method signatures and docstrings:
- def __init__(self): ... | bc6733d774fe31a23f4c7e73e5eb0beed8d30e7d | <|skeleton|>
class PulseInformationWindow:
"""Secondary window of the WaveformViewer to inspect the properties of Pulse objects. Is opened upon ctrl (or cmd) clicking on a pulse in the main window of the WaveformViewer."""
def __init__(self):
"""Instantiates the Qt Widgets of the main window, sets the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PulseInformationWindow:
"""Secondary window of the WaveformViewer to inspect the properties of Pulse objects. Is opened upon ctrl (or cmd) clicking on a pulse in the main window of the WaveformViewer."""
def __init__(self):
"""Instantiates the Qt Widgets of the main window, sets the layout and co... | the_stack_v2_python_sparse | pycqed/gui/waveform_viewer.py | QudevETH/PycQED_py3 | train | 8 |
d9b117f5dffc3f5f23455b27694753d795673c4f | [
"if 'length' not in net_params.additional_params:\n raise ValueError('length of circle not supplied')\nself.length = net_params.additional_params['length']\nif 'lanes' not in net_params.additional_params:\n raise ValueError('lanes of circle not supplied')\nself.lanes = net_params.additional_params['lanes']\ni... | <|body_start_0|>
if 'length' not in net_params.additional_params:
raise ValueError('length of circle not supplied')
self.length = net_params.additional_params['length']
if 'lanes' not in net_params.additional_params:
raise ValueError('lanes of circle not supplied')
... | LoopScenario | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoopScenario:
def __init__(self, name, generator_class, vehicles, net_params, initial_config=None):
"""Initializes a loop scenario. Required net_params: length, lanes, speed_limit, resolution. See Scenario.py for description of params."""
<|body_0|>
def specify_edge_starts(s... | stack_v2_sparse_classes_36k_train_015837 | 1,524 | permissive | [
{
"docstring": "Initializes a loop scenario. Required net_params: length, lanes, speed_limit, resolution. See Scenario.py for description of params.",
"name": "__init__",
"signature": "def __init__(self, name, generator_class, vehicles, net_params, initial_config=None)"
},
{
"docstring": "See pa... | 2 | stack_v2_sparse_classes_30k_train_011460 | Implement the Python class `LoopScenario` described below.
Class description:
Implement the LoopScenario class.
Method signatures and docstrings:
- def __init__(self, name, generator_class, vehicles, net_params, initial_config=None): Initializes a loop scenario. Required net_params: length, lanes, speed_limit, resolu... | Implement the Python class `LoopScenario` described below.
Class description:
Implement the LoopScenario class.
Method signatures and docstrings:
- def __init__(self, name, generator_class, vehicles, net_params, initial_config=None): Initializes a loop scenario. Required net_params: length, lanes, speed_limit, resolu... | f3f6d7e9c64f6b641a464a716c7f38ca00388805 | <|skeleton|>
class LoopScenario:
def __init__(self, name, generator_class, vehicles, net_params, initial_config=None):
"""Initializes a loop scenario. Required net_params: length, lanes, speed_limit, resolution. See Scenario.py for description of params."""
<|body_0|>
def specify_edge_starts(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoopScenario:
def __init__(self, name, generator_class, vehicles, net_params, initial_config=None):
"""Initializes a loop scenario. Required net_params: length, lanes, speed_limit, resolution. See Scenario.py for description of params."""
if 'length' not in net_params.additional_params:
... | the_stack_v2_python_sparse | flow/scenarios/loop/loop_scenario.py | mark-koren/flow | train | 0 | |
683859b8ebbb5d83222e3e406b7333fa266a277e | [
"res = fn.ones_like(t)\nif isinstance(t, (list, tuple)):\n t = onp.asarray(t)\nassert res.shape == t.shape\nassert fn.get_interface(res) == fn.get_interface(t)\nassert fn.allclose(res, np.ones(t.shape))\nif hasattr(res, 'numpy'):\n res = res.numpy()\n t = t.numpy()\nassert onp.asarray(res).dtype.type is on... | <|body_start_0|>
res = fn.ones_like(t)
if isinstance(t, (list, tuple)):
t = onp.asarray(t)
assert res.shape == t.shape
assert fn.get_interface(res) == fn.get_interface(t)
assert fn.allclose(res, np.ones(t.shape))
if hasattr(res, 'numpy'):
res = res... | Tests for the ones_like function | TestOnesLike | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestOnesLike:
"""Tests for the ones_like function"""
def test_ones_like_inferred_dtype(self, t):
"""Test that the ones like function creates the correct shape and type tensor."""
<|body_0|>
def test_ones_like_explicit_dtype(self, t):
"""Test that the ones like fu... | stack_v2_sparse_classes_36k_train_015838 | 47,600 | permissive | [
{
"docstring": "Test that the ones like function creates the correct shape and type tensor.",
"name": "test_ones_like_inferred_dtype",
"signature": "def test_ones_like_inferred_dtype(self, t)"
},
{
"docstring": "Test that the ones like function creates the correct shape and type tensor.",
"n... | 2 | null | Implement the Python class `TestOnesLike` described below.
Class description:
Tests for the ones_like function
Method signatures and docstrings:
- def test_ones_like_inferred_dtype(self, t): Test that the ones like function creates the correct shape and type tensor.
- def test_ones_like_explicit_dtype(self, t): Test ... | Implement the Python class `TestOnesLike` described below.
Class description:
Tests for the ones_like function
Method signatures and docstrings:
- def test_ones_like_inferred_dtype(self, t): Test that the ones like function creates the correct shape and type tensor.
- def test_ones_like_explicit_dtype(self, t): Test ... | 0c1c805fd5dfce465a8955ee3faf81037023a23e | <|skeleton|>
class TestOnesLike:
"""Tests for the ones_like function"""
def test_ones_like_inferred_dtype(self, t):
"""Test that the ones like function creates the correct shape and type tensor."""
<|body_0|>
def test_ones_like_explicit_dtype(self, t):
"""Test that the ones like fu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestOnesLike:
"""Tests for the ones_like function"""
def test_ones_like_inferred_dtype(self, t):
"""Test that the ones like function creates the correct shape and type tensor."""
res = fn.ones_like(t)
if isinstance(t, (list, tuple)):
t = onp.asarray(t)
assert r... | the_stack_v2_python_sparse | artifacts/old_dataset_versions/original_commits_backup/pennylane/pennylane#1081/before/test_functions.py | MattePalte/Bugs-Quantum-Computing-Platforms | train | 4 |
d9b4d78dc33b092f25083195e2d45cde78cc14aa | [
"if s == '':\n return 0\narr = []\nmaxSize = 0\nfor index, char in enumerate(s):\n print(index, '+', char)\n if char not in arr:\n arr.append(char)\n else:\n while True:\n num = arr[0]\n arr.remove(num)\n if num == char:\n break\n arr.... | <|body_start_0|>
if s == '':
return 0
arr = []
maxSize = 0
for index, char in enumerate(s):
print(index, '+', char)
if char not in arr:
arr.append(char)
else:
while True:
num = arr[0]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
"""执行用时 :60 ms, 在所有 Python3 提交中击败了88.14%的用户 内存消耗 :13.5 MB, 在所有 Python3 提交中击败了41.01%的用户 :param s: :return:"""
<|body_0|>
def lengthOfLongestSubstring2(self, s: str) -> int:
"""Runtime: 156 ms, faster than 21... | stack_v2_sparse_classes_36k_train_015839 | 4,437 | no_license | [
{
"docstring": "执行用时 :60 ms, 在所有 Python3 提交中击败了88.14%的用户 内存消耗 :13.5 MB, 在所有 Python3 提交中击败了41.01%的用户 :param s: :return:",
"name": "lengthOfLongestSubstring",
"signature": "def lengthOfLongestSubstring(self, s: str) -> int"
},
{
"docstring": "Runtime: 156 ms, faster than 21.77% of Python3 online s... | 6 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s: str) -> int: 执行用时 :60 ms, 在所有 Python3 提交中击败了88.14%的用户 内存消耗 :13.5 MB, 在所有 Python3 提交中击败了41.01%的用户 :param s: :return:
- def lengthOfLongestSub... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s: str) -> int: 执行用时 :60 ms, 在所有 Python3 提交中击败了88.14%的用户 内存消耗 :13.5 MB, 在所有 Python3 提交中击败了41.01%的用户 :param s: :return:
- def lengthOfLongestSub... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
"""执行用时 :60 ms, 在所有 Python3 提交中击败了88.14%的用户 内存消耗 :13.5 MB, 在所有 Python3 提交中击败了41.01%的用户 :param s: :return:"""
<|body_0|>
def lengthOfLongestSubstring2(self, s: str) -> int:
"""Runtime: 156 ms, faster than 21... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
"""执行用时 :60 ms, 在所有 Python3 提交中击败了88.14%的用户 内存消耗 :13.5 MB, 在所有 Python3 提交中击败了41.01%的用户 :param s: :return:"""
if s == '':
return 0
arr = []
maxSize = 0
for index, char in enumerate(s):
p... | the_stack_v2_python_sparse | LeetCode/字符串/3. Longest Substring Without Repeating Characters.py | yiming1012/MyLeetCode | train | 2 | |
ed6846288a524d9c4ff3d0845cb649df844a5b93 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ClonePostRequestBody()",
"from ....models.clonable_team_parts import ClonableTeamParts\nfrom ....models.team_visibility_type import TeamVisibilityType\nfrom ....models.clonable_team_parts import ClonableTeamParts\nfrom ....models.team_... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ClonePostRequestBody()
<|end_body_0|>
<|body_start_1|>
from ....models.clonable_team_parts import ClonableTeamParts
from ....models.team_visibility_type import TeamVisibilityType
... | ClonePostRequestBody | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClonePostRequestBody:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ClonePostRequestBody:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ... | stack_v2_sparse_classes_36k_train_015840 | 3,899 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ClonePostRequestBody",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminato... | 3 | stack_v2_sparse_classes_30k_train_017632 | Implement the Python class `ClonePostRequestBody` described below.
Class description:
Implement the ClonePostRequestBody class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ClonePostRequestBody: Creates a new instance of the appropriate class based o... | Implement the Python class `ClonePostRequestBody` described below.
Class description:
Implement the ClonePostRequestBody class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ClonePostRequestBody: Creates a new instance of the appropriate class based o... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ClonePostRequestBody:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ClonePostRequestBody:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClonePostRequestBody:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ClonePostRequestBody:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns... | the_stack_v2_python_sparse | msgraph/generated/teams/item/clone/clone_post_request_body.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
d0622ec9a9fb891ae2c9a0a875e3f0e5666725ed | [
"super().__init__()\nself.cfg = cfg\nself.task_queue = task_queue\nself.result_queue = result_queue\nself.gpu_id = gpu_id\nself.device = torch.device('cuda:{}'.format(self.gpu_id)) if self.cfg.NUM_GPUS else 'cpu'",
"model = Predictor(self.cfg, gpu_id=self.gpu_id)\nwhile True:\n task = self.task_queue.get()\n ... | <|body_start_0|>
super().__init__()
self.cfg = cfg
self.task_queue = task_queue
self.result_queue = result_queue
self.gpu_id = gpu_id
self.device = torch.device('cuda:{}'.format(self.gpu_id)) if self.cfg.NUM_GPUS else 'cpu'
<|end_body_0|>
<|body_start_1|>
model =... | _Predictor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Predictor:
def __init__(self, cfg, task_queue, result_queue, gpu_id=None):
"""Predict Worker for Detectron2. Args: cfg (CfgNode): configs. Details can be found in slowfast/config/defaults.py task_queue (mp.Queue): a shared queue for incoming task. result_queue (mp.Queue): a shared queue... | stack_v2_sparse_classes_36k_train_015841 | 9,808 | permissive | [
{
"docstring": "Predict Worker for Detectron2. Args: cfg (CfgNode): configs. Details can be found in slowfast/config/defaults.py task_queue (mp.Queue): a shared queue for incoming task. result_queue (mp.Queue): a shared queue for predicted results. gpu_id (int): index of the GPU device for the current child pro... | 2 | stack_v2_sparse_classes_30k_train_008595 | Implement the Python class `_Predictor` described below.
Class description:
Implement the _Predictor class.
Method signatures and docstrings:
- def __init__(self, cfg, task_queue, result_queue, gpu_id=None): Predict Worker for Detectron2. Args: cfg (CfgNode): configs. Details can be found in slowfast/config/defaults.... | Implement the Python class `_Predictor` described below.
Class description:
Implement the _Predictor class.
Method signatures and docstrings:
- def __init__(self, cfg, task_queue, result_queue, gpu_id=None): Predict Worker for Detectron2. Args: cfg (CfgNode): configs. Details can be found in slowfast/config/defaults.... | 6092dad7be32bb1d6b71fe1bade258dc8b492fe3 | <|skeleton|>
class _Predictor:
def __init__(self, cfg, task_queue, result_queue, gpu_id=None):
"""Predict Worker for Detectron2. Args: cfg (CfgNode): configs. Details can be found in slowfast/config/defaults.py task_queue (mp.Queue): a shared queue for incoming task. result_queue (mp.Queue): a shared queue... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _Predictor:
def __init__(self, cfg, task_queue, result_queue, gpu_id=None):
"""Predict Worker for Detectron2. Args: cfg (CfgNode): configs. Details can be found in slowfast/config/defaults.py task_queue (mp.Queue): a shared queue for incoming task. result_queue (mp.Queue): a shared queue for predicted... | the_stack_v2_python_sparse | slowfast/visualization/async_predictor.py | facebookresearch/SlowFast | train | 6,221 | |
e9ed6f8f1b581c28c38fd86f5cb450d64c318a10 | [
"payload = {'data': data, 'timestamp': int(time.time() * 1000)}\njwt_token = jwt.encode(payload, 'testingplatformhs256', algorithm='HS256')\nreturn bytes.decode(jwt_token)",
"try:\n return jwt.decode(jwt_token, verify=False)\nexcept DecodeError:\n return None"
] | <|body_start_0|>
payload = {'data': data, 'timestamp': int(time.time() * 1000)}
jwt_token = jwt.encode(payload, 'testingplatformhs256', algorithm='HS256')
return bytes.decode(jwt_token)
<|end_body_0|>
<|body_start_1|>
try:
return jwt.decode(jwt_token, verify=False)
e... | Security | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Security:
def encode(data):
"""生成 jwt token"""
<|body_0|>
def decode(jwt_token):
"""解析 jwt token"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
payload = {'data': data, 'timestamp': int(time.time() * 1000)}
jwt_token = jwt.encode(payload, '... | stack_v2_sparse_classes_36k_train_015842 | 1,417 | permissive | [
{
"docstring": "生成 jwt token",
"name": "encode",
"signature": "def encode(data)"
},
{
"docstring": "解析 jwt token",
"name": "decode",
"signature": "def decode(jwt_token)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018187 | Implement the Python class `Security` described below.
Class description:
Implement the Security class.
Method signatures and docstrings:
- def encode(data): 生成 jwt token
- def decode(jwt_token): 解析 jwt token | Implement the Python class `Security` described below.
Class description:
Implement the Security class.
Method signatures and docstrings:
- def encode(data): 生成 jwt token
- def decode(jwt_token): 解析 jwt token
<|skeleton|>
class Security:
def encode(data):
"""生成 jwt token"""
<|body_0|>
def d... | d7008343c25ec7f47acb670ae5c9b9b5f0593d63 | <|skeleton|>
class Security:
def encode(data):
"""生成 jwt token"""
<|body_0|>
def decode(jwt_token):
"""解析 jwt token"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Security:
def encode(data):
"""生成 jwt token"""
payload = {'data': data, 'timestamp': int(time.time() * 1000)}
jwt_token = jwt.encode(payload, 'testingplatformhs256', algorithm='HS256')
return bytes.decode(jwt_token)
def decode(jwt_token):
"""解析 jwt token"""
... | the_stack_v2_python_sparse | backend/util/jwt_token.py | felixu1992/testing-platform | train | 0 | |
840464221f9705d2cd52d868d9c09fea1fe7389b | [
"if isinstance(wrap_errors, dict):\n self.wrap_errors = wrap_errors\nsuper(self.__class__, self).__init__(wrap_errors, *args, **kwargs)",
"data = {}\nif self.wrap_errors:\n data = {'error_message': ''}\n for field, errors in self.wrap_errors.items():\n data['error_message'] += '{0} '.format(field)... | <|body_start_0|>
if isinstance(wrap_errors, dict):
self.wrap_errors = wrap_errors
super(self.__class__, self).__init__(wrap_errors, *args, **kwargs)
<|end_body_0|>
<|body_start_1|>
data = {}
if self.wrap_errors:
data = {'error_message': ''}
for field,... | Generic form validation execption. | FormValidationError | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FormValidationError:
"""Generic form validation execption."""
def __init__(self, wrap_errors=None, *args, **kwargs):
"""Initialise new MaxRequestsExceeded instance."""
<|body_0|>
def response_data(self):
"""Render a dict with a description of the validation error... | stack_v2_sparse_classes_36k_train_015843 | 7,717 | permissive | [
{
"docstring": "Initialise new MaxRequestsExceeded instance.",
"name": "__init__",
"signature": "def __init__(self, wrap_errors=None, *args, **kwargs)"
},
{
"docstring": "Render a dict with a description of the validation errors.",
"name": "response_data",
"signature": "def response_data... | 2 | stack_v2_sparse_classes_30k_train_009587 | Implement the Python class `FormValidationError` described below.
Class description:
Generic form validation execption.
Method signatures and docstrings:
- def __init__(self, wrap_errors=None, *args, **kwargs): Initialise new MaxRequestsExceeded instance.
- def response_data(self): Render a dict with a description of... | Implement the Python class `FormValidationError` described below.
Class description:
Generic form validation execption.
Method signatures and docstrings:
- def __init__(self, wrap_errors=None, *args, **kwargs): Initialise new MaxRequestsExceeded instance.
- def response_data(self): Render a dict with a description of... | 724dbb631da3c61d42f62024f9d7826423624191 | <|skeleton|>
class FormValidationError:
"""Generic form validation execption."""
def __init__(self, wrap_errors=None, *args, **kwargs):
"""Initialise new MaxRequestsExceeded instance."""
<|body_0|>
def response_data(self):
"""Render a dict with a description of the validation error... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FormValidationError:
"""Generic form validation execption."""
def __init__(self, wrap_errors=None, *args, **kwargs):
"""Initialise new MaxRequestsExceeded instance."""
if isinstance(wrap_errors, dict):
self.wrap_errors = wrap_errors
super(self.__class__, self).__init__... | the_stack_v2_python_sparse | djangolg/views/lg.py | jafo2128/djangolg | train | 0 |
8e0ff89da4fa2c4cb63b7ae339c6cce42adf7f27 | [
"AbstractComponent.__init__(self)\nif os.path.exists(file):\n filepath = file\nelse:\n filepath = os.path.join(MORSE_COMPONENTS, file)\n if not os.path.exists(filepath):\n logger.error('Blender file %s for external asset import can not be found.\\n Either provide an absolute... | <|body_start_0|>
AbstractComponent.__init__(self)
if os.path.exists(file):
filepath = file
else:
filepath = os.path.join(MORSE_COMPONENTS, file)
if not os.path.exists(filepath):
logger.error('Blender file %s for external asset import can ... | Allows to import any Blender object to the scene. | PassiveObject | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PassiveObject:
"""Allows to import any Blender object to the scene."""
def __init__(self, file, prefix=None, keep_pose=False):
""":param blenderfile: The Blender file to load. Path can be absolute or relative to MORSE assets' installation path (typically, $PREFIX/share/morse/data) :p... | stack_v2_sparse_classes_36k_train_015844 | 28,313 | permissive | [
{
"docstring": ":param blenderfile: The Blender file to load. Path can be absolute or relative to MORSE assets' installation path (typically, $PREFIX/share/morse/data) :param prefix: (optional) the prefix of the objects to load in the Blender file. If not set, all objects present in the file are loaded. If set,... | 2 | null | Implement the Python class `PassiveObject` described below.
Class description:
Allows to import any Blender object to the scene.
Method signatures and docstrings:
- def __init__(self, file, prefix=None, keep_pose=False): :param blenderfile: The Blender file to load. Path can be absolute or relative to MORSE assets' i... | Implement the Python class `PassiveObject` described below.
Class description:
Allows to import any Blender object to the scene.
Method signatures and docstrings:
- def __init__(self, file, prefix=None, keep_pose=False): :param blenderfile: The Blender file to load. Path can be absolute or relative to MORSE assets' i... | 07fcb64fea3b58b258e917eb1aed0a585f863418 | <|skeleton|>
class PassiveObject:
"""Allows to import any Blender object to the scene."""
def __init__(self, file, prefix=None, keep_pose=False):
""":param blenderfile: The Blender file to load. Path can be absolute or relative to MORSE assets' installation path (typically, $PREFIX/share/morse/data) :p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PassiveObject:
"""Allows to import any Blender object to the scene."""
def __init__(self, file, prefix=None, keep_pose=False):
""":param blenderfile: The Blender file to load. Path can be absolute or relative to MORSE assets' installation path (typically, $PREFIX/share/morse/data) :param prefix: ... | the_stack_v2_python_sparse | src/morse/builder/morsebuilder.py | DefaultUser/morse | train | 2 |
be37114d2ada19f1378ea1a8ecac64b054a26240 | [
"payment_profile = self.get_object()\ncard_id = kwargs['card_id']\ntry:\n delete_external_card(payment_profile.external_api_id, card_id)\nexcept PaymentAPIError as err:\n return Response({'message': str(err), 'detail': err.detail}, status=status.HTTP_400_BAD_REQUEST)\nreturn Response(status=status.HTTP_204_NO... | <|body_start_0|>
payment_profile = self.get_object()
card_id = kwargs['card_id']
try:
delete_external_card(payment_profile.external_api_id, card_id)
except PaymentAPIError as err:
return Response({'message': str(err), 'detail': err.detail}, status=status.HTTP_400_... | retrieve: Return the given payment profile. list: Return a list of all the existing payment profiles. | PaymentProfileViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaymentProfileViewSet:
"""retrieve: Return the given payment profile. list: Return a list of all the existing payment profiles."""
def cards(self, request, *args, **kwargs):
"""This custom action is manually routed in urls.py"""
<|body_0|>
def get_queryset(self):
... | stack_v2_sparse_classes_36k_train_015845 | 19,173 | permissive | [
{
"docstring": "This custom action is manually routed in urls.py",
"name": "cards",
"signature": "def cards(self, request, *args, **kwargs)"
},
{
"docstring": "This viewset should return a user's credit cards except if the currently authenticated user is an admin (is_staff).",
"name": "get_q... | 2 | null | Implement the Python class `PaymentProfileViewSet` described below.
Class description:
retrieve: Return the given payment profile. list: Return a list of all the existing payment profiles.
Method signatures and docstrings:
- def cards(self, request, *args, **kwargs): This custom action is manually routed in urls.py
-... | Implement the Python class `PaymentProfileViewSet` described below.
Class description:
retrieve: Return the given payment profile. list: Return a list of all the existing payment profiles.
Method signatures and docstrings:
- def cards(self, request, *args, **kwargs): This custom action is manually routed in urls.py
-... | 4188745e236eab2056fe8455d81964641301fc3c | <|skeleton|>
class PaymentProfileViewSet:
"""retrieve: Return the given payment profile. list: Return a list of all the existing payment profiles."""
def cards(self, request, *args, **kwargs):
"""This custom action is manually routed in urls.py"""
<|body_0|>
def get_queryset(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PaymentProfileViewSet:
"""retrieve: Return the given payment profile. list: Return a list of all the existing payment profiles."""
def cards(self, request, *args, **kwargs):
"""This custom action is manually routed in urls.py"""
payment_profile = self.get_object()
card_id = kwargs... | the_stack_v2_python_sparse | store/views.py | FJNR-inc/Blitz-API | train | 5 |
d616d705ea09006ae1c9023099bf3d25b1e02fa4 | [
"filter_parser = reqparse.RequestParser(bundle_errors=True)\nfilter_parser.add_argument('page', type=int, default=DEFAULT_PAGE, location='args')\nfilter_parser.add_argument('size', type=int, default=DEFAULT_SITE, location='args')\nfilter_parser_args = filter_parser.parse_args()\nif not filter_parser_args:\n abor... | <|body_start_0|>
filter_parser = reqparse.RequestParser(bundle_errors=True)
filter_parser.add_argument('page', type=int, default=DEFAULT_PAGE, location='args')
filter_parser.add_argument('size', type=int, default=DEFAULT_SITE, location='args')
filter_parser_args = filter_parser.parse_arg... | UsersResource | UsersResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UsersResource:
"""UsersResource"""
def get(self):
"""Example: curl http://0.0.0.0:8000/user curl http://0.0.0.0:8000/user?page=1&size=20 :return:"""
<|body_0|>
def post(self):
"""Example: curl http://0.0.0.0:8000/user -H "Content-Type: application/json" -X POST -... | stack_v2_sparse_classes_36k_train_015846 | 6,420 | permissive | [
{
"docstring": "Example: curl http://0.0.0.0:8000/user curl http://0.0.0.0:8000/user?page=1&size=20 :return:",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Example: curl http://0.0.0.0:8000/user -H \"Content-Type: application/json\" -X POST -d ' { \"user\": { \"name\": \"tom\",... | 3 | null | Implement the Python class `UsersResource` described below.
Class description:
UsersResource
Method signatures and docstrings:
- def get(self): Example: curl http://0.0.0.0:8000/user curl http://0.0.0.0:8000/user?page=1&size=20 :return:
- def post(self): Example: curl http://0.0.0.0:8000/user -H "Content-Type: applic... | Implement the Python class `UsersResource` described below.
Class description:
UsersResource
Method signatures and docstrings:
- def get(self): Example: curl http://0.0.0.0:8000/user curl http://0.0.0.0:8000/user?page=1&size=20 :return:
- def post(self): Example: curl http://0.0.0.0:8000/user -H "Content-Type: applic... | 25729aa7a8a5b38906e60b370609b15e8911ecdd | <|skeleton|>
class UsersResource:
"""UsersResource"""
def get(self):
"""Example: curl http://0.0.0.0:8000/user curl http://0.0.0.0:8000/user?page=1&size=20 :return:"""
<|body_0|>
def post(self):
"""Example: curl http://0.0.0.0:8000/user -H "Content-Type: application/json" -X POST -... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UsersResource:
"""UsersResource"""
def get(self):
"""Example: curl http://0.0.0.0:8000/user curl http://0.0.0.0:8000/user?page=1&size=20 :return:"""
filter_parser = reqparse.RequestParser(bundle_errors=True)
filter_parser.add_argument('page', type=int, default=DEFAULT_PAGE, locati... | the_stack_v2_python_sparse | api_restful/user/resource.py | zhanghe06/bearing_project | train | 2 |
deb00aa717b4af6b81377ac107324c7aa37e06aa | [
"super().setUp()\ncurrent_app.config['DOMAIN_ANALYZER_WATCHED_DOMAINS'] = ['foobar.com']\ncurrent_app.config['DOMAIN_ANALYZER_WATCHED_DOMAINS_THRESHOLD'] = 10\ncurrent_app.config['DOMAIN_ANALYZER_WATCHED_DOMAINS_SCORE_THRESHOLD'] = 0.75\ncurrent_app.config['DOMAIN_ANALYZER_WHITELISTED_DOMAINS'] = ['ytimg.com', 'gst... | <|body_start_0|>
super().setUp()
current_app.config['DOMAIN_ANALYZER_WATCHED_DOMAINS'] = ['foobar.com']
current_app.config['DOMAIN_ANALYZER_WATCHED_DOMAINS_THRESHOLD'] = 10
current_app.config['DOMAIN_ANALYZER_WATCHED_DOMAINS_SCORE_THRESHOLD'] = 0.75
current_app.config['DOMAIN_ANA... | Tests the functionality of the analyzer. | TestDomainsPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDomainsPlugin:
"""Tests the functionality of the analyzer."""
def setUp(self):
"""Set up the tests."""
<|body_0|>
def test_minhash(self):
"""Test minhash function."""
<|body_1|>
def test_get_similar_domains(self):
"""Test get_similar_doma... | stack_v2_sparse_classes_36k_train_015847 | 2,440 | permissive | [
{
"docstring": "Set up the tests.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test minhash function.",
"name": "test_minhash",
"signature": "def test_minhash(self)"
},
{
"docstring": "Test get_similar_domains function.",
"name": "test_get_similar_doma... | 3 | stack_v2_sparse_classes_30k_train_016147 | Implement the Python class `TestDomainsPlugin` described below.
Class description:
Tests the functionality of the analyzer.
Method signatures and docstrings:
- def setUp(self): Set up the tests.
- def test_minhash(self): Test minhash function.
- def test_get_similar_domains(self): Test get_similar_domains function. | Implement the Python class `TestDomainsPlugin` described below.
Class description:
Tests the functionality of the analyzer.
Method signatures and docstrings:
- def setUp(self): Set up the tests.
- def test_minhash(self): Test minhash function.
- def test_get_similar_domains(self): Test get_similar_domains function.
... | 24f471b58ca4a87cb053961b5f05c07a544ca7b8 | <|skeleton|>
class TestDomainsPlugin:
"""Tests the functionality of the analyzer."""
def setUp(self):
"""Set up the tests."""
<|body_0|>
def test_minhash(self):
"""Test minhash function."""
<|body_1|>
def test_get_similar_domains(self):
"""Test get_similar_doma... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDomainsPlugin:
"""Tests the functionality of the analyzer."""
def setUp(self):
"""Set up the tests."""
super().setUp()
current_app.config['DOMAIN_ANALYZER_WATCHED_DOMAINS'] = ['foobar.com']
current_app.config['DOMAIN_ANALYZER_WATCHED_DOMAINS_THRESHOLD'] = 10
cu... | the_stack_v2_python_sparse | timesketch/lib/analyzers/phishy_domains_test.py | google/timesketch | train | 2,263 |
cb4729ab705bbe626b9041fe03e0c19157cb1ce3 | [
"view = super().as_view(*args, **initkwargs)\n\nasync def async_view(*args, **kwargs):\n return await view(*args, **kwargs)\nasync_view.csrf_exempt = True\nreturn async_view",
"self.args = args\nself.kwargs = kwargs\nrequest = self.initialize_request(request, *args, **kwargs)\nself.request = request\nself.head... | <|body_start_0|>
view = super().as_view(*args, **initkwargs)
async def async_view(*args, **kwargs):
return await view(*args, **kwargs)
async_view.csrf_exempt = True
return async_view
<|end_body_0|>
<|body_start_1|>
self.args = args
self.kwargs = kwargs
... | Provides async view compatible support for DRF Views and ViewSets. This must be the first inherited class. For example: class MyAPIViewSet(AsyncMixin, GenericViewSet): pass | AsyncAPIViewMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsyncAPIViewMixin:
"""Provides async view compatible support for DRF Views and ViewSets. This must be the first inherited class. For example: class MyAPIViewSet(AsyncMixin, GenericViewSet): pass"""
def as_view(cls, *args, **initkwargs):
"""Make Django process the view as an async vie... | stack_v2_sparse_classes_36k_train_015848 | 2,587 | no_license | [
{
"docstring": "Make Django process the view as an async view.",
"name": "as_view",
"signature": "def as_view(cls, *args, **initkwargs)"
},
{
"docstring": "Add async support.",
"name": "dispatch",
"signature": "async def dispatch(self, request, *args, **kwargs)"
}
] | 2 | null | Implement the Python class `AsyncAPIViewMixin` described below.
Class description:
Provides async view compatible support for DRF Views and ViewSets. This must be the first inherited class. For example: class MyAPIViewSet(AsyncMixin, GenericViewSet): pass
Method signatures and docstrings:
- def as_view(cls, *args, **... | Implement the Python class `AsyncAPIViewMixin` described below.
Class description:
Provides async view compatible support for DRF Views and ViewSets. This must be the first inherited class. For example: class MyAPIViewSet(AsyncMixin, GenericViewSet): pass
Method signatures and docstrings:
- def as_view(cls, *args, **... | edea4e5b0c382c604db2c3fbb58dc73e57de8431 | <|skeleton|>
class AsyncAPIViewMixin:
"""Provides async view compatible support for DRF Views and ViewSets. This must be the first inherited class. For example: class MyAPIViewSet(AsyncMixin, GenericViewSet): pass"""
def as_view(cls, *args, **initkwargs):
"""Make Django process the view as an async vie... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AsyncAPIViewMixin:
"""Provides async view compatible support for DRF Views and ViewSets. This must be the first inherited class. For example: class MyAPIViewSet(AsyncMixin, GenericViewSet): pass"""
def as_view(cls, *args, **initkwargs):
"""Make Django process the view as an async view."""
... | the_stack_v2_python_sparse | core/views.py | RealGuy69/modularhistory | train | 0 |
aa787d79b7d3d1e2eca1f4b8fa6c6d0db1846b7a | [
"if 'action' not in msg:\n self.msgSend({'code': 'Error', 'msg': 'Missing action.'})\n return\naction = msg['action']\nif action == 'info':\n self.do_info(msg)\n return\nelif action == 'seal':\n self.do_seal(msg)\n return\nelif action == 'head':\n self.do_head(msg)\n return\nelse:\n self.... | <|body_start_0|>
if 'action' not in msg:
self.msgSend({'code': 'Error', 'msg': 'Missing action.'})
return
action = msg['action']
if action == 'info':
self.do_info(msg)
return
elif action == 'seal':
self.do_seal(msg)
... | Rcore | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rcore:
def msgReceived(self, msg):
"""Process incoming messages"""
<|body_0|>
def do_head(self, msg):
"""Returns the current head of the chain."""
<|body_1|>
def do_seal(self, msg):
"""Seals an onject into the chain, and return current head."""
... | stack_v2_sparse_classes_36k_train_015849 | 7,203 | permissive | [
{
"docstring": "Process incoming messages",
"name": "msgReceived",
"signature": "def msgReceived(self, msg)"
},
{
"docstring": "Returns the current head of the chain.",
"name": "do_head",
"signature": "def do_head(self, msg)"
},
{
"docstring": "Seals an onject into the chain, and... | 3 | null | Implement the Python class `Rcore` described below.
Class description:
Implement the Rcore class.
Method signatures and docstrings:
- def msgReceived(self, msg): Process incoming messages
- def do_head(self, msg): Returns the current head of the chain.
- def do_seal(self, msg): Seals an onject into the chain, and ret... | Implement the Python class `Rcore` described below.
Class description:
Implement the Rcore class.
Method signatures and docstrings:
- def msgReceived(self, msg): Process incoming messages
- def do_head(self, msg): Returns the current head of the chain.
- def do_seal(self, msg): Seals an onject into the chain, and ret... | 881fe3e9aac89f42eb7877b480498f910aa37d22 | <|skeleton|>
class Rcore:
def msgReceived(self, msg):
"""Process incoming messages"""
<|body_0|>
def do_head(self, msg):
"""Returns the current head of the chain."""
<|body_1|>
def do_seal(self, msg):
"""Seals an onject into the chain, and return current head."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Rcore:
def msgReceived(self, msg):
"""Process incoming messages"""
if 'action' not in msg:
self.msgSend({'code': 'Error', 'msg': 'Missing action.'})
return
action = msg['action']
if action == 'info':
self.do_info(msg)
return
... | the_stack_v2_python_sparse | rousseau-package/attic/core.py | FrancisPouliot/rousseau-chain | train | 0 | |
283c6a07062c8b18768fb305ce494a20f71e8352 | [
"self._translation_vector = {}\nself._translation_distance = {}\nself._rotation_matrix = {}\nself._rotation_axis = {}\nself._rotation_angle = {}",
"if not id_from in self._translation_vector:\n self._translation_vector[id_from] = {}\nif not id_from in self._translation_distance:\n self._translation_distance... | <|body_start_0|>
self._translation_vector = {}
self._translation_distance = {}
self._rotation_matrix = {}
self._rotation_axis = {}
self._rotation_angle = {}
<|end_body_0|>
<|body_start_1|>
if not id_from in self._translation_vector:
self._translation_vector[i... | A special object for representing rotational and translational displacements between models. | Displacements | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Displacements:
"""A special object for representing rotational and translational displacements between models."""
def __init__(self):
"""Initialise the storage objects."""
<|body_0|>
def _calculate(self, id_from=None, id_to=None, coord_from=None, coord_to=None, centroid=... | stack_v2_sparse_classes_36k_train_015850 | 8,243 | no_license | [
{
"docstring": "Initialise the storage objects.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Calculate the rotational and translational displacements using the given coordinate sets. This uses the U{Kabsch algorithm<http://en.wikipedia.org/wiki/Kabsch_algorithm>}. @... | 4 | null | Implement the Python class `Displacements` described below.
Class description:
A special object for representing rotational and translational displacements between models.
Method signatures and docstrings:
- def __init__(self): Initialise the storage objects.
- def _calculate(self, id_from=None, id_to=None, coord_fro... | Implement the Python class `Displacements` described below.
Class description:
A special object for representing rotational and translational displacements between models.
Method signatures and docstrings:
- def __init__(self): Initialise the storage objects.
- def _calculate(self, id_from=None, id_to=None, coord_fro... | c317326ddeacd1a1c608128769676899daeae531 | <|skeleton|>
class Displacements:
"""A special object for representing rotational and translational displacements between models."""
def __init__(self):
"""Initialise the storage objects."""
<|body_0|>
def _calculate(self, id_from=None, id_to=None, coord_from=None, coord_to=None, centroid=... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Displacements:
"""A special object for representing rotational and translational displacements between models."""
def __init__(self):
"""Initialise the storage objects."""
self._translation_vector = {}
self._translation_distance = {}
self._rotation_matrix = {}
self... | the_stack_v2_python_sparse | lib/structure/internal/displacements.py | jlec/relax | train | 4 |
8c427bb2076e8aeade30aa179a4338e208a62544 | [
"if self.current_user is None:\n return\ntry:\n user_id = int(user_id)\nexcept ValueError:\n self.set_status(400, 'Parameter must be an integer')\nif user_id == self.current_user.id:\n ret = {'user': self.current_user.serialize()}\nelse:\n try:\n user = self.api_endpoint.user_by_id(self.curren... | <|body_start_0|>
if self.current_user is None:
return
try:
user_id = int(user_id)
except ValueError:
self.set_status(400, 'Parameter must be an integer')
if user_id == self.current_user.id:
ret = {'user': self.current_user.serialize()}
... | The User API endpoint. Ops on a single user. | UserAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserAPI:
"""The User API endpoint. Ops on a single user."""
def get(self, user_id):
"""HTTP GET method."""
<|body_0|>
def post(self, user_id):
"""HTTP POST method, to edit a user."""
<|body_1|>
def delete(self, user_id: int):
"""HTTP DELETE m... | stack_v2_sparse_classes_36k_train_015851 | 7,558 | permissive | [
{
"docstring": "HTTP GET method.",
"name": "get",
"signature": "def get(self, user_id)"
},
{
"docstring": "HTTP POST method, to edit a user.",
"name": "post",
"signature": "def post(self, user_id)"
},
{
"docstring": "HTTP DELETE method.",
"name": "delete",
"signature": "d... | 3 | null | Implement the Python class `UserAPI` described below.
Class description:
The User API endpoint. Ops on a single user.
Method signatures and docstrings:
- def get(self, user_id): HTTP GET method.
- def post(self, user_id): HTTP POST method, to edit a user.
- def delete(self, user_id: int): HTTP DELETE method. | Implement the Python class `UserAPI` described below.
Class description:
The User API endpoint. Ops on a single user.
Method signatures and docstrings:
- def get(self, user_id): HTTP GET method.
- def post(self, user_id): HTTP POST method, to edit a user.
- def delete(self, user_id: int): HTTP DELETE method.
<|skele... | c8e0c908af1954a8b41d0f6de23d08589564f0ab | <|skeleton|>
class UserAPI:
"""The User API endpoint. Ops on a single user."""
def get(self, user_id):
"""HTTP GET method."""
<|body_0|>
def post(self, user_id):
"""HTTP POST method, to edit a user."""
<|body_1|>
def delete(self, user_id: int):
"""HTTP DELETE m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserAPI:
"""The User API endpoint. Ops on a single user."""
def get(self, user_id):
"""HTTP GET method."""
if self.current_user is None:
return
try:
user_id = int(user_id)
except ValueError:
self.set_status(400, 'Parameter must be an int... | the_stack_v2_python_sparse | zoe_api/rest_api/user.py | DistributedSystemsGroup/zoe | train | 60 |
b551968c9de039248ef33a8d7247a2552d8bef8d | [
"assert is_unwrappable_to(env, DiscreteEnv)\nassert is_unwrappable_to(env, FeatureWrapper)\nsuper(MaxEntIRL, self).__init__(env, expert_trajs, rl_alg_factory, metrics, config)\nself.transition_matrix = get_transition_matrix(self.env)\nself.n_states, self.n_actions, _ = self.transition_matrix.shape\nfeature_wrapper ... | <|body_start_0|>
assert is_unwrappable_to(env, DiscreteEnv)
assert is_unwrappable_to(env, FeatureWrapper)
super(MaxEntIRL, self).__init__(env, expert_trajs, rl_alg_factory, metrics, config)
self.transition_matrix = get_transition_matrix(self.env)
self.n_states, self.n_actions, _ ... | Maximum Entropy IRL (Ziebart et al., 2008). Not to be confused with Maximum Entropy Deep IRL (Wulfmeier et al., 2016) or Maximum Causal Entropy IRL (Ziebart et al., 2010). | MaxEntIRL | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaxEntIRL:
"""Maximum Entropy IRL (Ziebart et al., 2008). Not to be confused with Maximum Entropy Deep IRL (Wulfmeier et al., 2016) or Maximum Causal Entropy IRL (Ziebart et al., 2010)."""
def __init__(self, env: gym.Env, expert_trajs: List[Dict[str, list]], rl_alg_factory: Callable[[gym.Env... | stack_v2_sparse_classes_36k_train_015852 | 5,210 | no_license | [
{
"docstring": "See :class:`irl_benchmark.irl.algorithms.base_algorithm.BaseIRLAlgorithm`.",
"name": "__init__",
"signature": "def __init__(self, env: gym.Env, expert_trajs: List[Dict[str, list]], rl_alg_factory: Callable[[gym.Env], BaseRLAlgorithm], metrics: List[BaseMetric], config: dict)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_013735 | Implement the Python class `MaxEntIRL` described below.
Class description:
Maximum Entropy IRL (Ziebart et al., 2008). Not to be confused with Maximum Entropy Deep IRL (Wulfmeier et al., 2016) or Maximum Causal Entropy IRL (Ziebart et al., 2010).
Method signatures and docstrings:
- def __init__(self, env: gym.Env, ex... | Implement the Python class `MaxEntIRL` described below.
Class description:
Maximum Entropy IRL (Ziebart et al., 2008). Not to be confused with Maximum Entropy Deep IRL (Wulfmeier et al., 2016) or Maximum Causal Entropy IRL (Ziebart et al., 2010).
Method signatures and docstrings:
- def __init__(self, env: gym.Env, ex... | 8dbf62c79a106e460a542c4008903aec8ec472c6 | <|skeleton|>
class MaxEntIRL:
"""Maximum Entropy IRL (Ziebart et al., 2008). Not to be confused with Maximum Entropy Deep IRL (Wulfmeier et al., 2016) or Maximum Causal Entropy IRL (Ziebart et al., 2010)."""
def __init__(self, env: gym.Env, expert_trajs: List[Dict[str, list]], rl_alg_factory: Callable[[gym.Env... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MaxEntIRL:
"""Maximum Entropy IRL (Ziebart et al., 2008). Not to be confused with Maximum Entropy Deep IRL (Wulfmeier et al., 2016) or Maximum Causal Entropy IRL (Ziebart et al., 2010)."""
def __init__(self, env: gym.Env, expert_trajs: List[Dict[str, list]], rl_alg_factory: Callable[[gym.Env], BaseRLAlgo... | the_stack_v2_python_sparse | irl_benchmark/irl/algorithms/me_irl.py | dit7ya/irl-benchmark-1 | train | 0 |
edf0ab9e9cbc10c0b55a2d16a8416403ee1d8962 | [
"request_json = request.get_json()\ncurrent_app.logger.info('<Receipt.post')\ntry:\n valid_format, errors = schema_utils.validate(request_json, 'payment_receipt_input')\n if not valid_format:\n return error_to_response(Error.INVALID_REQUEST, invalid_params=schema_utils.serialize(errors))\n pdf = Rec... | <|body_start_0|>
request_json = request.get_json()
current_app.logger.info('<Receipt.post')
try:
valid_format, errors = schema_utils.validate(request_json, 'payment_receipt_input')
if not valid_format:
return error_to_response(Error.INVALID_REQUEST, invali... | Endpoint resource to create receipt.Use this endpoint when no invoice number is available. | InvoiceReceipt | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InvoiceReceipt:
"""Endpoint resource to create receipt.Use this endpoint when no invoice number is available."""
def post(invoice_id):
"""Create the Receipt for the Invoice."""
<|body_0|>
def get(invoice_id):
"""Return the receipt details."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_015853 | 3,171 | permissive | [
{
"docstring": "Create the Receipt for the Invoice.",
"name": "post",
"signature": "def post(invoice_id)"
},
{
"docstring": "Return the receipt details.",
"name": "get",
"signature": "def get(invoice_id)"
}
] | 2 | null | Implement the Python class `InvoiceReceipt` described below.
Class description:
Endpoint resource to create receipt.Use this endpoint when no invoice number is available.
Method signatures and docstrings:
- def post(invoice_id): Create the Receipt for the Invoice.
- def get(invoice_id): Return the receipt details. | Implement the Python class `InvoiceReceipt` described below.
Class description:
Endpoint resource to create receipt.Use this endpoint when no invoice number is available.
Method signatures and docstrings:
- def post(invoice_id): Create the Receipt for the Invoice.
- def get(invoice_id): Return the receipt details.
<... | 0d71d37b0e08d11f6b6d9f59a4b202dfabc98fc1 | <|skeleton|>
class InvoiceReceipt:
"""Endpoint resource to create receipt.Use this endpoint when no invoice number is available."""
def post(invoice_id):
"""Create the Receipt for the Invoice."""
<|body_0|>
def get(invoice_id):
"""Return the receipt details."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InvoiceReceipt:
"""Endpoint resource to create receipt.Use this endpoint when no invoice number is available."""
def post(invoice_id):
"""Create the Receipt for the Invoice."""
request_json = request.get_json()
current_app.logger.info('<Receipt.post')
try:
vali... | the_stack_v2_python_sparse | pay-api/src/pay_api/resources/invoice_receipt.py | bcgov/sbc-pay | train | 6 |
66d135add0f3af6a47237814a5fac2d081e39acd | [
"self.ip = ip\nif self.ip.find('/') != -1:\n self.has_netmask = True\n self.ip_obj = IPy.IP(self.ip)\nelse:\n self.has_netmask = False\n self.ip_obj = None",
"if self.has_netmask:\n return ip in self.ip_obj\nelse:\n return ip == self.ip"
] | <|body_start_0|>
self.ip = ip
if self.ip.find('/') != -1:
self.has_netmask = True
self.ip_obj = IPy.IP(self.ip)
else:
self.has_netmask = False
self.ip_obj = None
<|end_body_0|>
<|body_start_1|>
if self.has_netmask:
return ip in... | IP | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IP:
def __init__(self, ip):
"""ip(str): ip or ip/netmask"""
<|body_0|>
def __eq__(self, ip):
"""check if "ip" is equals or --included-- in this IP Address"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.ip = ip
if self.ip.find('/') != -... | stack_v2_sparse_classes_36k_train_015854 | 2,218 | no_license | [
{
"docstring": "ip(str): ip or ip/netmask",
"name": "__init__",
"signature": "def __init__(self, ip)"
},
{
"docstring": "check if \"ip\" is equals or --included-- in this IP Address",
"name": "__eq__",
"signature": "def __eq__(self, ip)"
}
] | 2 | null | Implement the Python class `IP` described below.
Class description:
Implement the IP class.
Method signatures and docstrings:
- def __init__(self, ip): ip(str): ip or ip/netmask
- def __eq__(self, ip): check if "ip" is equals or --included-- in this IP Address | Implement the Python class `IP` described below.
Class description:
Implement the IP class.
Method signatures and docstrings:
- def __init__(self, ip): ip(str): ip or ip/netmask
- def __eq__(self, ip): check if "ip" is equals or --included-- in this IP Address
<|skeleton|>
class IP:
def __init__(self, ip):
... | 596aa468f8264ab0129431e3ede6cc1282b1ebbd | <|skeleton|>
class IP:
def __init__(self, ip):
"""ip(str): ip or ip/netmask"""
<|body_0|>
def __eq__(self, ip):
"""check if "ip" is equals or --included-- in this IP Address"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IP:
def __init__(self, ip):
"""ip(str): ip or ip/netmask"""
self.ip = ip
if self.ip.find('/') != -1:
self.has_netmask = True
self.ip_obj = IPy.IP(self.ip)
else:
self.has_netmask = False
self.ip_obj = None
def __eq__(self, ip)... | the_stack_v2_python_sparse | core/lib/iplib.py | ha8sh/IBSng | train | 1 | |
7ff391c97e7b508094939678f69a82a783c729ab | [
"self.sigma_ = sigma_\nself.lambda_ = lambda_\nself.fitsigma = fitsigma\nself.fitlambda = fitlambda\nself.coef_ = coef_\nself.intercept_ = intercept_",
"X = np.array(X)\nY = np.array(Y)\nif len(X.shape) == 1:\n X = X.reshape(-1, 1)\nself.X = np.append(X, np.ones((X.shape[0], 1)), axis=1)\nself.updateW(Y=Y)\nif... | <|body_start_0|>
self.sigma_ = sigma_
self.lambda_ = lambda_
self.fitsigma = fitsigma
self.fitlambda = fitlambda
self.coef_ = coef_
self.intercept_ = intercept_
<|end_body_0|>
<|body_start_1|>
X = np.array(X)
Y = np.array(Y)
if len(X.shape) == 1:
... | BayesianRegress | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BayesianRegress:
def __init__(self, lambda_=0.1, sigma_=2.5, coef_=None, intercept_=None, fitsigma=True, fitlambda=False):
"""Initialize a Bayesian regressor. _lambda: L2 constrains of weights _sigma: square root of variance."""
<|body_0|>
def fit(self, X, Y):
"""Fit... | stack_v2_sparse_classes_36k_train_015855 | 15,651 | permissive | [
{
"docstring": "Initialize a Bayesian regressor. _lambda: L2 constrains of weights _sigma: square root of variance.",
"name": "__init__",
"signature": "def __init__(self, lambda_=0.1, sigma_=2.5, coef_=None, intercept_=None, fitsigma=True, fitlambda=False)"
},
{
"docstring": "Fit the model.",
... | 4 | stack_v2_sparse_classes_30k_train_007200 | Implement the Python class `BayesianRegress` described below.
Class description:
Implement the BayesianRegress class.
Method signatures and docstrings:
- def __init__(self, lambda_=0.1, sigma_=2.5, coef_=None, intercept_=None, fitsigma=True, fitlambda=False): Initialize a Bayesian regressor. _lambda: L2 constrains of... | Implement the Python class `BayesianRegress` described below.
Class description:
Implement the BayesianRegress class.
Method signatures and docstrings:
- def __init__(self, lambda_=0.1, sigma_=2.5, coef_=None, intercept_=None, fitsigma=True, fitlambda=False): Initialize a Bayesian regressor. _lambda: L2 constrains of... | 06559cef6a43888f015117f25734125f95b34484 | <|skeleton|>
class BayesianRegress:
def __init__(self, lambda_=0.1, sigma_=2.5, coef_=None, intercept_=None, fitsigma=True, fitlambda=False):
"""Initialize a Bayesian regressor. _lambda: L2 constrains of weights _sigma: square root of variance."""
<|body_0|>
def fit(self, X, Y):
"""Fit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BayesianRegress:
def __init__(self, lambda_=0.1, sigma_=2.5, coef_=None, intercept_=None, fitsigma=True, fitlambda=False):
"""Initialize a Bayesian regressor. _lambda: L2 constrains of weights _sigma: square root of variance."""
self.sigma_ = sigma_
self.lambda_ = lambda_
self.... | the_stack_v2_python_sparse | brie/version1/model_brie.py | huangyh09/brie | train | 45 | |
4e42e313b4e8f4517cca59865a67badc6b525b39 | [
"n = len(grid)\np = [[(i, j) for j in range(n)] for i in range(n)]\nh = sorted([[grid[i][j], i, j] for j in range(n) for i in range(n)])\n\ndef f(a, b):\n if (a, b) != p[a][b]:\n p[a][b] = f(*p[a][b])\n return p[a][b]\nk = 0\nfor t in range(max(grid[0][0], grid[-1][-1]), h[-1][0]):\n while h[k][0] <... | <|body_start_0|>
n = len(grid)
p = [[(i, j) for j in range(n)] for i in range(n)]
h = sorted([[grid[i][j], i, j] for j in range(n) for i in range(n)])
def f(a, b):
if (a, b) != p[a][b]:
p[a][b] = f(*p[a][b])
return p[a][b]
k = 0
fo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def swim_in_water(grid: List[List[int]]) -> int:
"""并查集 @param grid: @return:"""
<|body_0|>
def swim_in_water_v2(grid: List[List[int]]) -> int:
"""BFS @param grid: @return:"""
<|body_1|>
def swim_in_water_v3(grid: List[List[int]]) -> int:
... | stack_v2_sparse_classes_36k_train_015856 | 6,600 | no_license | [
{
"docstring": "并查集 @param grid: @return:",
"name": "swim_in_water",
"signature": "def swim_in_water(grid: List[List[int]]) -> int"
},
{
"docstring": "BFS @param grid: @return:",
"name": "swim_in_water_v2",
"signature": "def swim_in_water_v2(grid: List[List[int]]) -> int"
},
{
"d... | 4 | stack_v2_sparse_classes_30k_train_015380 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swim_in_water(grid: List[List[int]]) -> int: 并查集 @param grid: @return:
- def swim_in_water_v2(grid: List[List[int]]) -> int: BFS @param grid: @return:
- def swim_in_water_v3(... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swim_in_water(grid: List[List[int]]) -> int: 并查集 @param grid: @return:
- def swim_in_water_v2(grid: List[List[int]]) -> int: BFS @param grid: @return:
- def swim_in_water_v3(... | 1d1876620a55ff88af7bc390cf1a4fd4350d8d16 | <|skeleton|>
class Solution:
def swim_in_water(grid: List[List[int]]) -> int:
"""并查集 @param grid: @return:"""
<|body_0|>
def swim_in_water_v2(grid: List[List[int]]) -> int:
"""BFS @param grid: @return:"""
<|body_1|>
def swim_in_water_v3(grid: List[List[int]]) -> int:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def swim_in_water(grid: List[List[int]]) -> int:
"""并查集 @param grid: @return:"""
n = len(grid)
p = [[(i, j) for j in range(n)] for i in range(n)]
h = sorted([[grid[i][j], i, j] for j in range(n) for i in range(n)])
def f(a, b):
if (a, b) != p[a][b... | the_stack_v2_python_sparse | 02-算法思想/广度优先搜索/778.水位上升的泳池中游泳(H).py | jh-lau/leetcode_in_python | train | 0 | |
7832225e48e1e4f5c0d50cfc54300dcc2910dfef | [
"self.read_data(filename)\nself.prep_dataset()\nself.standardize()\nself.apply_PCA()",
"with open(filename) as infile:\n next(infile)\n for line in infile:\n line = line.strip().split(',')\n features = line[:-2]\n features = list(map(float, features))\n self.targets.append(line[-... | <|body_start_0|>
self.read_data(filename)
self.prep_dataset()
self.standardize()
self.apply_PCA()
<|end_body_0|>
<|body_start_1|>
with open(filename) as infile:
next(infile)
for line in infile:
line = line.strip().split(',')
... | At this stage we initialize the variables needed in the various methods below. | PCA | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PCA:
"""At this stage we initialize the variables needed in the various methods below."""
def __init__(self, filename):
"""Initialization method - acts as a controller Args: filename (string): path to the file to process"""
<|body_0|>
def read_data(self, filename):
... | stack_v2_sparse_classes_36k_train_015857 | 4,762 | no_license | [
{
"docstring": "Initialization method - acts as a controller Args: filename (string): path to the file to process",
"name": "__init__",
"signature": "def __init__(self, filename)"
},
{
"docstring": "Loads in the specified file. Creates features vector and targets vector Args: filename (string): ... | 5 | stack_v2_sparse_classes_30k_train_015064 | Implement the Python class `PCA` described below.
Class description:
At this stage we initialize the variables needed in the various methods below.
Method signatures and docstrings:
- def __init__(self, filename): Initialization method - acts as a controller Args: filename (string): path to the file to process
- def ... | Implement the Python class `PCA` described below.
Class description:
At this stage we initialize the variables needed in the various methods below.
Method signatures and docstrings:
- def __init__(self, filename): Initialization method - acts as a controller Args: filename (string): path to the file to process
- def ... | 1106cf0dbc88490fd925f1c7c8e27dc088f29de9 | <|skeleton|>
class PCA:
"""At this stage we initialize the variables needed in the various methods below."""
def __init__(self, filename):
"""Initialization method - acts as a controller Args: filename (string): path to the file to process"""
<|body_0|>
def read_data(self, filename):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PCA:
"""At this stage we initialize the variables needed in the various methods below."""
def __init__(self, filename):
"""Initialization method - acts as a controller Args: filename (string): path to the file to process"""
self.read_data(filename)
self.prep_dataset()
self... | the_stack_v2_python_sparse | src/PCA/dim_red.py | flight505/Shared_Intro_ML | train | 0 |
d2b1908815875ef9a26bcb5af85bcf7ade7de7e8 | [
"next_nodes = [[] for _ in range(numCourses)]\nin_degree = [0] * numCourses\nfree_courses = []\nfor edge in prerequisites:\n next_nodes[edge[1]].append(edge[0])\n in_degree[edge[0]] += 1\nfor i in range(len(in_degree)):\n if in_degree[i] == 0:\n free_courses.append(i)\nfor i in free_courses:\n fo... | <|body_start_0|>
next_nodes = [[] for _ in range(numCourses)]
in_degree = [0] * numCourses
free_courses = []
for edge in prerequisites:
next_nodes[edge[1]].append(edge[0])
in_degree[edge[0]] += 1
for i in range(len(in_degree)):
if in_degree[i] ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canFinish(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rtype: bool"""
<|body_0|>
def canFinish1(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rtype: b... | stack_v2_sparse_classes_36k_train_015858 | 2,912 | no_license | [
{
"docstring": ":type numCourses: int :type prerequisites: List[List[int]] :rtype: bool",
"name": "canFinish",
"signature": "def canFinish(self, numCourses, prerequisites)"
},
{
"docstring": ":type numCourses: int :type prerequisites: List[List[int]] :rtype: bool",
"name": "canFinish1",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canFinish(self, numCourses, prerequisites): :type numCourses: int :type prerequisites: List[List[int]] :rtype: bool
- def canFinish1(self, numCourses, prerequisites): :type n... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canFinish(self, numCourses, prerequisites): :type numCourses: int :type prerequisites: List[List[int]] :rtype: bool
- def canFinish1(self, numCourses, prerequisites): :type n... | ff9118b8a0ce9a3db89c2bf6f2f79def7ae4f17f | <|skeleton|>
class Solution:
def canFinish(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rtype: bool"""
<|body_0|>
def canFinish1(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rtype: b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canFinish(self, numCourses, prerequisites):
""":type numCourses: int :type prerequisites: List[List[int]] :rtype: bool"""
next_nodes = [[] for _ in range(numCourses)]
in_degree = [0] * numCourses
free_courses = []
for edge in prerequisites:
nex... | the_stack_v2_python_sparse | 201-300/207.py | JianghaoPi/LeetCode | train | 0 | |
679907b3f6ce26210793a204bcf396f0834bc00b | [
"self._width = width\nself._height = height\nself._images = {}\nreturn",
"bmp = self._images.get(filename)\nif bmp is None:\n image = wx.Image(filename, wx.BITMAP_TYPE_ANY)\n self._scale(image)\n bmp = image.ConvertToBitmap()\n self._images[filename] = bmp\nreturn bmp",
"if image.GetWidth() != self.... | <|body_start_0|>
self._width = width
self._height = height
self._images = {}
return
<|end_body_0|>
<|body_start_1|>
bmp = self._images.get(filename)
if bmp is None:
image = wx.Image(filename, wx.BITMAP_TYPE_ANY)
self._scale(image)
bmp ... | An image cache. | ImageCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageCache:
"""An image cache."""
def __init__(self, width, height):
"""Creates a new image cache."""
<|body_0|>
def get_image(self, filename):
"""Returns the specified image (currently as a bitmap)."""
<|body_1|>
def _scale(self, image):
"""... | stack_v2_sparse_classes_36k_train_015859 | 2,463 | no_license | [
{
"docstring": "Creates a new image cache.",
"name": "__init__",
"signature": "def __init__(self, width, height)"
},
{
"docstring": "Returns the specified image (currently as a bitmap).",
"name": "get_image",
"signature": "def get_image(self, filename)"
},
{
"docstring": "Scales ... | 3 | stack_v2_sparse_classes_30k_val_000464 | Implement the Python class `ImageCache` described below.
Class description:
An image cache.
Method signatures and docstrings:
- def __init__(self, width, height): Creates a new image cache.
- def get_image(self, filename): Returns the specified image (currently as a bitmap).
- def _scale(self, image): Scales the spec... | Implement the Python class `ImageCache` described below.
Class description:
An image cache.
Method signatures and docstrings:
- def __init__(self, width, height): Creates a new image cache.
- def get_image(self, filename): Returns the specified image (currently as a bitmap).
- def _scale(self, image): Scales the spec... | 5466f5858dbd2f1f082fa0d7417b57c8fb068fad | <|skeleton|>
class ImageCache:
"""An image cache."""
def __init__(self, width, height):
"""Creates a new image cache."""
<|body_0|>
def get_image(self, filename):
"""Returns the specified image (currently as a bitmap)."""
<|body_1|>
def _scale(self, image):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageCache:
"""An image cache."""
def __init__(self, width, height):
"""Creates a new image cache."""
self._width = width
self._height = height
self._images = {}
return
def get_image(self, filename):
"""Returns the specified image (currently as a bitma... | the_stack_v2_python_sparse | maps/build/EnthoughtBase/enthought/util/wx/image_cache.py | m-elhussieny/code | train | 0 |
6fde25b4153077941d4ca6b053202548df1bb508 | [
"h = bandpass_data_fits('sdss3_filter_responses.fits')\nsection = 'ugriz'.index(band[0]) + 1\nd = h[section].data\nif d.wavelength.dtype.isnative:\n df = pd.DataFrame({'wlen': d.wavelength, 'resp': d.respt})\nelse:\n df = pd.DataFrame({'wlen': d.wavelength.byteswap(True).newbyteorder(), 'resp': d.respt.bytesw... | <|body_start_0|>
h = bandpass_data_fits('sdss3_filter_responses.fits')
section = 'ugriz'.index(band[0]) + 1
d = h[section].data
if d.wavelength.dtype.isnative:
df = pd.DataFrame({'wlen': d.wavelength, 'resp': d.respt})
else:
df = pd.DataFrame({'wlen': d.wa... | SdssBandpass | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SdssBandpass:
def _load_data(self, band):
"""Filter responses for SDSS. Data table from https://www.sdss3.org/binaries/filter_curves.fits, as linked from https://www.sdss3.org/instruments/camera.php#Filters. SHA1 hash of the file is d3f638c41e21489ba7d6dbe7bb8217d938f21184. "Determined b... | stack_v2_sparse_classes_36k_train_015860 | 34,146 | permissive | [
{
"docstring": "Filter responses for SDSS. Data table from https://www.sdss3.org/binaries/filter_curves.fits, as linked from https://www.sdss3.org/instruments/camera.php#Filters. SHA1 hash of the file is d3f638c41e21489ba7d6dbe7bb8217d938f21184. \"Determined by Jim Gunn in June 2001.\" Doi+ 2010 have updated es... | 2 | null | Implement the Python class `SdssBandpass` described below.
Class description:
Implement the SdssBandpass class.
Method signatures and docstrings:
- def _load_data(self, band): Filter responses for SDSS. Data table from https://www.sdss3.org/binaries/filter_curves.fits, as linked from https://www.sdss3.org/instruments... | Implement the Python class `SdssBandpass` described below.
Class description:
Implement the SdssBandpass class.
Method signatures and docstrings:
- def _load_data(self, band): Filter responses for SDSS. Data table from https://www.sdss3.org/binaries/filter_curves.fits, as linked from https://www.sdss3.org/instruments... | ff0ac3d9cc563b441143cf73f282dd4ae98c7a51 | <|skeleton|>
class SdssBandpass:
def _load_data(self, band):
"""Filter responses for SDSS. Data table from https://www.sdss3.org/binaries/filter_curves.fits, as linked from https://www.sdss3.org/instruments/camera.php#Filters. SHA1 hash of the file is d3f638c41e21489ba7d6dbe7bb8217d938f21184. "Determined b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SdssBandpass:
def _load_data(self, band):
"""Filter responses for SDSS. Data table from https://www.sdss3.org/binaries/filter_curves.fits, as linked from https://www.sdss3.org/instruments/camera.php#Filters. SHA1 hash of the file is d3f638c41e21489ba7d6dbe7bb8217d938f21184. "Determined by Jim Gunn in ... | the_stack_v2_python_sparse | pwkit/synphot.py | pkgw/pwkit | train | 24 | |
0528402cc2c7e48fa740de49ee4e7ac618ef613c | [
"self.conn = Connection(password=get_environment_variable('VEN_ADWORDS_PASSWORD'), developer_token=get_environment_variable('VEN_ADWORDS_TOKEN'), account_id=account_id)\nself.awq = AWQ(self.conn)\nself.gmoney = GMoney(min_money=min_money, max_money=max_money)\nself.ops = Operations(self.gmoney)\nself.mutations = Mu... | <|body_start_0|>
self.conn = Connection(password=get_environment_variable('VEN_ADWORDS_PASSWORD'), developer_token=get_environment_variable('VEN_ADWORDS_TOKEN'), account_id=account_id)
self.awq = AWQ(self.conn)
self.gmoney = GMoney(min_money=min_money, max_money=max_money)
self.ops = Ope... | KeywordOperationsBase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeywordOperationsBase:
def __init__(self, account_id='7998744469', store=None, min_money=None, max_money=None, logging_level=logging.DEBUG, chk_size=5000):
"""Pass in min and max (in Euros, NOT micros) based bid if you want to override the GMoney defaults store: storage that acts like an... | stack_v2_sparse_classes_36k_train_015861 | 3,450 | permissive | [
{
"docstring": "Pass in min and max (in Euros, NOT micros) based bid if you want to override the GMoney defaults store: storage that acts like an HDF5 store",
"name": "__init__",
"signature": "def __init__(self, account_id='7998744469', store=None, min_money=None, max_money=None, logging_level=logging.D... | 4 | stack_v2_sparse_classes_30k_train_006595 | Implement the Python class `KeywordOperationsBase` described below.
Class description:
Implement the KeywordOperationsBase class.
Method signatures and docstrings:
- def __init__(self, account_id='7998744469', store=None, min_money=None, max_money=None, logging_level=logging.DEBUG, chk_size=5000): Pass in min and max... | Implement the Python class `KeywordOperationsBase` described below.
Class description:
Implement the KeywordOperationsBase class.
Method signatures and docstrings:
- def __init__(self, account_id='7998744469', store=None, min_money=None, max_money=None, logging_level=logging.DEBUG, chk_size=5000): Pass in min and max... | 72dbdf41b0250708ad525030128cc7c3948b3f41 | <|skeleton|>
class KeywordOperationsBase:
def __init__(self, account_id='7998744469', store=None, min_money=None, max_money=None, logging_level=logging.DEBUG, chk_size=5000):
"""Pass in min and max (in Euros, NOT micros) based bid if you want to override the GMoney defaults store: storage that acts like an... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KeywordOperationsBase:
def __init__(self, account_id='7998744469', store=None, min_money=None, max_money=None, logging_level=logging.DEBUG, chk_size=5000):
"""Pass in min and max (in Euros, NOT micros) based bid if you want to override the GMoney defaults store: storage that acts like an HDF5 store"""... | the_stack_v2_python_sparse | ut/aw/keyword_operations_base.py | thorwhalen/ut | train | 6 | |
392e13a14c9614d39a6ae478afd18406c5ce23eb | [
"print('Received GET on resource /books/<book_id>/notes')\nif book_id.isdigit():\n list_notes = NoteChecker.get_notes(book_id)\n return (list_notes, 200)\nelse:\n abort(400, 'Invalid input for book_id')",
"print('Received POST on resource /books/<book_id>/notes')\nif book_id.isdigit():\n note = NoteCh... | <|body_start_0|>
print('Received GET on resource /books/<book_id>/notes')
if book_id.isdigit():
list_notes = NoteChecker.get_notes(book_id)
return (list_notes, 200)
else:
abort(400, 'Invalid input for book_id')
<|end_body_0|>
<|body_start_1|>
print('R... | BookNotes | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BookNotes:
def get(self, book_id):
"""Gets the book notes for a specific book. :param book_id: Record of book. :return: JSON List of notes for a specific book."""
<|body_0|>
def post(self, book_id):
"""Creates a new note for a book. :param book_id: Record for a book.... | stack_v2_sparse_classes_36k_train_015862 | 14,158 | no_license | [
{
"docstring": "Gets the book notes for a specific book. :param book_id: Record of book. :return: JSON List of notes for a specific book.",
"name": "get",
"signature": "def get(self, book_id)"
},
{
"docstring": "Creates a new note for a book. :param book_id: Record for a book. :return: JSON of c... | 2 | stack_v2_sparse_classes_30k_train_018785 | Implement the Python class `BookNotes` described below.
Class description:
Implement the BookNotes class.
Method signatures and docstrings:
- def get(self, book_id): Gets the book notes for a specific book. :param book_id: Record of book. :return: JSON List of notes for a specific book.
- def post(self, book_id): Cre... | Implement the Python class `BookNotes` described below.
Class description:
Implement the BookNotes class.
Method signatures and docstrings:
- def get(self, book_id): Gets the book notes for a specific book. :param book_id: Record of book. :return: JSON List of notes for a specific book.
- def post(self, book_id): Cre... | 4c3fdf41a43a56c253faecacac5f9d977d9c99be | <|skeleton|>
class BookNotes:
def get(self, book_id):
"""Gets the book notes for a specific book. :param book_id: Record of book. :return: JSON List of notes for a specific book."""
<|body_0|>
def post(self, book_id):
"""Creates a new note for a book. :param book_id: Record for a book.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BookNotes:
def get(self, book_id):
"""Gets the book notes for a specific book. :param book_id: Record of book. :return: JSON List of notes for a specific book."""
print('Received GET on resource /books/<book_id>/notes')
if book_id.isdigit():
list_notes = NoteChecker.get_not... | the_stack_v2_python_sparse | apis/books_api.py | neu-seattle-cs5500-fall18/book-library-web-service-scrumptious | train | 0 | |
e37c7a2b403a5ea08a4c4dca7671bbb891921288 | [
"super(SelfOutput, self).__init__()\nself.connecter = nn.Linear(hidden_size, hidden_size)\nself.LayerNorm = LayerNorm(hidden_size)\nself.dropout = nn.Dropout(hidden_dropout_ratio)",
"hidden_states = self.connecter(hidden_states)\nhidden_states = self.dropout(hidden_states)\nhidden_states = self.LayerNorm(hidden_s... | <|body_start_0|>
super(SelfOutput, self).__init__()
self.connecter = nn.Linear(hidden_size, hidden_size)
self.LayerNorm = LayerNorm(hidden_size)
self.dropout = nn.Dropout(hidden_dropout_ratio)
<|end_body_0|>
<|body_start_1|>
hidden_states = self.connecter(hidden_states)
... | Self-Output Layer | SelfOutput | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfOutput:
"""Self-Output Layer"""
def __init__(self, hidden_size, hidden_dropout_ratio):
"""Initialization"""
<|body_0|>
def forward(self, hidden_states, input_tensor):
"""Self-output block"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super... | stack_v2_sparse_classes_36k_train_015863 | 12,741 | permissive | [
{
"docstring": "Initialization",
"name": "__init__",
"signature": "def __init__(self, hidden_size, hidden_dropout_ratio)"
},
{
"docstring": "Self-output block",
"name": "forward",
"signature": "def forward(self, hidden_states, input_tensor)"
}
] | 2 | null | Implement the Python class `SelfOutput` described below.
Class description:
Self-Output Layer
Method signatures and docstrings:
- def __init__(self, hidden_size, hidden_dropout_ratio): Initialization
- def forward(self, hidden_states, input_tensor): Self-output block | Implement the Python class `SelfOutput` described below.
Class description:
Self-Output Layer
Method signatures and docstrings:
- def __init__(self, hidden_size, hidden_dropout_ratio): Initialization
- def forward(self, hidden_states, input_tensor): Self-output block
<|skeleton|>
class SelfOutput:
"""Self-Output... | e6ab0261eb719c21806bbadfd94001ecfe27de45 | <|skeleton|>
class SelfOutput:
"""Self-Output Layer"""
def __init__(self, hidden_size, hidden_dropout_ratio):
"""Initialization"""
<|body_0|>
def forward(self, hidden_states, input_tensor):
"""Self-output block"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SelfOutput:
"""Self-Output Layer"""
def __init__(self, hidden_size, hidden_dropout_ratio):
"""Initialization"""
super(SelfOutput, self).__init__()
self.connecter = nn.Linear(hidden_size, hidden_size)
self.LayerNorm = LayerNorm(hidden_size)
self.dropout = nn.Dropout... | the_stack_v2_python_sparse | apps/drug_target_interaction/moltrans_dti/double_towers.py | PaddlePaddle/PaddleHelix | train | 771 |
57a9408a247c68ecb4ce04953c0ee1d4c88c29cb | [
"recent_candles = self.get_latest_candles(symbol, 60 * 12)\nif not SymbolDay.validate_candles(recent_candles, min_minutes=60 * 12):\n self.error_process('High96PctModel candles ({}): {}'.format(len(recent_candles), [candle.open for candle in recent_candles][0:3]))\n raise ValueError('High96PctModel loaded inv... | <|body_start_0|>
recent_candles = self.get_latest_candles(symbol, 60 * 12)
if not SymbolDay.validate_candles(recent_candles, min_minutes=60 * 12):
self.error_process('High96PctModel candles ({}): {}'.format(len(recent_candles), [candle.open for candle in recent_candles][0:3]))
ra... | Checks that the 12-hour high is within the upper 4% of the symbol's 75-week price range. E.g. if the 75-week range is [$24.19, $29.48], then the price must have exceeded $29.27 within the last 12 hours. | High96PctModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class High96PctModel:
"""Checks that the 12-hour high is within the upper 4% of the symbol's 75-week price range. E.g. if the 75-week range is [$24.19, $29.48], then the price must have exceeded $29.27 within the last 12 hours."""
def calculate_output(self, symbol: str) -> OUTPUT_TYPE:
"""... | stack_v2_sparse_classes_36k_train_015864 | 2,700 | no_license | [
{
"docstring": "Returns True if the symbol's 12-hour high falls in the upper 4% of its 75-day range, False otherwise.",
"name": "calculate_output",
"signature": "def calculate_output(self, symbol: str) -> OUTPUT_TYPE"
},
{
"docstring": "Assigns a pass/fail grade depending on whether the model ou... | 2 | null | Implement the Python class `High96PctModel` described below.
Class description:
Checks that the 12-hour high is within the upper 4% of the symbol's 75-week price range. E.g. if the 75-week range is [$24.19, $29.48], then the price must have exceeded $29.27 within the last 12 hours.
Method signatures and docstrings:
-... | Implement the Python class `High96PctModel` described below.
Class description:
Checks that the 12-hour high is within the upper 4% of the symbol's 75-week price range. E.g. if the 75-week range is [$24.19, $29.48], then the price must have exceeded $29.27 within the last 12 hours.
Method signatures and docstrings:
-... | 3e067af6840e41d15a6b46ca5f5828000df35321 | <|skeleton|>
class High96PctModel:
"""Checks that the 12-hour high is within the upper 4% of the symbol's 75-week price range. E.g. if the 75-week range is [$24.19, $29.48], then the price must have exceeded $29.27 within the last 12 hours."""
def calculate_output(self, symbol: str) -> OUTPUT_TYPE:
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class High96PctModel:
"""Checks that the 12-hour high is within the upper 4% of the symbol's 75-week price range. E.g. if the 75-week range is [$24.19, $29.48], then the price must have exceeded $29.27 within the last 12 hours."""
def calculate_output(self, symbol: str) -> OUTPUT_TYPE:
"""Returns True ... | the_stack_v2_python_sparse | backend/tc2/stock_analysis/strategy_models/swing_strategy/High96PctModel.py | maxilie/TC2_public | train | 0 |
63576f0fa6e838cb96749d405c76ad665ab3f63d | [
"super(InceptionV3, self).__init__()\nself.resize_input = resize_input\nself.normalize_input = normalize_input\nself.output_blocks = sorted(output_blocks)\nself.last_needed_block = max(output_blocks)\nassert self.last_needed_block <= 3, 'Last possible output block index is 3'\nself.blocks = nn.ModuleList()\nif use_... | <|body_start_0|>
super(InceptionV3, self).__init__()
self.resize_input = resize_input
self.normalize_input = normalize_input
self.output_blocks = sorted(output_blocks)
self.last_needed_block = max(output_blocks)
assert self.last_needed_block <= 3, 'Last possible output bl... | Pretrained InceptionV3 network returning feature maps | InceptionV3 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InceptionV3:
"""Pretrained InceptionV3 network returning feature maps"""
def __init__(self, output_blocks=[DEFAULT_BLOCK_INDEX], resize_input=True, normalize_input=True, requires_grad=False, use_fid_inception=True):
"""Build pretrained InceptionV3 Parameters ---------- output_blocks ... | stack_v2_sparse_classes_36k_train_015865 | 21,318 | no_license | [
{
"docstring": "Build pretrained InceptionV3 Parameters ---------- output_blocks : list of int Indices of blocks to return features of. Possible values are: - 0: corresponds to output of first max pooling - 1: corresponds to output of second max pooling - 2: corresponds to output which is fed to aux classifier ... | 2 | null | Implement the Python class `InceptionV3` described below.
Class description:
Pretrained InceptionV3 network returning feature maps
Method signatures and docstrings:
- def __init__(self, output_blocks=[DEFAULT_BLOCK_INDEX], resize_input=True, normalize_input=True, requires_grad=False, use_fid_inception=True): Build pr... | Implement the Python class `InceptionV3` described below.
Class description:
Pretrained InceptionV3 network returning feature maps
Method signatures and docstrings:
- def __init__(self, output_blocks=[DEFAULT_BLOCK_INDEX], resize_input=True, normalize_input=True, requires_grad=False, use_fid_inception=True): Build pr... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class InceptionV3:
"""Pretrained InceptionV3 network returning feature maps"""
def __init__(self, output_blocks=[DEFAULT_BLOCK_INDEX], resize_input=True, normalize_input=True, requires_grad=False, use_fid_inception=True):
"""Build pretrained InceptionV3 Parameters ---------- output_blocks ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InceptionV3:
"""Pretrained InceptionV3 network returning feature maps"""
def __init__(self, output_blocks=[DEFAULT_BLOCK_INDEX], resize_input=True, normalize_input=True, requires_grad=False, use_fid_inception=True):
"""Build pretrained InceptionV3 Parameters ---------- output_blocks : list of int... | the_stack_v2_python_sparse | generated/test_VITA_Group_GAN_Slimming.py | jansel/pytorch-jit-paritybench | train | 35 |
fef0718cc414c04acfbe29ae1e5413ade5c204b6 | [
"self.val_flag_list = []\nself.vals = set([])\nself.val_to_index = {}",
"flag = False\nif val not in self.vals:\n flag = True\n self.vals.add(val)\n if self.val_to_index.get(val, -1) == -1:\n self.val_flag_list.append([val, 1])\n self.val_to_index[val] = len(self.val_flag_list) - 1\n els... | <|body_start_0|>
self.val_flag_list = []
self.vals = set([])
self.val_to_index = {}
<|end_body_0|>
<|body_start_1|>
flag = False
if val not in self.vals:
flag = True
self.vals.add(val)
if self.val_to_index.get(val, -1) == -1:
s... | RandomizedSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val: int) -> bool:
"""Inserts a value to the set. Returns true if the set did not already contain the specified element."""
<|body_1|>
def remove(se... | stack_v2_sparse_classes_36k_train_015866 | 1,663 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a value to the set. Returns true if the set did not already contain the specified element.",
"name": "insert",
"signature": "def insert(self, val: int) ... | 4 | stack_v2_sparse_classes_30k_train_013167 | Implement the Python class `RandomizedSet` described below.
Class description:
Implement the RandomizedSet class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val: int) -> bool: Inserts a value to the set. Returns true if the set did not already conta... | Implement the Python class `RandomizedSet` described below.
Class description:
Implement the RandomizedSet class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val: int) -> bool: Inserts a value to the set. Returns true if the set did not already conta... | e4ceb275a6c9a56999289751f13e74548d9cd185 | <|skeleton|>
class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val: int) -> bool:
"""Inserts a value to the set. Returns true if the set did not already contain the specified element."""
<|body_1|>
def remove(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
self.val_flag_list = []
self.vals = set([])
self.val_to_index = {}
def insert(self, val: int) -> bool:
"""Inserts a value to the set. Returns true if the set did not already contain the s... | the_stack_v2_python_sparse | 380. Insert Delete GetRandom O(1).py | mh-rahman/Programming-Practice | train | 3 | |
d7ce85a35f27a763e91a066428558318897667ba | [
"errors: List[Error] = []\nprices, stats, price_errors = self.safely_compute_equilibrium_prices(costs, iteration, prices)\nshares, share_errors = self.safely_compute_shares(prices)\nwith np.errstate(all='ignore'):\n delta = self.update_delta_with_variable('prices', prices)\n costs = self.update_costs_with_var... | <|body_start_0|>
errors: List[Error] = []
prices, stats, price_errors = self.safely_compute_equilibrium_prices(costs, iteration, prices)
shares, share_errors = self.safely_compute_shares(prices)
with np.errstate(all='ignore'):
delta = self.update_delta_with_variable('prices',... | A market in a simulation of synthetic BLP data. | SimulationMarket | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimulationMarket:
"""A market in a simulation of synthetic BLP data."""
def compute_endogenous(self, costs: Array, prices: Array, iteration: Iteration) -> Tuple[Array, Array, Array, Array, SolverStats, List[Error]]:
"""Compute endogenous prices and shares, along with the associated d... | stack_v2_sparse_classes_36k_train_015867 | 4,199 | permissive | [
{
"docstring": "Compute endogenous prices and shares, along with the associated delta and costs.",
"name": "compute_endogenous",
"signature": "def compute_endogenous(self, costs: Array, prices: Array, iteration: Iteration) -> Tuple[Array, Array, Array, Array, SolverStats, List[Error]]"
},
{
"doc... | 6 | stack_v2_sparse_classes_30k_train_010994 | Implement the Python class `SimulationMarket` described below.
Class description:
A market in a simulation of synthetic BLP data.
Method signatures and docstrings:
- def compute_endogenous(self, costs: Array, prices: Array, iteration: Iteration) -> Tuple[Array, Array, Array, Array, SolverStats, List[Error]]: Compute ... | Implement the Python class `SimulationMarket` described below.
Class description:
A market in a simulation of synthetic BLP data.
Method signatures and docstrings:
- def compute_endogenous(self, costs: Array, prices: Array, iteration: Iteration) -> Tuple[Array, Array, Array, Array, SolverStats, List[Error]]: Compute ... | 0eac4d652736553455731f80f1b0f7884d76578e | <|skeleton|>
class SimulationMarket:
"""A market in a simulation of synthetic BLP data."""
def compute_endogenous(self, costs: Array, prices: Array, iteration: Iteration) -> Tuple[Array, Array, Array, Array, SolverStats, List[Error]]:
"""Compute endogenous prices and shares, along with the associated d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimulationMarket:
"""A market in a simulation of synthetic BLP data."""
def compute_endogenous(self, costs: Array, prices: Array, iteration: Iteration) -> Tuple[Array, Array, Array, Array, SolverStats, List[Error]]:
"""Compute endogenous prices and shares, along with the associated delta and cost... | the_stack_v2_python_sparse | pyblp/markets/simulation_market.py | GloriaColmenares/pyblp | train | 1 |
aa01e46aa8c50f4c71d2bfe81d05c96d913ca420 | [
"if type(X_init) is not np.ndarray or len(X_init.shape) != 2:\n raise TypeError('X_init must be numpy.ndarray of shape (t, 1)')\nt, one = X_init.shape\nif one != 1:\n raise TypeError('X_init must be numpy.ndarray of shape (t, 1)')\nif type(Y_init) is not np.ndarray or len(Y_init.shape) != 2:\n raise TypeEr... | <|body_start_0|>
if type(X_init) is not np.ndarray or len(X_init.shape) != 2:
raise TypeError('X_init must be numpy.ndarray of shape (t, 1)')
t, one = X_init.shape
if one != 1:
raise TypeError('X_init must be numpy.ndarray of shape (t, 1)')
if type(Y_init) is not ... | Represents a noiseless 1D Gaussian process class constructor: def __init__(self, X_init, Y_init, l=1, sigma_f=1) public instance attributes: X [numpy.ndarray of shape (t, 1)]: representing the inputs sampled with the black-box function t: number of samples Y [numpy.ndarry of shape (t, 1)]: representing the outputs of t... | GaussianProcess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianProcess:
"""Represents a noiseless 1D Gaussian process class constructor: def __init__(self, X_init, Y_init, l=1, sigma_f=1) public instance attributes: X [numpy.ndarray of shape (t, 1)]: representing the inputs sampled with the black-box function t: number of samples Y [numpy.ndarry of s... | stack_v2_sparse_classes_36k_train_015868 | 3,918 | no_license | [
{
"docstring": "Class constructor parameters: X_init [numpy.ndarray of shape (t, 1)]: representing the inputs sampled with the black-box function t: number of samples Y_init [numpy.ndarry of shape (t, 1)]: representing outputs of the black-box function for each input l [int or float]: length parameter for the k... | 2 | null | Implement the Python class `GaussianProcess` described below.
Class description:
Represents a noiseless 1D Gaussian process class constructor: def __init__(self, X_init, Y_init, l=1, sigma_f=1) public instance attributes: X [numpy.ndarray of shape (t, 1)]: representing the inputs sampled with the black-box function t:... | Implement the Python class `GaussianProcess` described below.
Class description:
Represents a noiseless 1D Gaussian process class constructor: def __init__(self, X_init, Y_init, l=1, sigma_f=1) public instance attributes: X [numpy.ndarray of shape (t, 1)]: representing the inputs sampled with the black-box function t:... | 8834b201ca84937365e4dcc0fac978656cdf5293 | <|skeleton|>
class GaussianProcess:
"""Represents a noiseless 1D Gaussian process class constructor: def __init__(self, X_init, Y_init, l=1, sigma_f=1) public instance attributes: X [numpy.ndarray of shape (t, 1)]: representing the inputs sampled with the black-box function t: number of samples Y [numpy.ndarry of s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GaussianProcess:
"""Represents a noiseless 1D Gaussian process class constructor: def __init__(self, X_init, Y_init, l=1, sigma_f=1) public instance attributes: X [numpy.ndarray of shape (t, 1)]: representing the inputs sampled with the black-box function t: number of samples Y [numpy.ndarry of shape (t, 1)]:... | the_stack_v2_python_sparse | unsupervised_learning/0x03-hyperparameter_tuning/0-gp.py | ejonakodra/holbertonschool-machine_learning-1 | train | 0 |
f0dd6fbcfe8c622331394b38ec411949231692a9 | [
"super(SEBlock, self).__init__()\nself.pool2d_gap = AdaptiveAvgPool2D(1)\nself._num_channels = num_channels\nstdv = 1.0 / math.sqrt(num_channels * 1.0)\nmed_ch = num_channels // reduction_ratio\nself.squeeze = Linear(num_channels, med_ch, weight_attr=ParamAttr(learning_rate=lr_mult, initializer=Uniform(-stdv, stdv)... | <|body_start_0|>
super(SEBlock, self).__init__()
self.pool2d_gap = AdaptiveAvgPool2D(1)
self._num_channels = num_channels
stdv = 1.0 / math.sqrt(num_channels * 1.0)
med_ch = num_channels // reduction_ratio
self.squeeze = Linear(num_channels, med_ch, weight_attr=ParamAttr(... | SEBlock | SEBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SEBlock:
"""SEBlock"""
def __init__(self, num_channels, lr_mult, reduction_ratio=4, name=None):
"""init"""
<|body_0|>
def forward(self, inputs):
"""forward"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(SEBlock, self).__init__()
s... | stack_v2_sparse_classes_36k_train_015869 | 1,651 | no_license | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, num_channels, lr_mult, reduction_ratio=4, name=None)"
},
{
"docstring": "forward",
"name": "forward",
"signature": "def forward(self, inputs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018452 | Implement the Python class `SEBlock` described below.
Class description:
SEBlock
Method signatures and docstrings:
- def __init__(self, num_channels, lr_mult, reduction_ratio=4, name=None): init
- def forward(self, inputs): forward | Implement the Python class `SEBlock` described below.
Class description:
SEBlock
Method signatures and docstrings:
- def __init__(self, num_channels, lr_mult, reduction_ratio=4, name=None): init
- def forward(self, inputs): forward
<|skeleton|>
class SEBlock:
"""SEBlock"""
def __init__(self, num_channels, l... | bd3790ce72a2a26611b5eda3901651b5a809348f | <|skeleton|>
class SEBlock:
"""SEBlock"""
def __init__(self, num_channels, lr_mult, reduction_ratio=4, name=None):
"""init"""
<|body_0|>
def forward(self, inputs):
"""forward"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SEBlock:
"""SEBlock"""
def __init__(self, num_channels, lr_mult, reduction_ratio=4, name=None):
"""init"""
super(SEBlock, self).__init__()
self.pool2d_gap = AdaptiveAvgPool2D(1)
self._num_channels = num_channels
stdv = 1.0 / math.sqrt(num_channels * 1.0)
me... | the_stack_v2_python_sparse | framework/e2e/moduletrans/diy/layer/SEBlock.py | PaddlePaddle/PaddleTest | train | 42 |
c61014558391ed9157c77162161654adf2f48722 | [
"if not cls._app_client:\n app_client = AsyncOAuth2Client(client_id=Config.consumer_key, client_secret=Config.consumer_secret)\n await app_client.fetch_token(url=TOKEN_ENDPOINT, grant_type='client_credentials')\n cls._app_client = app_client\nreturn cls._app_client",
"if not cls._user_client:\n cls._u... | <|body_start_0|>
if not cls._app_client:
app_client = AsyncOAuth2Client(client_id=Config.consumer_key, client_secret=Config.consumer_secret)
await app_client.fetch_token(url=TOKEN_ENDPOINT, grant_type='client_credentials')
cls._app_client = app_client
return cls._app_... | AsyncAuthHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsyncAuthHandler:
async def app_client(cls) -> AsyncOAuth2Client:
"""Create App Client or return existing one. Returns: App Client"""
<|body_0|>
def user_client(cls) -> AsyncOAuth1Client:
"""Create User Client or return existing one. Returns: User Client"""
<... | stack_v2_sparse_classes_36k_train_015870 | 3,086 | permissive | [
{
"docstring": "Create App Client or return existing one. Returns: App Client",
"name": "app_client",
"signature": "async def app_client(cls) -> AsyncOAuth2Client"
},
{
"docstring": "Create User Client or return existing one. Returns: User Client",
"name": "user_client",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_train_019680 | Implement the Python class `AsyncAuthHandler` described below.
Class description:
Implement the AsyncAuthHandler class.
Method signatures and docstrings:
- async def app_client(cls) -> AsyncOAuth2Client: Create App Client or return existing one. Returns: App Client
- def user_client(cls) -> AsyncOAuth1Client: Create ... | Implement the Python class `AsyncAuthHandler` described below.
Class description:
Implement the AsyncAuthHandler class.
Method signatures and docstrings:
- async def app_client(cls) -> AsyncOAuth2Client: Create App Client or return existing one. Returns: App Client
- def user_client(cls) -> AsyncOAuth1Client: Create ... | 387006356e10c0e1c9dad363cd927a67e3c48cde | <|skeleton|>
class AsyncAuthHandler:
async def app_client(cls) -> AsyncOAuth2Client:
"""Create App Client or return existing one. Returns: App Client"""
<|body_0|>
def user_client(cls) -> AsyncOAuth1Client:
"""Create User Client or return existing one. Returns: User Client"""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AsyncAuthHandler:
async def app_client(cls) -> AsyncOAuth2Client:
"""Create App Client or return existing one. Returns: App Client"""
if not cls._app_client:
app_client = AsyncOAuth2Client(client_id=Config.consumer_key, client_secret=Config.consumer_secret)
await app_cl... | the_stack_v2_python_sparse | src/twicorder/aio_auth.py | thimic/twicorder-search | train | 2 | |
162c4232168b4be7528c00f5d1b569cfa6038746 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn CalendarPermission()",
"from .calendar_role_type import CalendarRoleType\nfrom .email_address import EmailAddress\nfrom .entity import Entity\nfrom .calendar_role_type import CalendarRoleType\nfrom .email_address import EmailAddress\nf... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return CalendarPermission()
<|end_body_0|>
<|body_start_1|>
from .calendar_role_type import CalendarRoleType
from .email_address import EmailAddress
from .entity import Entity
f... | CalendarPermission | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CalendarPermission:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CalendarPermission:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the obje... | stack_v2_sparse_classes_36k_train_015871 | 4,023 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: CalendarPermission",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_... | 3 | stack_v2_sparse_classes_30k_train_009195 | Implement the Python class `CalendarPermission` described below.
Class description:
Implement the CalendarPermission class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CalendarPermission: Creates a new instance of the appropriate class based on disc... | Implement the Python class `CalendarPermission` described below.
Class description:
Implement the CalendarPermission class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CalendarPermission: Creates a new instance of the appropriate class based on disc... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class CalendarPermission:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CalendarPermission:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the obje... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CalendarPermission:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CalendarPermission:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Ca... | the_stack_v2_python_sparse | msgraph/generated/models/calendar_permission.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
0c2bff81b45eb34d050d6e1730e7782741764eb0 | [
"num = int(n)\nL = len(n)\na = L // 2\npre = n[:a]\ncandidates = []\nif L % 2 == 0:\n num_pre = [str(max(int(pre) - i, 0)) for i in range(-1, 2)]\n str_pre = [i + i[::-1] for i in num_pre]\nelse:\n str_pre = [pre + str(max(int(n[a]) + i, 0)) + pre[::-1] for i in range(-1, 2)]\nprint(str_pre)\ncandidates.ex... | <|body_start_0|>
num = int(n)
L = len(n)
a = L // 2
pre = n[:a]
candidates = []
if L % 2 == 0:
num_pre = [str(max(int(pre) - i, 0)) for i in range(-1, 2)]
str_pre = [i + i[::-1] for i in num_pre]
else:
str_pre = [pre + str(max(i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nearestPalindromic(self, n):
""":type n: str :rtype: str 48MS"""
<|body_0|>
def nearestPalindromic_1(self, n):
""":type n: str :rtype: str 70MS"""
<|body_1|>
def nearestPalindromic_2(self, n):
""":type n: str :rtype: str 43MS"""
... | stack_v2_sparse_classes_36k_train_015872 | 3,273 | no_license | [
{
"docstring": ":type n: str :rtype: str 48MS",
"name": "nearestPalindromic",
"signature": "def nearestPalindromic(self, n)"
},
{
"docstring": ":type n: str :rtype: str 70MS",
"name": "nearestPalindromic_1",
"signature": "def nearestPalindromic_1(self, n)"
},
{
"docstring": ":typ... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nearestPalindromic(self, n): :type n: str :rtype: str 48MS
- def nearestPalindromic_1(self, n): :type n: str :rtype: str 70MS
- def nearestPalindromic_2(self, n): :type n: st... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nearestPalindromic(self, n): :type n: str :rtype: str 48MS
- def nearestPalindromic_1(self, n): :type n: str :rtype: str 70MS
- def nearestPalindromic_2(self, n): :type n: st... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def nearestPalindromic(self, n):
""":type n: str :rtype: str 48MS"""
<|body_0|>
def nearestPalindromic_1(self, n):
""":type n: str :rtype: str 70MS"""
<|body_1|>
def nearestPalindromic_2(self, n):
""":type n: str :rtype: str 43MS"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def nearestPalindromic(self, n):
""":type n: str :rtype: str 48MS"""
num = int(n)
L = len(n)
a = L // 2
pre = n[:a]
candidates = []
if L % 2 == 0:
num_pre = [str(max(int(pre) - i, 0)) for i in range(-1, 2)]
str_pre = [i ... | the_stack_v2_python_sparse | FindTheClosestPalindrome_HARD_564.py | 953250587/leetcode-python | train | 2 | |
b9bdc70fbeab580890253b409090e8b6f9575735 | [
"super(FPN, self).__init__()\nself.inner_blocks = []\nself.layer_blocks = []\nfor idx, in_channels in enumerate(in_channels_list, 1):\n inner_block = 'fpn_inner{}'.format(idx)\n layer_block = 'fpn_layer{}'.format(idx)\n if in_channels == 0:\n continue\n inner_block_module = conv_block(in_channels... | <|body_start_0|>
super(FPN, self).__init__()
self.inner_blocks = []
self.layer_blocks = []
for idx, in_channels in enumerate(in_channels_list, 1):
inner_block = 'fpn_inner{}'.format(idx)
layer_block = 'fpn_layer{}'.format(idx)
if in_channels == 0:
... | Module that adds FPN on top of a list of feature maps. The feature maps are currently supposed to be in increasing depth order, and must be consecutive | FPN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FPN:
"""Module that adds FPN on top of a list of feature maps. The feature maps are currently supposed to be in increasing depth order, and must be consecutive"""
def __init__(self, in_channels_list, out_channels, conv_block, top_blocks=None):
"""Arguments: in_channels_list (list[int... | stack_v2_sparse_classes_36k_train_015873 | 7,261 | permissive | [
{
"docstring": "Arguments: in_channels_list (list[int]): number of channels for each feature map that will be fed out_channels (int): number of channels of the FPN representation top_blocks (nn.Module or None): if provided, an extra operation will be performed on the output of the last (smallest resolution) FPN... | 2 | null | Implement the Python class `FPN` described below.
Class description:
Module that adds FPN on top of a list of feature maps. The feature maps are currently supposed to be in increasing depth order, and must be consecutive
Method signatures and docstrings:
- def __init__(self, in_channels_list, out_channels, conv_block... | Implement the Python class `FPN` described below.
Class description:
Module that adds FPN on top of a list of feature maps. The feature maps are currently supposed to be in increasing depth order, and must be consecutive
Method signatures and docstrings:
- def __init__(self, in_channels_list, out_channels, conv_block... | ed03f0b11c16062e7faacb547f6eb9f83ce5f15e | <|skeleton|>
class FPN:
"""Module that adds FPN on top of a list of feature maps. The feature maps are currently supposed to be in increasing depth order, and must be consecutive"""
def __init__(self, in_channels_list, out_channels, conv_block, top_blocks=None):
"""Arguments: in_channels_list (list[int... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FPN:
"""Module that adds FPN on top of a list of feature maps. The feature maps are currently supposed to be in increasing depth order, and must be consecutive"""
def __init__(self, in_channels_list, out_channels, conv_block, top_blocks=None):
"""Arguments: in_channels_list (list[int]): number of... | the_stack_v2_python_sparse | tllib/vision/models/object_detection/backbone/vgg.py | thuml/Transfer-Learning-Library | train | 2,786 |
09df73bb58594e6327779dccb78b9da47fa903e9 | [
"super(SP_TransformerNetwork, self).__init__()\nself.power_list = self.cal_K(default_type)\nself.sigmoid = nn.Sigmoid()\nself.bn = nn.InstanceNorm2d(nc)",
"from math import log\nx = []\nif k != 0:\n for i in range(1, k + 1):\n lower = round(log(1 - 0.5 / (k + 1) * i) / log(0.5 / (k + 1) * i), 2)\n ... | <|body_start_0|>
super(SP_TransformerNetwork, self).__init__()
self.power_list = self.cal_K(default_type)
self.sigmoid = nn.Sigmoid()
self.bn = nn.InstanceNorm2d(nc)
<|end_body_0|>
<|body_start_1|>
from math import log
x = []
if k != 0:
for i in range... | Sturture-Preserving Transformation (SPT) as Equa. (2) in Ref. [1] Ref: [1] SPIN: Structure-Preserving Inner Offset Network for Scene Text Recognition. AAAI-2021. | SP_TransformerNetwork | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SP_TransformerNetwork:
"""Sturture-Preserving Transformation (SPT) as Equa. (2) in Ref. [1] Ref: [1] SPIN: Structure-Preserving Inner Offset Network for Scene Text Recognition. AAAI-2021."""
def __init__(self, nc=1, default_type=5):
"""Based on SPIN Args: nc (int): number of input ch... | stack_v2_sparse_classes_36k_train_015874 | 14,444 | permissive | [
{
"docstring": "Based on SPIN Args: nc (int): number of input channels (usually in 1 or 3) default_type (int): the complexity of transformation intensities (by default set to 6 as the paper)",
"name": "__init__",
"signature": "def __init__(self, nc=1, default_type=5)"
},
{
"docstring": "Args: k ... | 3 | null | Implement the Python class `SP_TransformerNetwork` described below.
Class description:
Sturture-Preserving Transformation (SPT) as Equa. (2) in Ref. [1] Ref: [1] SPIN: Structure-Preserving Inner Offset Network for Scene Text Recognition. AAAI-2021.
Method signatures and docstrings:
- def __init__(self, nc=1, default_... | Implement the Python class `SP_TransformerNetwork` described below.
Class description:
Sturture-Preserving Transformation (SPT) as Equa. (2) in Ref. [1] Ref: [1] SPIN: Structure-Preserving Inner Offset Network for Scene Text Recognition. AAAI-2021.
Method signatures and docstrings:
- def __init__(self, nc=1, default_... | fb47a96d1a38f5ce634c6f12d710ed5300cc89fc | <|skeleton|>
class SP_TransformerNetwork:
"""Sturture-Preserving Transformation (SPT) as Equa. (2) in Ref. [1] Ref: [1] SPIN: Structure-Preserving Inner Offset Network for Scene Text Recognition. AAAI-2021."""
def __init__(self, nc=1, default_type=5):
"""Based on SPIN Args: nc (int): number of input ch... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SP_TransformerNetwork:
"""Sturture-Preserving Transformation (SPT) as Equa. (2) in Ref. [1] Ref: [1] SPIN: Structure-Preserving Inner Offset Network for Scene Text Recognition. AAAI-2021."""
def __init__(self, nc=1, default_type=5):
"""Based on SPIN Args: nc (int): number of input channels (usual... | the_stack_v2_python_sparse | davarocr/davarocr/davar_rcg/models/transformations/spin_transformation.py | OCRWorld/DAVAR-Lab-OCR | train | 0 |
46fcb5c5156b2433593989fc33937da25f1da1a3 | [
"self.task_name = task_name\nself.task_params = task_params\nself.world_params = world_params\nself.initial_full_state = initial_full_state\nself.robot_actions = []\nself.observations = []\nself.rewards = []\nself.infos = []\nself.dones = []\nself.timestamps = []",
"self.robot_actions.append(robot_action)\nself.o... | <|body_start_0|>
self.task_name = task_name
self.task_params = task_params
self.world_params = world_params
self.initial_full_state = initial_full_state
self.robot_actions = []
self.observations = []
self.rewards = []
self.infos = []
self.dones = [... | Episode | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Episode:
def __init__(self, task_name, initial_full_state, task_params=None, world_params=None):
"""The structure in which the data from each episode will be logged. :param task_name: :param initial_full_state: :param task_params: :param world_params:"""
<|body_0|>
def appen... | stack_v2_sparse_classes_36k_train_015875 | 1,242 | permissive | [
{
"docstring": "The structure in which the data from each episode will be logged. :param task_name: :param initial_full_state: :param task_params: :param world_params:",
"name": "__init__",
"signature": "def __init__(self, task_name, initial_full_state, task_params=None, world_params=None)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_008129 | Implement the Python class `Episode` described below.
Class description:
Implement the Episode class.
Method signatures and docstrings:
- def __init__(self, task_name, initial_full_state, task_params=None, world_params=None): The structure in which the data from each episode will be logged. :param task_name: :param i... | Implement the Python class `Episode` described below.
Class description:
Implement the Episode class.
Method signatures and docstrings:
- def __init__(self, task_name, initial_full_state, task_params=None, world_params=None): The structure in which the data from each episode will be logged. :param task_name: :param i... | 4c0ac37e559daa0dd89668e5bff5eec82a4158c5 | <|skeleton|>
class Episode:
def __init__(self, task_name, initial_full_state, task_params=None, world_params=None):
"""The structure in which the data from each episode will be logged. :param task_name: :param initial_full_state: :param task_params: :param world_params:"""
<|body_0|>
def appen... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Episode:
def __init__(self, task_name, initial_full_state, task_params=None, world_params=None):
"""The structure in which the data from each episode will be logged. :param task_name: :param initial_full_state: :param task_params: :param world_params:"""
self.task_name = task_name
self... | the_stack_v2_python_sparse | Trifinger/causal_world/loggers/episode.py | emigmo/BenTDM | train | 0 | |
58a63bf8cf3844d7d5a6fae45be4fc5e0a2ce0ce | [
"super(RevokeResponsePayload, self).__init__()\nif unique_identifier is None:\n self.unique_identifier = attributes.UniqueIdentifier()\nelse:\n self.unique_identifier = unique_identifier\nself.validate()",
"super(RevokeResponsePayload, self).read(istream, kmip_version=kmip_version)\ntstream = BytearrayStrea... | <|body_start_0|>
super(RevokeResponsePayload, self).__init__()
if unique_identifier is None:
self.unique_identifier = attributes.UniqueIdentifier()
else:
self.unique_identifier = unique_identifier
self.validate()
<|end_body_0|>
<|body_start_1|>
super(Revo... | A response payload for the Revoke operation. The payload contains the server response to the initial Revoke request. See Section 4.20 of the KMIP 1.1 specification for more information. Attributes: unique_identifier: The UUID of a managed cryptographic object. | RevokeResponsePayload | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RevokeResponsePayload:
"""A response payload for the Revoke operation. The payload contains the server response to the initial Revoke request. See Section 4.20 of the KMIP 1.1 specification for more information. Attributes: unique_identifier: The UUID of a managed cryptographic object."""
de... | stack_v2_sparse_classes_36k_train_015876 | 8,772 | permissive | [
{
"docstring": "Construct a RevokeResponsePayload object. Args: unique_identifier (UniqueIdentifier): The UUID of a managed cryptographic object.",
"name": "__init__",
"signature": "def __init__(self, unique_identifier=None)"
},
{
"docstring": "Read the data encoding the RevokeResponsePayload ob... | 4 | null | Implement the Python class `RevokeResponsePayload` described below.
Class description:
A response payload for the Revoke operation. The payload contains the server response to the initial Revoke request. See Section 4.20 of the KMIP 1.1 specification for more information. Attributes: unique_identifier: The UUID of a m... | Implement the Python class `RevokeResponsePayload` described below.
Class description:
A response payload for the Revoke operation. The payload contains the server response to the initial Revoke request. See Section 4.20 of the KMIP 1.1 specification for more information. Attributes: unique_identifier: The UUID of a m... | f0a44b26ce902d8b9c330634d5b3603959edf1d4 | <|skeleton|>
class RevokeResponsePayload:
"""A response payload for the Revoke operation. The payload contains the server response to the initial Revoke request. See Section 4.20 of the KMIP 1.1 specification for more information. Attributes: unique_identifier: The UUID of a managed cryptographic object."""
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RevokeResponsePayload:
"""A response payload for the Revoke operation. The payload contains the server response to the initial Revoke request. See Section 4.20 of the KMIP 1.1 specification for more information. Attributes: unique_identifier: The UUID of a managed cryptographic object."""
def __init__(se... | the_stack_v2_python_sparse | kmip/core/messages/payloads/revoke.py | OpenKMIP/PyKMIP | train | 232 |
5b36ae39744da25c08d4088f62e6e77451230c28 | [
"self.key = key\nself.name = name\nself.group_by = group_by\nself.new_group_by = new_group_by\nself.scalar_func = func\nsuper(ScalarAggregator, self).__init__(group_by, self.scalar_wrapper_)",
"group = pdf.reset_index().groupby(by=self.new_group_by, group_keys=False)\n\ndef func(pdf):\n agg = self.scalar_func(... | <|body_start_0|>
self.key = key
self.name = name
self.group_by = group_by
self.new_group_by = new_group_by
self.scalar_func = func
super(ScalarAggregator, self).__init__(group_by, self.scalar_wrapper_)
<|end_body_0|>
<|body_start_1|>
group = pdf.reset_index().gro... | This class defines a simple aggregator that groups metrics and applies an aggregating function. Grouping is determined by the set difference between an original `group_by` term and a subset `new_group_py` term. | ScalarAggregator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScalarAggregator:
"""This class defines a simple aggregator that groups metrics and applies an aggregating function. Grouping is determined by the set difference between an original `group_by` term and a subset `new_group_py` term."""
def __init__(self, key, group_by, new_group_by, func, nam... | stack_v2_sparse_classes_36k_train_015877 | 8,406 | permissive | [
{
"docstring": ":param key: metric heading name with values to aggregate :param group_by: level at which original metric was computed, e.g. ('subject_id', 'label') :param new_group_by: level at which metric after aggregation is computed, e.g. ('label') :param func: function (iterable=>scalar) to aggregate the c... | 2 | stack_v2_sparse_classes_30k_train_009767 | Implement the Python class `ScalarAggregator` described below.
Class description:
This class defines a simple aggregator that groups metrics and applies an aggregating function. Grouping is determined by the set difference between an original `group_by` term and a subset `new_group_py` term.
Method signatures and doc... | Implement the Python class `ScalarAggregator` described below.
Class description:
This class defines a simple aggregator that groups metrics and applies an aggregating function. Grouping is determined by the set difference between an original `group_by` term and a subset `new_group_py` term.
Method signatures and doc... | 84dd0f85c9a1ab8a72f4c55fcf073379acf5ae1b | <|skeleton|>
class ScalarAggregator:
"""This class defines a simple aggregator that groups metrics and applies an aggregating function. Grouping is determined by the set difference between an original `group_by` term and a subset `new_group_py` term."""
def __init__(self, key, group_by, new_group_by, func, nam... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScalarAggregator:
"""This class defines a simple aggregator that groups metrics and applies an aggregating function. Grouping is determined by the set difference between an original `group_by` term and a subset `new_group_py` term."""
def __init__(self, key, group_by, new_group_by, func, name):
"... | the_stack_v2_python_sparse | niftynet/evaluation/base_evaluator.py | 12SigmaTechnologies/NiftyNet-1 | train | 2 |
69ef8b95244ba262646f9a23e85ee544d12ee7ab | [
"grammar = nltk.data.load('./TestFiles/pcfg.pcfg')\nwith open('./TestFiles/sentences', 'r') as sentences:\n test_sentences = sentences.readlines()\nwith open('./TestFiles/trees', 'r') as trees:\n expected_trees = trees.readlines()\nparser = PCKY(grammar)\nfor sentence, expected in zip(test_sentences, expected... | <|body_start_0|>
grammar = nltk.data.load('./TestFiles/pcfg.pcfg')
with open('./TestFiles/sentences', 'r') as sentences:
test_sentences = sentences.readlines()
with open('./TestFiles/trees', 'r') as trees:
expected_trees = trees.readlines()
parser = PCKY(grammar)
... | This class contains tests for the PCKY class | TestPCKY | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPCKY:
"""This class contains tests for the PCKY class"""
def test_parse(self):
"""Test grammar parse example :return: void"""
<|body_0|>
def test_unk(self):
"""Test unknown words :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
gramm... | stack_v2_sparse_classes_36k_train_015878 | 5,674 | no_license | [
{
"docstring": "Test grammar parse example :return: void",
"name": "test_parse",
"signature": "def test_parse(self)"
},
{
"docstring": "Test unknown words :return:",
"name": "test_unk",
"signature": "def test_unk(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007036 | Implement the Python class `TestPCKY` described below.
Class description:
This class contains tests for the PCKY class
Method signatures and docstrings:
- def test_parse(self): Test grammar parse example :return: void
- def test_unk(self): Test unknown words :return: | Implement the Python class `TestPCKY` described below.
Class description:
This class contains tests for the PCKY class
Method signatures and docstrings:
- def test_parse(self): Test grammar parse example :return: void
- def test_unk(self): Test unknown words :return:
<|skeleton|>
class TestPCKY:
"""This class co... | 7af7b357347ed526de7a3d6f16652843d214dcbf | <|skeleton|>
class TestPCKY:
"""This class contains tests for the PCKY class"""
def test_parse(self):
"""Test grammar parse example :return: void"""
<|body_0|>
def test_unk(self):
"""Test unknown words :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestPCKY:
"""This class contains tests for the PCKY class"""
def test_parse(self):
"""Test grammar parse example :return: void"""
grammar = nltk.data.load('./TestFiles/pcfg.pcfg')
with open('./TestFiles/sentences', 'r') as sentences:
test_sentences = sentences.readline... | the_stack_v2_python_sparse | Parser/pcky.py | zoew2/Projects | train | 0 |
898844c574a735ddd0b2c73f92daf849c700c4e1 | [
"adm = ApplikationsAdministration()\nliste = adm.get_einkaufsliste_by_id(id)\nadm.delete_einkaufsliste(liste)\nreturn ''",
"adm = ApplikationsAdministration()\na = Einkaufsliste.from_dict(api.payload)\nif a is not None:\n a.set_id(id)\n adm.update_einkaufsliste(a)\n return ('', 200)\nelse:\n return ('... | <|body_start_0|>
adm = ApplikationsAdministration()
liste = adm.get_einkaufsliste_by_id(id)
adm.delete_einkaufsliste(liste)
return ''
<|end_body_0|>
<|body_start_1|>
adm = ApplikationsAdministration()
a = Einkaufsliste.from_dict(api.payload)
if a is not None:
... | EinkaufslisteOperations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EinkaufslisteOperations:
def delete(self, id):
"""Löschen einer Einkaufsliste anhand einer id"""
<|body_0|>
def put(self, id):
"""Update einer durch id bestimmten Einkaufsliste"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
adm = ApplikationsAdmini... | stack_v2_sparse_classes_36k_train_015879 | 23,456 | no_license | [
{
"docstring": "Löschen einer Einkaufsliste anhand einer id",
"name": "delete",
"signature": "def delete(self, id)"
},
{
"docstring": "Update einer durch id bestimmten Einkaufsliste",
"name": "put",
"signature": "def put(self, id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011524 | Implement the Python class `EinkaufslisteOperations` described below.
Class description:
Implement the EinkaufslisteOperations class.
Method signatures and docstrings:
- def delete(self, id): Löschen einer Einkaufsliste anhand einer id
- def put(self, id): Update einer durch id bestimmten Einkaufsliste | Implement the Python class `EinkaufslisteOperations` described below.
Class description:
Implement the EinkaufslisteOperations class.
Method signatures and docstrings:
- def delete(self, id): Löschen einer Einkaufsliste anhand einer id
- def put(self, id): Update einer durch id bestimmten Einkaufsliste
<|skeleton|>
... | d4a2b196f21a5379188cb78b31c59d69f739964f | <|skeleton|>
class EinkaufslisteOperations:
def delete(self, id):
"""Löschen einer Einkaufsliste anhand einer id"""
<|body_0|>
def put(self, id):
"""Update einer durch id bestimmten Einkaufsliste"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EinkaufslisteOperations:
def delete(self, id):
"""Löschen einer Einkaufsliste anhand einer id"""
adm = ApplikationsAdministration()
liste = adm.get_einkaufsliste_by_id(id)
adm.delete_einkaufsliste(liste)
return ''
def put(self, id):
"""Update einer durch id... | the_stack_v2_python_sparse | src/main.py | SvenjaHolzinger/SoftwarePraktikum | train | 0 | |
74c013c5205023b31a48b054f1b0d477bb7ce4ee | [
"if os.path.isfile(bam) is False:\n raise Exception(f'{bam} file does not exist')\nself.bam = bam\nself.reference = reference",
"arguments_mpileup = [BCFTools.arg('-f', self.reference), BCFTools.arg('--threads', threads)]\nfor a in annots:\n arguments_mpileup.append(BCFTools.arg('-a', a))\nallowed_keys = ['... | <|body_start_0|>
if os.path.isfile(bam) is False:
raise Exception(f'{bam} file does not exist')
self.bam = bam
self.reference = reference
<|end_body_0|>
<|body_start_1|>
arguments_mpileup = [BCFTools.arg('-f', self.reference), BCFTools.arg('--threads', threads)]
for ... | Class to run the BCFTools variant caller Class variables --------------- bcftools_folder : str, Optional Path to folder containing the bcftools binary arg : namedtuple Containing a particular argument and its value | BCFTools | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BCFTools:
"""Class to run the BCFTools variant caller Class variables --------------- bcftools_folder : str, Optional Path to folder containing the bcftools binary arg : namedtuple Containing a particular argument and its value"""
def __init__(self, bam: str, reference: str) -> None:
... | stack_v2_sparse_classes_36k_train_015880 | 4,018 | permissive | [
{
"docstring": "Constructor Parameters ---------- bam : Path to BAM file used for the variant calling process. reference : Path to fasta file containing the reference.",
"name": "__init__",
"signature": "def __init__(self, bam: str, reference: str) -> None"
},
{
"docstring": "Run BCFTools mpileu... | 2 | null | Implement the Python class `BCFTools` described below.
Class description:
Class to run the BCFTools variant caller Class variables --------------- bcftools_folder : str, Optional Path to folder containing the bcftools binary arg : namedtuple Containing a particular argument and its value
Method signatures and docstri... | Implement the Python class `BCFTools` described below.
Class description:
Class to run the BCFTools variant caller Class variables --------------- bcftools_folder : str, Optional Path to folder containing the bcftools binary arg : namedtuple Containing a particular argument and its value
Method signatures and docstri... | ffea4885227c2299f886a4f41e70b6e1f6bb43da | <|skeleton|>
class BCFTools:
"""Class to run the BCFTools variant caller Class variables --------------- bcftools_folder : str, Optional Path to folder containing the bcftools binary arg : namedtuple Containing a particular argument and its value"""
def __init__(self, bam: str, reference: str) -> None:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BCFTools:
"""Class to run the BCFTools variant caller Class variables --------------- bcftools_folder : str, Optional Path to folder containing the bcftools binary arg : namedtuple Containing a particular argument and its value"""
def __init__(self, bam: str, reference: str) -> None:
"""Construct... | the_stack_v2_python_sparse | VariantCalling/BCFTools.py | igsr/igsr_analysis | train | 3 |
4580f0fb2f0ec0ff12a25c6ff6f71fd953f3c635 | [
"self.nav_to_games_list()\ngames_list = self.browser.find_element_by_id('id_game_list')\ngames = games_list.find_elements_by_tag_name('li')\nself.assertEqual(len(games), 0)\nself.browser.find_element_by_id('id_new_game').click()\nnew_game_name = 'My New Game'\nself.browser.find_element_by_id('id_name').send_keys(ne... | <|body_start_0|>
self.nav_to_games_list()
games_list = self.browser.find_element_by_id('id_game_list')
games = games_list.find_elements_by_tag_name('li')
self.assertEqual(len(games), 0)
self.browser.find_element_by_id('id_new_game').click()
new_game_name = 'My New Game'
... | MakeGameTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MakeGameTest:
def test_make_new_game_via_form(self):
"""Simulate a user making a new game"""
<|body_0|>
def test_make_game_with_multiple_chains(self):
"""Make a game with multiple chains"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.nav_to_ga... | stack_v2_sparse_classes_36k_train_015881 | 3,302 | no_license | [
{
"docstring": "Simulate a user making a new game",
"name": "test_make_new_game_via_form",
"signature": "def test_make_new_game_via_form(self)"
},
{
"docstring": "Make a game with multiple chains",
"name": "test_make_game_with_multiple_chains",
"signature": "def test_make_game_with_multi... | 2 | stack_v2_sparse_classes_30k_train_007320 | Implement the Python class `MakeGameTest` described below.
Class description:
Implement the MakeGameTest class.
Method signatures and docstrings:
- def test_make_new_game_via_form(self): Simulate a user making a new game
- def test_make_game_with_multiple_chains(self): Make a game with multiple chains | Implement the Python class `MakeGameTest` described below.
Class description:
Implement the MakeGameTest class.
Method signatures and docstrings:
- def test_make_new_game_via_form(self): Simulate a user making a new game
- def test_make_game_with_multiple_chains(self): Make a game with multiple chains
<|skeleton|>
c... | 0421070eb678eca83fa19d894292303b9a59f9d3 | <|skeleton|>
class MakeGameTest:
def test_make_new_game_via_form(self):
"""Simulate a user making a new game"""
<|body_0|>
def test_make_game_with_multiple_chains(self):
"""Make a game with multiple chains"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MakeGameTest:
def test_make_new_game_via_form(self):
"""Simulate a user making a new game"""
self.nav_to_games_list()
games_list = self.browser.find_element_by_id('id_game_list')
games = games_list.find_elements_by_tag_name('li')
self.assertEqual(len(games), 0)
... | the_stack_v2_python_sparse | ftests/test_make_game.py | Ingwar/telephone | train | 0 | |
03a40297cfe74c33202596e29ef92b3a24eea31b | [
"if s in wordDict:\n return True\nfor k in wordDict:\n if len(k) <= len(s) and k == s[:len(k)]:\n if self.wordBreak(s[len(k):], wordDict):\n return True\n else:\n continue\nreturn False",
"dp = [False for i in range(len(s) + 1)]\ndp[0] = True\nfor i in range(len(dp)):\n ... | <|body_start_0|>
if s in wordDict:
return True
for k in wordDict:
if len(k) <= len(s) and k == s[:len(k)]:
if self.wordBreak(s[len(k):], wordDict):
return True
else:
continue
return False
<|end_body_0... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_0|>
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_015882 | 1,095 | no_license | [
{
"docstring": ":type s: str :type wordDict: List[str] :rtype: bool",
"name": "wordBreak",
"signature": "def wordBreak(self, s, wordDict)"
},
{
"docstring": ":type s: str :type wordDict: List[str] :rtype: bool",
"name": "wordBreak",
"signature": "def wordBreak(self, s, wordDict)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005821 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool
<|s... | 908b88d6318c2dae51137552c2958ba9429f00d1 | <|skeleton|>
class Solution:
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_0|>
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
if s in wordDict:
return True
for k in wordDict:
if len(k) <= len(s) and k == s[:len(k)]:
if self.wordBreak(s[len(k):], wordDict):
... | the_stack_v2_python_sparse | 139 Word Break.py | uncleyao/Leetcode | train | 2 | |
9be32d014cbbaa6e65c658bd834a61a64eb9da43 | [
"client = action.client\nexec_results = []\nfor run_cmd in run_cmds:\n cmd = run_cmd.cmd\n cmd_user = run_cmd.user\n log.debug('Creating exec command in container %s with user %s: %s.', c_name, cmd_user, cmd)\n ec_kwargs = self.get_exec_create_kwargs(action, c_name, cmd, cmd_user)\n create_result = c... | <|body_start_0|>
client = action.client
exec_results = []
for run_cmd in run_cmds:
cmd = run_cmd.cmd
cmd_user = run_cmd.user
log.debug('Creating exec command in container %s with user %s: %s.', c_name, cmd_user, cmd)
ec_kwargs = self.get_exec_creat... | Utility mixin for executing configured commands inside containers. | ExecMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExecMixin:
"""Utility mixin for executing configured commands inside containers."""
def exec_commands(self, action, c_name, run_cmds, **kwargs):
"""Runs a single command inside a container. :param action: Action configuration. :type action: dockermap.map.runner.ActionConfig :param c_... | stack_v2_sparse_classes_36k_train_015883 | 2,879 | permissive | [
{
"docstring": "Runs a single command inside a container. :param action: Action configuration. :type action: dockermap.map.runner.ActionConfig :param c_name: Container name. :type c_name: unicode | str :param run_cmds: Commands to run. :type run_cmds: list[dockermap.map.input.ExecCommand] :return: List of exec ... | 2 | stack_v2_sparse_classes_30k_train_011081 | Implement the Python class `ExecMixin` described below.
Class description:
Utility mixin for executing configured commands inside containers.
Method signatures and docstrings:
- def exec_commands(self, action, c_name, run_cmds, **kwargs): Runs a single command inside a container. :param action: Action configuration. ... | Implement the Python class `ExecMixin` described below.
Class description:
Utility mixin for executing configured commands inside containers.
Method signatures and docstrings:
- def exec_commands(self, action, c_name, run_cmds, **kwargs): Runs a single command inside a container. :param action: Action configuration. ... | 54e325595fc0b6b9d154dacc790a222f957895da | <|skeleton|>
class ExecMixin:
"""Utility mixin for executing configured commands inside containers."""
def exec_commands(self, action, c_name, run_cmds, **kwargs):
"""Runs a single command inside a container. :param action: Action configuration. :type action: dockermap.map.runner.ActionConfig :param c_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExecMixin:
"""Utility mixin for executing configured commands inside containers."""
def exec_commands(self, action, c_name, run_cmds, **kwargs):
"""Runs a single command inside a container. :param action: Action configuration. :type action: dockermap.map.runner.ActionConfig :param c_name: Contain... | the_stack_v2_python_sparse | dockermap/map/runner/cmd.py | merll/docker-map | train | 85 |
0a8896c8bfe65d3de7b64299cbe0cb071bd40dbf | [
"check_is_fitted(self)\nX = check_array(X, accept_sparse='csr')\nn_features = self.coef_.shape[1]\nif X.shape[1] != n_features:\n raise ValueError('X has %d features per sample; expecting %d' % (X.shape[1], n_features))\nscores = mt.dot(X, self.coef_.T) + self.intercept_\nreturn scores",
"scores = self.decisio... | <|body_start_0|>
check_is_fitted(self)
X = check_array(X, accept_sparse='csr')
n_features = self.coef_.shape[1]
if X.shape[1] != n_features:
raise ValueError('X has %d features per sample; expecting %d' % (X.shape[1], n_features))
scores = mt.dot(X, self.coef_.T) + se... | Mixin for linear classifiers. Handles prediction for sparse and dense X. | LinearClassifierMixin | [
"BSD-3-Clause",
"MIT",
"ISC",
"Apache-2.0",
"CC0-1.0",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearClassifierMixin:
"""Mixin for linear classifiers. Handles prediction for sparse and dense X."""
def decision_function(self, X):
"""Predict confidence scores for samples. The confidence score for a sample is proportional to the signed distance of that sample to the hyperplane. P... | stack_v2_sparse_classes_36k_train_015884 | 12,383 | permissive | [
{
"docstring": "Predict confidence scores for samples. The confidence score for a sample is proportional to the signed distance of that sample to the hyperplane. Parameters ---------- X : array-like or sparse matrix, shape (n_samples, n_features) Samples. Returns ------- array, shape=(n_samples,) if n_classes =... | 2 | null | Implement the Python class `LinearClassifierMixin` described below.
Class description:
Mixin for linear classifiers. Handles prediction for sparse and dense X.
Method signatures and docstrings:
- def decision_function(self, X): Predict confidence scores for samples. The confidence score for a sample is proportional t... | Implement the Python class `LinearClassifierMixin` described below.
Class description:
Mixin for linear classifiers. Handles prediction for sparse and dense X.
Method signatures and docstrings:
- def decision_function(self, X): Predict confidence scores for samples. The confidence score for a sample is proportional t... | c36c53fa22e10ef9477d9c454401a2f281375f31 | <|skeleton|>
class LinearClassifierMixin:
"""Mixin for linear classifiers. Handles prediction for sparse and dense X."""
def decision_function(self, X):
"""Predict confidence scores for samples. The confidence score for a sample is proportional to the signed distance of that sample to the hyperplane. P... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinearClassifierMixin:
"""Mixin for linear classifiers. Handles prediction for sparse and dense X."""
def decision_function(self, X):
"""Predict confidence scores for samples. The confidence score for a sample is proportional to the signed distance of that sample to the hyperplane. Parameters ---... | the_stack_v2_python_sparse | mars/learn/linear_model/_base.py | mars-project/mars | train | 2,704 |
4246e668024b5aecace9d466dd24608c1b85bfae | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | LearningCenterServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LearningCenterServicer:
"""Missing associated documentation comment in .proto file."""
def Touch(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def StartTrain(self, request, context):
"""Missing associated docum... | stack_v2_sparse_classes_36k_train_015885 | 8,367 | no_license | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "Touch",
"signature": "def Touch(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "StartTrain",
"signature": "def StartTrain(self, request, con... | 5 | stack_v2_sparse_classes_30k_train_014080 | Implement the Python class `LearningCenterServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Touch(self, request, context): Missing associated documentation comment in .proto file.
- def StartTrain(self, request, context): Mis... | Implement the Python class `LearningCenterServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Touch(self, request, context): Missing associated documentation comment in .proto file.
- def StartTrain(self, request, context): Mis... | 7240629209b4641180e4e4a8291ece25431d83a2 | <|skeleton|>
class LearningCenterServicer:
"""Missing associated documentation comment in .proto file."""
def Touch(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def StartTrain(self, request, context):
"""Missing associated docum... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LearningCenterServicer:
"""Missing associated documentation comment in .proto file."""
def Touch(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
... | the_stack_v2_python_sparse | grpcservice/pb/learn_pb2_grpc.py | snowwayne1231/ai-chatfilter-service | train | 0 |
f58b0384f0b5e42c775e9a5d2c9dd6540939096b | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn EducationStudent()",
"from .education_gender import EducationGender\nfrom .education_gender import EducationGender\nfields: Dict[str, Callable[[Any], None]] = {'birthDate': lambda n: setattr(self, 'birth_date', n.get_date_value()), 'ex... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return EducationStudent()
<|end_body_0|>
<|body_start_1|>
from .education_gender import EducationGender
from .education_gender import EducationGender
fields: Dict[str, Callable[[Any], N... | EducationStudent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EducationStudent:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationStudent:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object R... | stack_v2_sparse_classes_36k_train_015886 | 3,847 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: EducationStudent",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_va... | 3 | stack_v2_sparse_classes_30k_train_008711 | Implement the Python class `EducationStudent` described below.
Class description:
Implement the EducationStudent class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationStudent: Creates a new instance of the appropriate class based on discrimina... | Implement the Python class `EducationStudent` described below.
Class description:
Implement the EducationStudent class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationStudent: Creates a new instance of the appropriate class based on discrimina... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class EducationStudent:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationStudent:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object R... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EducationStudent:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationStudent:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Educat... | the_stack_v2_python_sparse | msgraph/generated/models/education_student.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
ef0196abca4c3c189e5c68cc40429aead3b9feab | [
"self.fw_rules_map = fw_rules_map\nself.cluster_info = cluster_info\nself.output_config = output_config\nself.results_map = results_map",
"query_name = self.output_config.queryName\nif self.output_config.configName:\n query_name += ', config: ' + self.output_config.configName\noutput_format = self.output_confi... | <|body_start_0|>
self.fw_rules_map = fw_rules_map
self.cluster_info = cluster_info
self.output_config = output_config
self.results_map = results_map
<|end_body_0|>
<|body_start_1|>
query_name = self.output_config.queryName
if self.output_config.configName:
qu... | This is a class for minimizing and handling fw-rules globally for all connection sets | MinimizeFWRules | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MinimizeFWRules:
"""This is a class for minimizing and handling fw-rules globally for all connection sets"""
def __init__(self, fw_rules_map, cluster_info, output_config, results_map):
"""create n object of MinimizeFWRules :param fw_rules_map: a map from ConnectionSet to list[FWRule]... | stack_v2_sparse_classes_36k_train_015887 | 39,627 | permissive | [
{
"docstring": "create n object of MinimizeFWRules :param fw_rules_map: a map from ConnectionSet to list[FWRule] - the list of minimized fw-rules per connection :param cluster_info: an object of type ClusterInfo :param output_config: an object of type OutputConiguration :param results_map: (temp, for debugging)... | 4 | stack_v2_sparse_classes_30k_train_005716 | Implement the Python class `MinimizeFWRules` described below.
Class description:
This is a class for minimizing and handling fw-rules globally for all connection sets
Method signatures and docstrings:
- def __init__(self, fw_rules_map, cluster_info, output_config, results_map): create n object of MinimizeFWRules :par... | Implement the Python class `MinimizeFWRules` described below.
Class description:
This is a class for minimizing and handling fw-rules globally for all connection sets
Method signatures and docstrings:
- def __init__(self, fw_rules_map, cluster_info, output_config, results_map): create n object of MinimizeFWRules :par... | b04e06d8e04cb0c8de87196c3f571b8a53abd0bd | <|skeleton|>
class MinimizeFWRules:
"""This is a class for minimizing and handling fw-rules globally for all connection sets"""
def __init__(self, fw_rules_map, cluster_info, output_config, results_map):
"""create n object of MinimizeFWRules :param fw_rules_map: a map from ConnectionSet to list[FWRule]... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MinimizeFWRules:
"""This is a class for minimizing and handling fw-rules globally for all connection sets"""
def __init__(self, fw_rules_map, cluster_info, output_config, results_map):
"""create n object of MinimizeFWRules :param fw_rules_map: a map from ConnectionSet to list[FWRule] - the list o... | the_stack_v2_python_sparse | network-config-analyzer/MinimizeFWRules.py | hbnworkstation/network-config-analyzer | train | 0 |
d8d3e38b2a04a1596b63761b1c616a68cb7006f5 | [
"copy_file('./entrypoint.sh', build_dir)\nsetup_commands = ['RUN conda config --add channels conda-forge', 'COPY ./entrypoint.sh /entrypoint.sh', 'RUN chmod +x /entrypoint.sh']\nreturn '\\n'.join(setup_commands)",
"print('Building Serving Image....')\nbuild_serving_image(image_name=image_name, mlflow_home=None, c... | <|body_start_0|>
copy_file('./entrypoint.sh', build_dir)
setup_commands = ['RUN conda config --add channels conda-forge', 'COPY ./entrypoint.sh /entrypoint.sh', 'RUN chmod +x /entrypoint.sh']
return '\n'.join(setup_commands)
<|end_body_0|>
<|body_start_1|>
print('Building Serving Image.... | Build our custom mlflow model serving container | ImageBuilder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageBuilder:
"""Build our custom mlflow model serving container"""
def splice_serving_custom_install_hook(build_dir):
"""Custom Install Hook for Splice Machine Model Serving container :return: custom install steps as a string"""
<|body_0|>
def build_docker(image_name: s... | stack_v2_sparse_classes_36k_train_015888 | 1,763 | permissive | [
{
"docstring": "Custom Install Hook for Splice Machine Model Serving container :return: custom install steps as a string",
"name": "splice_serving_custom_install_hook",
"signature": "def splice_serving_custom_install_hook(build_dir)"
},
{
"docstring": "Build the docker image :return:",
"name... | 2 | stack_v2_sparse_classes_30k_train_002977 | Implement the Python class `ImageBuilder` described below.
Class description:
Build our custom mlflow model serving container
Method signatures and docstrings:
- def splice_serving_custom_install_hook(build_dir): Custom Install Hook for Splice Machine Model Serving container :return: custom install steps as a string
... | Implement the Python class `ImageBuilder` described below.
Class description:
Build our custom mlflow model serving container
Method signatures and docstrings:
- def splice_serving_custom_install_hook(build_dir): Custom Install Hook for Splice Machine Model Serving container :return: custom install steps as a string
... | 2f9a0d3d2814941c6bd78f9dcc019870a4e8c2da | <|skeleton|>
class ImageBuilder:
"""Build our custom mlflow model serving container"""
def splice_serving_custom_install_hook(build_dir):
"""Custom Install Hook for Splice Machine Model Serving container :return: custom install steps as a string"""
<|body_0|>
def build_docker(image_name: s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageBuilder:
"""Build our custom mlflow model serving container"""
def splice_serving_custom_install_hook(build_dir):
"""Custom Install Hook for Splice Machine Model Serving container :return: custom install steps as a string"""
copy_file('./entrypoint.sh', build_dir)
setup_comma... | the_stack_v2_python_sparse | infrastructure/model_deployment/serving/build_serving_dockerfile.py | myles-novick/ml-workflow | train | 0 |
ea608673c6f83bbd424d5e95a18baf17cfcf1ca5 | [
"assert isinstance(path, unicode), path\nlisting = os.listdir(path)\nout = []\nfor item in listing:\n if not item.endswith('.pyc') and item != '__init__.py':\n out.append(item)\nreturn out",
"assert isinstance(path, unicode), path\nempty = True\nfor item in os.listdir(path):\n if not item.endswith('.... | <|body_start_0|>
assert isinstance(path, unicode), path
listing = os.listdir(path)
out = []
for item in listing:
if not item.endswith('.pyc') and item != '__init__.py':
out.append(item)
return out
<|end_body_0|>
<|body_start_1|>
assert isinsta... | This custom file system is much like the default AbstractedFS except that it will not return pyc files and init files. Default init files are also added to new directories automatically. It also will allow directories to be removed with pyc and __init__.py files in them. | HumbleAbstractedFS | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HumbleAbstractedFS:
"""This custom file system is much like the default AbstractedFS except that it will not return pyc files and init files. Default init files are also added to new directories automatically. It also will allow directories to be removed with pyc and __init__.py files in them."""... | stack_v2_sparse_classes_36k_train_015889 | 2,366 | no_license | [
{
"docstring": "List the content of a directory.",
"name": "listdir",
"signature": "def listdir(self, path)"
},
{
"docstring": "Remove the specified directory.",
"name": "rmdir",
"signature": "def rmdir(self, path)"
},
{
"docstring": "Create the specified directory.",
"name":... | 5 | stack_v2_sparse_classes_30k_train_007128 | Implement the Python class `HumbleAbstractedFS` described below.
Class description:
This custom file system is much like the default AbstractedFS except that it will not return pyc files and init files. Default init files are also added to new directories automatically. It also will allow directories to be removed wit... | Implement the Python class `HumbleAbstractedFS` described below.
Class description:
This custom file system is much like the default AbstractedFS except that it will not return pyc files and init files. Default init files are also added to new directories automatically. It also will allow directories to be removed wit... | 4d5ecb1473147cb13a556ab4ce5a368638055c08 | <|skeleton|>
class HumbleAbstractedFS:
"""This custom file system is much like the default AbstractedFS except that it will not return pyc files and init files. Default init files are also added to new directories automatically. It also will allow directories to be removed with pyc and __init__.py files in them."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HumbleAbstractedFS:
"""This custom file system is much like the default AbstractedFS except that it will not return pyc files and init files. Default init files are also added to new directories automatically. It also will allow directories to be removed with pyc and __init__.py files in them."""
def lis... | the_stack_v2_python_sparse | servers/ftp/abstractedFS.py | automicus/Automaton | train | 0 |
c0b5dec99912e0602b4450fd470f2723456d9b5e | [
"names = set()\nindices = dict()\nwith open(filename, 'r') as infile:\n data = list(csv.reader(infile))\nfor line in data:\n for person in line:\n names.add(person)\nlist_names = list(names)\nself.names = list_names\nn = len(list_names)\nadj = np.zeros((n, n))\nfor line in data:\n a, b = (line[0], l... | <|body_start_0|>
names = set()
indices = dict()
with open(filename, 'r') as infile:
data = list(csv.reader(infile))
for line in data:
for person in line:
names.add(person)
list_names = list(names)
self.names = list_names
n =... | Predict links between nodes of a network. | LinkPredictor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkPredictor:
"""Predict links between nodes of a network."""
def __init__(self, filename='social_network.csv'):
"""Create the effective resistance matrix by constructing an adjacency matrix. Parameters: filename (str): The name of a file containing graph data."""
<|body_0|>... | stack_v2_sparse_classes_36k_train_015890 | 15,129 | no_license | [
{
"docstring": "Create the effective resistance matrix by constructing an adjacency matrix. Parameters: filename (str): The name of a file containing graph data.",
"name": "__init__",
"signature": "def __init__(self, filename='social_network.csv')"
},
{
"docstring": "Predict the next link, eithe... | 3 | stack_v2_sparse_classes_30k_train_009259 | Implement the Python class `LinkPredictor` described below.
Class description:
Predict links between nodes of a network.
Method signatures and docstrings:
- def __init__(self, filename='social_network.csv'): Create the effective resistance matrix by constructing an adjacency matrix. Parameters: filename (str): The na... | Implement the Python class `LinkPredictor` described below.
Class description:
Predict links between nodes of a network.
Method signatures and docstrings:
- def __init__(self, filename='social_network.csv'): Create the effective resistance matrix by constructing an adjacency matrix. Parameters: filename (str): The na... | a7de984715c16e2c073e39aa4cdfe3f26f2110d8 | <|skeleton|>
class LinkPredictor:
"""Predict links between nodes of a network."""
def __init__(self, filename='social_network.csv'):
"""Create the effective resistance matrix by constructing an adjacency matrix. Parameters: filename (str): The name of a file containing graph data."""
<|body_0|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinkPredictor:
"""Predict links between nodes of a network."""
def __init__(self, filename='social_network.csv'):
"""Create the effective resistance matrix by constructing an adjacency matrix. Parameters: filename (str): The name of a file containing graph data."""
names = set()
i... | the_stack_v2_python_sparse | Drazin/Drazin_Inverse.py | jbwilkes/Projects1 | train | 0 |
7f30a18b578033d0809f9e3d4a39a60327168234 | [
"super(TokenSim, self).__init__()\nself.config = config\nself.data_extractor = data_extractor\nself.tokenizer = tokenizer\nlist_include_flags = [True, self.config.include_city, self.config.include_state, self.config.include_country, self.config.include_type]\nself.counter = 0\nfor flag in list_include_flags:\n i... | <|body_start_0|>
super(TokenSim, self).__init__()
self.config = config
self.data_extractor = data_extractor
self.tokenizer = tokenizer
list_include_flags = [True, self.config.include_city, self.config.include_state, self.config.include_country, self.config.include_type]
s... | TokenSim | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TokenSim:
def __init__(self, config, data_extractor, tokenizer):
"""param config: config object param vocab: vocab object param max_len_token: max number of tokens"""
<|body_0|>
def score_pair_train(self, qry_tk, cnd_tk, qry_min_cnd_tk, cnd_min_qry_tk, qry_insct_cnd_tk):
... | stack_v2_sparse_classes_36k_train_015891 | 3,435 | no_license | [
{
"docstring": "param config: config object param vocab: vocab object param max_len_token: max number of tokens",
"name": "__init__",
"signature": "def __init__(self, config, data_extractor, tokenizer)"
},
{
"docstring": "Scores the batch of query candidate pair Take the dot product of set repre... | 3 | stack_v2_sparse_classes_30k_train_000285 | Implement the Python class `TokenSim` described below.
Class description:
Implement the TokenSim class.
Method signatures and docstrings:
- def __init__(self, config, data_extractor, tokenizer): param config: config object param vocab: vocab object param max_len_token: max number of tokens
- def score_pair_train(self... | Implement the Python class `TokenSim` described below.
Class description:
Implement the TokenSim class.
Method signatures and docstrings:
- def __init__(self, config, data_extractor, tokenizer): param config: config object param vocab: vocab object param max_len_token: max number of tokens
- def score_pair_train(self... | c0b2f83a7d4c0d5fa5effb7584e0e0acc6f877a0 | <|skeleton|>
class TokenSim:
def __init__(self, config, data_extractor, tokenizer):
"""param config: config object param vocab: vocab object param max_len_token: max number of tokens"""
<|body_0|>
def score_pair_train(self, qry_tk, cnd_tk, qry_min_cnd_tk, cnd_min_qry_tk, qry_insct_cnd_tk):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TokenSim:
def __init__(self, config, data_extractor, tokenizer):
"""param config: config object param vocab: vocab object param max_len_token: max number of tokens"""
super(TokenSim, self).__init__()
self.config = config
self.data_extractor = data_extractor
self.tokeniz... | the_stack_v2_python_sparse | src/main/baselines/TokenSim.py | iesl/institution_hierarchies | train | 3 | |
70c32a23905fe2bffa162ba3e8569f6f4d63b656 | [
"super().__init__()\nself.start_pol = self._get_constant(start_pol)\nself.period = self._get_constant(period)\nself._level = bool(self.start_pol)\nself._last_edge = 0",
"for x in iter(int, 1):\n if self._last_edge > self.period - 1:\n self._level = not self._level\n self._last_edge = 1\n else:... | <|body_start_0|>
super().__init__()
self.start_pol = self._get_constant(start_pol)
self.period = self._get_constant(period)
self._level = bool(self.start_pol)
self._last_edge = 0
<|end_body_0|>
<|body_start_1|>
for x in iter(int, 1):
if self._last_edge > self... | Clock generator. | HDLSimulationClock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HDLSimulationClock:
"""Clock generator."""
def __init__(self, period, start_pol=1):
"""Initialize."""
<|body_0|>
def next(self):
"""Generate values."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__()
self.start_pol = self... | stack_v2_sparse_classes_36k_train_015892 | 1,593 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, period, start_pol=1)"
},
{
"docstring": "Generate values.",
"name": "next",
"signature": "def next(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020362 | Implement the Python class `HDLSimulationClock` described below.
Class description:
Clock generator.
Method signatures and docstrings:
- def __init__(self, period, start_pol=1): Initialize.
- def next(self): Generate values. | Implement the Python class `HDLSimulationClock` described below.
Class description:
Clock generator.
Method signatures and docstrings:
- def __init__(self, period, start_pol=1): Initialize.
- def next(self): Generate values.
<|skeleton|>
class HDLSimulationClock:
"""Clock generator."""
def __init__(self, pe... | 463412cf6a72456acc8cb99569e7dc9c9d472f6d | <|skeleton|>
class HDLSimulationClock:
"""Clock generator."""
def __init__(self, period, start_pol=1):
"""Initialize."""
<|body_0|>
def next(self):
"""Generate values."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HDLSimulationClock:
"""Clock generator."""
def __init__(self, period, start_pol=1):
"""Initialize."""
super().__init__()
self.start_pol = self._get_constant(start_pol)
self.period = self._get_constant(period)
self._level = bool(self.start_pol)
self._last_ed... | the_stack_v2_python_sparse | hdltools/hdllib/sim.py | brunosmmm/hdltools | train | 2 |
274abdb88bdc24b6b9d7a52f9f47735c9f04898a | [
"if os.environ.get('TCL_LIBRARY'):\n self.had_TCL_LIBRARY = True\n self.old_TCL_LIBRARY = os.environ['TCL_LIBRARY']\nelse:\n self.had_TCL_LIBRARY = False\ntcl_path = os.path.join(devkit_root, 'tools', 'python27', 'tcl', 'tcl8.5')\nos.environ['TCL_LIBRARY'] = tcl_path",
"if self.had_TCL_LIBRARY:\n os.e... | <|body_start_0|>
if os.environ.get('TCL_LIBRARY'):
self.had_TCL_LIBRARY = True
self.old_TCL_LIBRARY = os.environ['TCL_LIBRARY']
else:
self.had_TCL_LIBRARY = False
tcl_path = os.path.join(devkit_root, 'tools', 'python27', 'tcl', 'tcl8.5')
os.environ['TC... | TCL_LIBRARY_handler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TCL_LIBRARY_handler:
def __init__(self, devkit_root):
"""If there is already a TCL_LIBRARY environment variable, save it so can restore it later when done with Tkinter, or note that there wasn't one. Set the TCL_LIBRARY environment variable to what is needed by Tkinter."""
<|body... | stack_v2_sparse_classes_36k_train_015893 | 24,092 | no_license | [
{
"docstring": "If there is already a TCL_LIBRARY environment variable, save it so can restore it later when done with Tkinter, or note that there wasn't one. Set the TCL_LIBRARY environment variable to what is needed by Tkinter.",
"name": "__init__",
"signature": "def __init__(self, devkit_root)"
},
... | 2 | stack_v2_sparse_classes_30k_train_021201 | Implement the Python class `TCL_LIBRARY_handler` described below.
Class description:
Implement the TCL_LIBRARY_handler class.
Method signatures and docstrings:
- def __init__(self, devkit_root): If there is already a TCL_LIBRARY environment variable, save it so can restore it later when done with Tkinter, or note tha... | Implement the Python class `TCL_LIBRARY_handler` described below.
Class description:
Implement the TCL_LIBRARY_handler class.
Method signatures and docstrings:
- def __init__(self, devkit_root): If there is already a TCL_LIBRARY environment variable, save it so can restore it later when done with Tkinter, or note tha... | bff2d8c9e5e1ead4018f63098c1adea0e0c28184 | <|skeleton|>
class TCL_LIBRARY_handler:
def __init__(self, devkit_root):
"""If there is already a TCL_LIBRARY environment variable, save it so can restore it later when done with Tkinter, or note that there wasn't one. Set the TCL_LIBRARY environment variable to what is needed by Tkinter."""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TCL_LIBRARY_handler:
def __init__(self, devkit_root):
"""If there is already a TCL_LIBRARY environment variable, save it so can restore it later when done with Tkinter, or note that there wasn't one. Set the TCL_LIBRARY environment variable to what is needed by Tkinter."""
if os.environ.get('T... | the_stack_v2_python_sparse | adk/tools/packages/menus/buildFlashImage.py | litterstar7/Qualcomm_BT_Audio | train | 4 | |
aaa8a371f8bf8e2b655cf49b00976257b53247ca | [
"error_checking.assert_is_numpy_array(binary_region_matrix, num_dimensions=2)\nerror_checking.assert_is_integer_numpy_array(binary_region_matrix)\nerror_checking.assert_is_geq_numpy_array(binary_region_matrix, 0)\nerror_checking.assert_is_leq_numpy_array(binary_region_matrix, 1)\nsetattr(self, NUM_GRID_ROWS_KEY, bi... | <|body_start_0|>
error_checking.assert_is_numpy_array(binary_region_matrix, num_dimensions=2)
error_checking.assert_is_integer_numpy_array(binary_region_matrix)
error_checking.assert_is_geq_numpy_array(binary_region_matrix, 0)
error_checking.assert_is_leq_numpy_array(binary_region_matrix... | Allows A-star to search through a physical grid. Each node is a grid cell at location (column, row)*** or (c, r). The goal is to navigate from the start node (first grid cell) to the end node (last grid cell), using only grid cells that are part of a connected region. There may be no path through the connected region, ... | GridSearch | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GridSearch:
"""Allows A-star to search through a physical grid. Each node is a grid cell at location (column, row)*** or (c, r). The goal is to navigate from the start node (first grid cell) to the end node (last grid cell), using only grid cells that are part of a connected region. There may be ... | stack_v2_sparse_classes_36k_train_015894 | 6,630 | permissive | [
{
"docstring": "Creates new instance. :param binary_region_matrix: M-by-N numpy array of integers in 0...1. If binary_region_matrix[i, j] = 1, grid cell [i, j] is part of the connected region.",
"name": "__init__",
"signature": "def __init__(self, binary_region_matrix)"
},
{
"docstring": "Return... | 4 | stack_v2_sparse_classes_30k_train_021484 | Implement the Python class `GridSearch` described below.
Class description:
Allows A-star to search through a physical grid. Each node is a grid cell at location (column, row)*** or (c, r). The goal is to navigate from the start node (first grid cell) to the end node (last grid cell), using only grid cells that are pa... | Implement the Python class `GridSearch` described below.
Class description:
Allows A-star to search through a physical grid. Each node is a grid cell at location (column, row)*** or (c, r). The goal is to navigate from the start node (first grid cell) to the end node (last grid cell), using only grid cells that are pa... | 95b99a16fdaa67dae69586c7f7c76e27ccd4b89a | <|skeleton|>
class GridSearch:
"""Allows A-star to search through a physical grid. Each node is a grid cell at location (column, row)*** or (c, r). The goal is to navigate from the start node (first grid cell) to the end node (last grid cell), using only grid cells that are part of a connected region. There may be ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GridSearch:
"""Allows A-star to search through a physical grid. Each node is a grid cell at location (column, row)*** or (c, r). The goal is to navigate from the start node (first grid cell) to the end node (last grid cell), using only grid cells that are part of a connected region. There may be no path throu... | the_stack_v2_python_sparse | generalexam/ge_utils/a_star_search.py | thunderhoser/GeneralExam | train | 4 |
185e90b412d883cfde27972d7d0e45fa75cbc5b9 | [
"payload_normal = {'serialId': 3, 'dealerId': 10001, 'styleId': 9}\n'发送请求'\nr = requests.get(url=self.url_g, params=payload_normal)\n'打印请求url、请求状态码、请求报文'\nprint('请求的url是:', r.url)\nprint('请求返回的状态码是:', r.status_code)\nprint('请求返回的内容是:', r.text)\nprint(r.status_code == requests.codes.ok)\n'后续补充其他断言,数据验证等'",
"payloa... | <|body_start_0|>
payload_normal = {'serialId': 3, 'dealerId': 10001, 'styleId': 9}
'发送请求'
r = requests.get(url=self.url_g, params=payload_normal)
'打印请求url、请求状态码、请求报文'
print('请求的url是:', r.url)
print('请求返回的状态码是:', r.status_code)
print('请求返回的内容是:', r.text)
pr... | 把接口封装成一个接口类,下面的每个方法对应一条接口测试用例,以上信息会在报告中显示 | test_getStyleConfigList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_getStyleConfigList:
"""把接口封装成一个接口类,下面的每个方法对应一条接口测试用例,以上信息会在报告中显示"""
def test_getStyleConfigList_normal(self):
"""正确的参数"""
<|body_0|>
def test_getStyleConfigList_str(self):
"""输入str类型参数"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
payload... | stack_v2_sparse_classes_36k_train_015895 | 2,001 | no_license | [
{
"docstring": "正确的参数",
"name": "test_getStyleConfigList_normal",
"signature": "def test_getStyleConfigList_normal(self)"
},
{
"docstring": "输入str类型参数",
"name": "test_getStyleConfigList_str",
"signature": "def test_getStyleConfigList_str(self)"
}
] | 2 | null | Implement the Python class `test_getStyleConfigList` described below.
Class description:
把接口封装成一个接口类,下面的每个方法对应一条接口测试用例,以上信息会在报告中显示
Method signatures and docstrings:
- def test_getStyleConfigList_normal(self): 正确的参数
- def test_getStyleConfigList_str(self): 输入str类型参数 | Implement the Python class `test_getStyleConfigList` described below.
Class description:
把接口封装成一个接口类,下面的每个方法对应一条接口测试用例,以上信息会在报告中显示
Method signatures and docstrings:
- def test_getStyleConfigList_normal(self): 正确的参数
- def test_getStyleConfigList_str(self): 输入str类型参数
<|skeleton|>
class test_getStyleConfigList:
"""... | a288e1d266bfa1a7200ba2a6d74394f889973023 | <|skeleton|>
class test_getStyleConfigList:
"""把接口封装成一个接口类,下面的每个方法对应一条接口测试用例,以上信息会在报告中显示"""
def test_getStyleConfigList_normal(self):
"""正确的参数"""
<|body_0|>
def test_getStyleConfigList_str(self):
"""输入str类型参数"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class test_getStyleConfigList:
"""把接口封装成一个接口类,下面的每个方法对应一条接口测试用例,以上信息会在报告中显示"""
def test_getStyleConfigList_normal(self):
"""正确的参数"""
payload_normal = {'serialId': 3, 'dealerId': 10001, 'styleId': 9}
'发送请求'
r = requests.get(url=self.url_g, params=payload_normal)
'打印请求url、... | the_stack_v2_python_sparse | CloudYoung/liuhl/interface/test_case/test_getStyleConfigList.py | gengyanqikobe/Home_PC_share | train | 0 |
c4fef93deb1aa45b1138fe756e80f705785758c0 | [
"is_organizer(request)\nuser_id = request.data.get('user_id', False)\nif not user_id:\n return Response({'detail': 'Provide user id!'}, status=400)\norganizer = User.objects.get(id=user_id)\nis_premium = bool(request.data.get('is_premium', False))\npackage_id = int(request.data.get('package_id', 3))\nsub = organ... | <|body_start_0|>
is_organizer(request)
user_id = request.data.get('user_id', False)
if not user_id:
return Response({'detail': 'Provide user id!'}, status=400)
organizer = User.objects.get(id=user_id)
is_premium = bool(request.data.get('is_premium', False))
pa... | PackageViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PackageViewSet:
def create(self, request, format=None):
"""Sample submit: --- { 'user_id': 23, 'is_premium': true, 'package_id': 2, }"""
<|body_0|>
def update(self, request, pk, format=None):
"""Sample submit: --- { 'is_premium': true, 'package_id': 2, }"""
<... | stack_v2_sparse_classes_36k_train_015896 | 21,103 | no_license | [
{
"docstring": "Sample submit: --- { 'user_id': 23, 'is_premium': true, 'package_id': 2, }",
"name": "create",
"signature": "def create(self, request, format=None)"
},
{
"docstring": "Sample submit: --- { 'is_premium': true, 'package_id': 2, }",
"name": "update",
"signature": "def update... | 3 | stack_v2_sparse_classes_30k_train_002866 | Implement the Python class `PackageViewSet` described below.
Class description:
Implement the PackageViewSet class.
Method signatures and docstrings:
- def create(self, request, format=None): Sample submit: --- { 'user_id': 23, 'is_premium': true, 'package_id': 2, }
- def update(self, request, pk, format=None): Sampl... | Implement the Python class `PackageViewSet` described below.
Class description:
Implement the PackageViewSet class.
Method signatures and docstrings:
- def create(self, request, format=None): Sample submit: --- { 'user_id': 23, 'is_premium': true, 'package_id': 2, }
- def update(self, request, pk, format=None): Sampl... | 11be165f85cda0ffe7a237d011de562d3dc64135 | <|skeleton|>
class PackageViewSet:
def create(self, request, format=None):
"""Sample submit: --- { 'user_id': 23, 'is_premium': true, 'package_id': 2, }"""
<|body_0|>
def update(self, request, pk, format=None):
"""Sample submit: --- { 'is_premium': true, 'package_id': 2, }"""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PackageViewSet:
def create(self, request, format=None):
"""Sample submit: --- { 'user_id': 23, 'is_premium': true, 'package_id': 2, }"""
is_organizer(request)
user_id = request.data.get('user_id', False)
if not user_id:
return Response({'detail': 'Provide user id!'}... | the_stack_v2_python_sparse | apps/billing/views.py | ash018/FFTracker | train | 0 | |
f7f521fe038f5091776f4dbd78805027b057eccc | [
"t1 = random.choice(self._dataset.category_names)\nwhile True:\n idx2 = random.randint(0, self._dataset.category_sizes[t1])\n if idx1 != idx2:\n break\nwhile True:\n t2 = random.choice(self._dataset.category_names)\n if t1 != t2:\n break\nreturn (self._dataset.sample(t1, idx1)[0], self._da... | <|body_start_0|>
t1 = random.choice(self._dataset.category_names)
while True:
idx2 = random.randint(0, self._dataset.category_sizes[t1])
if idx1 != idx2:
break
while True:
t2 = random.choice(self._dataset.category_names)
if t1 != t2... | # This dataset generates a triple of images. an image of a category, another of the same category and lastly one from another category | TripletDataset | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TripletDataset:
"""# This dataset generates a triple of images. an image of a category, another of the same category and lastly one from another category"""
def __getitem__(self, idx1: int) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""returns torch.tensors for img triplet, ... | stack_v2_sparse_classes_36k_train_015897 | 2,770 | permissive | [
{
"docstring": "returns torch.tensors for img triplet, first tensor being idx random category, second being the same category with different index and third being of a random other category(Never the same) :param idx1: :type idx1: :return: :rtype:",
"name": "__getitem__",
"signature": "def __getitem__(s... | 2 | null | Implement the Python class `TripletDataset` described below.
Class description:
# This dataset generates a triple of images. an image of a category, another of the same category and lastly one from another category
Method signatures and docstrings:
- def __getitem__(self, idx1: int) -> Tuple[torch.Tensor, torch.Tenso... | Implement the Python class `TripletDataset` described below.
Class description:
# This dataset generates a triple of images. an image of a category, another of the same category and lastly one from another category
Method signatures and docstrings:
- def __getitem__(self, idx1: int) -> Tuple[torch.Tensor, torch.Tenso... | 06839b08d8e8f274c02a6bcd31bf1b32d3dc04e4 | <|skeleton|>
class TripletDataset:
"""# This dataset generates a triple of images. an image of a category, another of the same category and lastly one from another category"""
def __getitem__(self, idx1: int) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""returns torch.tensors for img triplet, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TripletDataset:
"""# This dataset generates a triple of images. an image of a category, another of the same category and lastly one from another category"""
def __getitem__(self, idx1: int) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""returns torch.tensors for img triplet, first tensor ... | the_stack_v2_python_sparse | neodroidvision/data/classification/nlet/triplet_dataset.py | aivclab/vision | train | 1 |
58f08e42e09cfd43ed70b3b55c7b0c876f8f68e7 | [
"format_date = lambda d: d.date().strftime('%d.%m.%Y')\ndate_from, date_till = get_datetime_from_till(7)\nsubject = cls.get_full_subject('Подборка материалов %s-%s' % (format_date(date_from), format_date(date_till)))\ncontext = {'date_from': date_from.timestamp(), 'date_till': date_till.timestamp()}\ncls(subject, c... | <|body_start_0|>
format_date = lambda d: d.date().strftime('%d.%m.%Y')
date_from, date_till = get_datetime_from_till(7)
subject = cls.get_full_subject('Подборка материалов %s-%s' % (format_date(date_from), format_date(date_till)))
context = {'date_from': date_from.timestamp(), 'date_till... | Класс реализующий рассылку с подборкой новых материалов сайта (сводку). | PythonzEmailDigest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PythonzEmailDigest:
"""Класс реализующий рассылку с подборкой новых материалов сайта (сводку)."""
def create(cls):
"""Создаёт депеши для рассылки еженедельной сводки. Реальная компиляция сводки происходит в compile(). :return:"""
<|body_0|>
def get_realms_data(cls, date_... | stack_v2_sparse_classes_36k_train_015898 | 16,316 | no_license | [
{
"docstring": "Создаёт депеши для рассылки еженедельной сводки. Реальная компиляция сводки происходит в compile(). :return:",
"name": "create",
"signature": "def create(cls)"
},
{
"docstring": "Возвращает данные о материалах за указанный период. :param date date_from: Дата начала периода :param... | 5 | stack_v2_sparse_classes_30k_train_013124 | Implement the Python class `PythonzEmailDigest` described below.
Class description:
Класс реализующий рассылку с подборкой новых материалов сайта (сводку).
Method signatures and docstrings:
- def create(cls): Создаёт депеши для рассылки еженедельной сводки. Реальная компиляция сводки происходит в compile(). :return:
... | Implement the Python class `PythonzEmailDigest` described below.
Class description:
Класс реализующий рассылку с подборкой новых материалов сайта (сводку).
Method signatures and docstrings:
- def create(cls): Создаёт депеши для рассылки еженедельной сводки. Реальная компиляция сводки происходит в compile(). :return:
... | 8d5d41755f33b7850af677ba0a2f26cba823daf9 | <|skeleton|>
class PythonzEmailDigest:
"""Класс реализующий рассылку с подборкой новых материалов сайта (сводку)."""
def create(cls):
"""Создаёт депеши для рассылки еженедельной сводки. Реальная компиляция сводки происходит в compile(). :return:"""
<|body_0|>
def get_realms_data(cls, date_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PythonzEmailDigest:
"""Класс реализующий рассылку с подборкой новых материалов сайта (сводку)."""
def create(cls):
"""Создаёт депеши для рассылки еженедельной сводки. Реальная компиляция сводки происходит в compile(). :return:"""
format_date = lambda d: d.date().strftime('%d.%m.%Y')
... | the_stack_v2_python_sparse | apps/sitemessages.py | GraceAredel/pythonz | train | 1 |
0ea5759351dc9d80090a5428f81382b1dea3fc40 | [
"_LOGGER.debug('Generating signing key')\nif algorithm.signing_algorithm_info is None:\n return None\nsigner = Signer(algorithm=algorithm, key=generate_ecc_signing_key(algorithm=algorithm))\nencryption_context[ENCODED_SIGNER_KEY] = to_str(signer.encoded_public_key())\nreturn signer.key_bytes()",
"default_algor... | <|body_start_0|>
_LOGGER.debug('Generating signing key')
if algorithm.signing_algorithm_info is None:
return None
signer = Signer(algorithm=algorithm, key=generate_ecc_signing_key(algorithm=algorithm))
encryption_context[ENCODED_SIGNER_KEY] = to_str(signer.encoded_public_key(... | Default crypto material manager. .. versionadded:: 1.3.0 :param master_key_provider: Master key provider to use :type master_key_provider: aws_encryption_sdk.key_providers.base.MasterKeyProvider | DefaultCryptoMaterialsManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefaultCryptoMaterialsManager:
"""Default crypto material manager. .. versionadded:: 1.3.0 :param master_key_provider: Master key provider to use :type master_key_provider: aws_encryption_sdk.key_providers.base.MasterKeyProvider"""
def _generate_signing_key_and_update_encryption_context(self... | stack_v2_sparse_classes_36k_train_015899 | 7,444 | permissive | [
{
"docstring": "Generates a signing key based on the provided algorithm. :param algorithm: Algorithm for which to generate signing key :type algorithm: aws_encryption_sdk.identifiers.Algorithm :param dict encryption_context: Encryption context from request :returns: Signing key bytes :rtype: bytes or None",
... | 4 | stack_v2_sparse_classes_30k_train_003268 | Implement the Python class `DefaultCryptoMaterialsManager` described below.
Class description:
Default crypto material manager. .. versionadded:: 1.3.0 :param master_key_provider: Master key provider to use :type master_key_provider: aws_encryption_sdk.key_providers.base.MasterKeyProvider
Method signatures and docstr... | Implement the Python class `DefaultCryptoMaterialsManager` described below.
Class description:
Default crypto material manager. .. versionadded:: 1.3.0 :param master_key_provider: Master key provider to use :type master_key_provider: aws_encryption_sdk.key_providers.base.MasterKeyProvider
Method signatures and docstr... | 3ba8019681ed95c41bb9448f0c3897d1aecc7559 | <|skeleton|>
class DefaultCryptoMaterialsManager:
"""Default crypto material manager. .. versionadded:: 1.3.0 :param master_key_provider: Master key provider to use :type master_key_provider: aws_encryption_sdk.key_providers.base.MasterKeyProvider"""
def _generate_signing_key_and_update_encryption_context(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DefaultCryptoMaterialsManager:
"""Default crypto material manager. .. versionadded:: 1.3.0 :param master_key_provider: Master key provider to use :type master_key_provider: aws_encryption_sdk.key_providers.base.MasterKeyProvider"""
def _generate_signing_key_and_update_encryption_context(self, algorithm, ... | the_stack_v2_python_sparse | src/aws_encryption_sdk/materials_managers/default.py | aws/aws-encryption-sdk-python | train | 137 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.