blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5c043ebef3506500eac8f169fd400079432885f2 | [
"super(GroupAdmin, self).AssertBasePermission(mr)\n_, owner_ids_dict = self.services.usergroup.LookupMembers(mr.cnxn, [mr.viewed_user_auth.user_id])\nowner_ids = owner_ids_dict[mr.viewed_user_auth.user_id]\nif not permissions.CanEditGroup(mr.perms, mr.auth.effective_ids, owner_ids):\n raise permissions.Permissio... | <|body_start_0|>
super(GroupAdmin, self).AssertBasePermission(mr)
_, owner_ids_dict = self.services.usergroup.LookupMembers(mr.cnxn, [mr.viewed_user_auth.user_id])
owner_ids = owner_ids_dict[mr.viewed_user_auth.user_id]
if not permissions.CanEditGroup(mr.perms, mr.auth.effective_ids, own... | The group admin page. | GroupAdmin | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupAdmin:
"""The group admin page."""
def AssertBasePermission(self, mr):
"""Assert that the user has the permissions needed to view this page."""
<|body_0|>
def GatherPageData(self, mr):
"""Build up a dictionary of data values to use when rendering the page.""... | stack_v2_sparse_classes_75kplus_train_002600 | 4,496 | permissive | [
{
"docstring": "Assert that the user has the permissions needed to view this page.",
"name": "AssertBasePermission",
"signature": "def AssertBasePermission(self, mr)"
},
{
"docstring": "Build up a dictionary of data values to use when rendering the page.",
"name": "GatherPageData",
"sign... | 3 | stack_v2_sparse_classes_30k_train_030659 | Implement the Python class `GroupAdmin` described below.
Class description:
The group admin page.
Method signatures and docstrings:
- def AssertBasePermission(self, mr): Assert that the user has the permissions needed to view this page.
- def GatherPageData(self, mr): Build up a dictionary of data values to use when ... | Implement the Python class `GroupAdmin` described below.
Class description:
The group admin page.
Method signatures and docstrings:
- def AssertBasePermission(self, mr): Assert that the user has the permissions needed to view this page.
- def GatherPageData(self, mr): Build up a dictionary of data values to use when ... | b5d4783f99461438ca9e6a477535617fadab6ba3 | <|skeleton|>
class GroupAdmin:
"""The group admin page."""
def AssertBasePermission(self, mr):
"""Assert that the user has the permissions needed to view this page."""
<|body_0|>
def GatherPageData(self, mr):
"""Build up a dictionary of data values to use when rendering the page.""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GroupAdmin:
"""The group admin page."""
def AssertBasePermission(self, mr):
"""Assert that the user has the permissions needed to view this page."""
super(GroupAdmin, self).AssertBasePermission(mr)
_, owner_ids_dict = self.services.usergroup.LookupMembers(mr.cnxn, [mr.viewed_user_... | the_stack_v2_python_sparse | appengine/monorail/sitewide/groupadmin.py | xinghun61/infra | train | 2 |
b1fa2a825a8fd0a9a3d2bde453058dc08fe402a1 | [
"def sink(i, j):\n if i < 0 or i == len(grid) or j < 0 or (j == len(grid[i])) or (grid[i][j] == '0'):\n return 0\n grid[i][j] = '0'\n sink(i + 1, j)\n sink(i - 1, j)\n sink(i, j + 1)\n sink(i, j - 1)\n return 1\nislands = 0\nfor i in range(len(grid)):\n for j in range(len(grid[i])):\n... | <|body_start_0|>
def sink(i, j):
if i < 0 or i == len(grid) or j < 0 or (j == len(grid[i])) or (grid[i][j] == '0'):
return 0
grid[i][j] = '0'
sink(i + 1, j)
sink(i - 1, j)
sink(i, j + 1)
sink(i, j - 1)
return 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numIslands(self, grid):
""":type grid: List[List[str]] :rtype: int"""
<|body_0|>
def numIslands_self(self, grid):
""":type grid: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def sink(i, j):
if... | stack_v2_sparse_classes_75kplus_train_002601 | 1,163 | no_license | [
{
"docstring": ":type grid: List[List[str]] :rtype: int",
"name": "numIslands",
"signature": "def numIslands(self, grid)"
},
{
"docstring": ":type grid: List[List[str]] :rtype: int",
"name": "numIslands_self",
"signature": "def numIslands_self(self, grid)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numIslands(self, grid): :type grid: List[List[str]] :rtype: int
- def numIslands_self(self, grid): :type grid: List[List[str]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numIslands(self, grid): :type grid: List[List[str]] :rtype: int
- def numIslands_self(self, grid): :type grid: List[List[str]] :rtype: int
<|skeleton|>
class Solution:
... | ea492ec864b50547214ecbbb2cdeeac21e70229b | <|skeleton|>
class Solution:
def numIslands(self, grid):
""":type grid: List[List[str]] :rtype: int"""
<|body_0|>
def numIslands_self(self, grid):
""":type grid: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def numIslands(self, grid):
""":type grid: List[List[str]] :rtype: int"""
def sink(i, j):
if i < 0 or i == len(grid) or j < 0 or (j == len(grid[i])) or (grid[i][j] == '0'):
return 0
grid[i][j] = '0'
sink(i + 1, j)
sink(i... | the_stack_v2_python_sparse | 200_number_of_islands/sol.py | lianke123321/leetcode_sol | train | 0 | |
d182644a784bbea7af6f0a819d235bb590dcb918 | [
"img_target = cv2.resize(image, dsize=(self.HEIGHT, self.WIDTH), interpolation=cv2.INTER_CUBIC)\nimg_target = np.expand_dims(img_target, axis=0)\nklass = self.model.predict(img_target)\nklass = klass.argmax(axis=-1)\nreturn klass[0]",
"hash_md5 = hashlib.md5()\nwith open(fname, 'rb') as fcontent:\n for chunk i... | <|body_start_0|>
img_target = cv2.resize(image, dsize=(self.HEIGHT, self.WIDTH), interpolation=cv2.INTER_CUBIC)
img_target = np.expand_dims(img_target, axis=0)
klass = self.model.predict(img_target)
klass = klass.argmax(axis=-1)
return klass[0]
<|end_body_0|>
<|body_start_1|>
... | This is the main classifier model, taking care of downloading additional data if necessary (ie. model weights!) | MaterialClassifier | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaterialClassifier:
"""This is the main classifier model, taking care of downloading additional data if necessary (ie. model weights!)"""
def classify(self, image):
"""Predict from a NUMPY array"""
<|body_0|>
def _read_file_md5(fname):
"""Read md5 from file Taken... | stack_v2_sparse_classes_75kplus_train_002602 | 5,171 | no_license | [
{
"docstring": "Predict from a NUMPY array",
"name": "classify",
"signature": "def classify(self, image)"
},
{
"docstring": "Read md5 from file Taken from: https://stackoverflow.com/questions/3431825/generating-an-md5-checksum-of-a-file",
"name": "_read_file_md5",
"signature": "def _read... | 3 | stack_v2_sparse_classes_30k_val_000118 | Implement the Python class `MaterialClassifier` described below.
Class description:
This is the main classifier model, taking care of downloading additional data if necessary (ie. model weights!)
Method signatures and docstrings:
- def classify(self, image): Predict from a NUMPY array
- def _read_file_md5(fname): Rea... | Implement the Python class `MaterialClassifier` described below.
Class description:
This is the main classifier model, taking care of downloading additional data if necessary (ie. model weights!)
Method signatures and docstrings:
- def classify(self, image): Predict from a NUMPY array
- def _read_file_md5(fname): Rea... | 40170adabb762576d18ce51db65fd1c8767eb852 | <|skeleton|>
class MaterialClassifier:
"""This is the main classifier model, taking care of downloading additional data if necessary (ie. model weights!)"""
def classify(self, image):
"""Predict from a NUMPY array"""
<|body_0|>
def _read_file_md5(fname):
"""Read md5 from file Taken... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MaterialClassifier:
"""This is the main classifier model, taking care of downloading additional data if necessary (ie. model weights!)"""
def classify(self, image):
"""Predict from a NUMPY array"""
img_target = cv2.resize(image, dsize=(self.HEIGHT, self.WIDTH), interpolation=cv2.INTER_CUB... | the_stack_v2_python_sparse | ecoclassifier/src/ecoclassifier/material_classifier.py | antbertrand/ecoclassifier | train | 0 |
931c1ee02f9e339be91ec69cf54c9c4005651d63 | [
"select_interro_options = [{'id': 'select_interro_test_empty', 'label': '-- Please choose --', 'value': '-'}] + [{'id': 'select_interro_{}'.format(interro.pk), 'label': interro.modele.description, 'value': interro.pk} for interro in Interrogation.objects.filter(user=request.user)]\ndata_step = data.get(wz_user_step... | <|body_start_0|>
select_interro_options = [{'id': 'select_interro_test_empty', 'label': '-- Please choose --', 'value': '-'}] + [{'id': 'select_interro_{}'.format(interro.pk), 'label': interro.modele.description, 'value': interro.pk} for interro in Interrogation.objects.filter(user=request.user)]
data_s... | WizardStepNewExamStep2 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WizardStepNewExamStep2:
def get_content(self, request, wz_user_step, data, **kwargs):
"""Args: request: the current request wz_user_step: current wz_user_step model data: all data gathered step after step **kwargs: other arguments (company and uuid amongst others) Returns: Object that sh... | stack_v2_sparse_classes_75kplus_train_002603 | 6,848 | permissive | [
{
"docstring": "Args: request: the current request wz_user_step: current wz_user_step model data: all data gathered step after step **kwargs: other arguments (company and uuid amongst others) Returns: Object that should be returned as JSON",
"name": "get_content",
"signature": "def get_content(self, req... | 3 | stack_v2_sparse_classes_30k_train_006136 | Implement the Python class `WizardStepNewExamStep2` described below.
Class description:
Implement the WizardStepNewExamStep2 class.
Method signatures and docstrings:
- def get_content(self, request, wz_user_step, data, **kwargs): Args: request: the current request wz_user_step: current wz_user_step model data: all da... | Implement the Python class `WizardStepNewExamStep2` described below.
Class description:
Implement the WizardStepNewExamStep2 class.
Method signatures and docstrings:
- def get_content(self, request, wz_user_step, data, **kwargs): Args: request: the current request wz_user_step: current wz_user_step model data: all da... | 7c76474ad41769804965a11550501321d7b1889b | <|skeleton|>
class WizardStepNewExamStep2:
def get_content(self, request, wz_user_step, data, **kwargs):
"""Args: request: the current request wz_user_step: current wz_user_step model data: all data gathered step after step **kwargs: other arguments (company and uuid amongst others) Returns: Object that sh... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WizardStepNewExamStep2:
def get_content(self, request, wz_user_step, data, **kwargs):
"""Args: request: the current request wz_user_step: current wz_user_step model data: all data gathered step after step **kwargs: other arguments (company and uuid amongst others) Returns: Object that should be return... | the_stack_v2_python_sparse | wizard/views/json/step/new_exam/step_2.py | olivierpons/evalr | train | 0 | |
e86d931933aee7d90c7745d2d0d90c8952bdb3d7 | [
"coords, instructs = parse(filename)\nmax_x = 0\nmax_y = 0\nfor x, y in coords:\n max_x = max(x, max_x)\n max_y = max(y, max_y)\nif max_x == 1305:\n max_x = 1310\nif max_y == 893:\n max_y = 894\ngrid = np.zeros((max_y + 1, max_x + 1), dtype=int)\nfor x, y in coords:\n grid[y][x] = 1\nfor var, amt in ... | <|body_start_0|>
coords, instructs = parse(filename)
max_x = 0
max_y = 0
for x, y in coords:
max_x = max(x, max_x)
max_y = max(y, max_y)
if max_x == 1305:
max_x = 1310
if max_y == 893:
max_y = 894
grid = np.zeros((ma... | AoC 2021 Day 13 | Day13 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Day13:
"""AoC 2021 Day 13"""
def part1(filename: str) -> int:
"""Given a filename, solve 2021 day 13 part 1"""
<|body_0|>
def part2(filename: str) -> int:
"""Given a filename, solve 2021 day 13 part 2"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_002604 | 2,946 | no_license | [
{
"docstring": "Given a filename, solve 2021 day 13 part 1",
"name": "part1",
"signature": "def part1(filename: str) -> int"
},
{
"docstring": "Given a filename, solve 2021 day 13 part 2",
"name": "part2",
"signature": "def part2(filename: str) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_038104 | Implement the Python class `Day13` described below.
Class description:
AoC 2021 Day 13
Method signatures and docstrings:
- def part1(filename: str) -> int: Given a filename, solve 2021 day 13 part 1
- def part2(filename: str) -> int: Given a filename, solve 2021 day 13 part 2 | Implement the Python class `Day13` described below.
Class description:
AoC 2021 Day 13
Method signatures and docstrings:
- def part1(filename: str) -> int: Given a filename, solve 2021 day 13 part 1
- def part2(filename: str) -> int: Given a filename, solve 2021 day 13 part 2
<|skeleton|>
class Day13:
"""AoC 202... | e89db235837d2d05848210a18c9c2a4456085570 | <|skeleton|>
class Day13:
"""AoC 2021 Day 13"""
def part1(filename: str) -> int:
"""Given a filename, solve 2021 day 13 part 1"""
<|body_0|>
def part2(filename: str) -> int:
"""Given a filename, solve 2021 day 13 part 2"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Day13:
"""AoC 2021 Day 13"""
def part1(filename: str) -> int:
"""Given a filename, solve 2021 day 13 part 1"""
coords, instructs = parse(filename)
max_x = 0
max_y = 0
for x, y in coords:
max_x = max(x, max_x)
max_y = max(y, max_y)
if... | the_stack_v2_python_sparse | 2021/python2021/aoc/day13.py | mreishus/aoc | train | 16 |
d7444fac16ab4819ab6d3b09d864b1318cb022b5 | [
"last_page_number_css = '#paginacao > ul > li:nth-child(7) > button::attr(value)'\nlast_page_number = int(response.css(last_page_number_css).extract_first())\nfor page_number in range(1, last_page_number + 1):\n yield Request(f'https://gravatai.atende.net/?pg=diariooficial&pagina={page_number}', callback=self.pa... | <|body_start_0|>
last_page_number_css = '#paginacao > ul > li:nth-child(7) > button::attr(value)'
last_page_number = int(response.css(last_page_number_css).extract_first())
for page_number in range(1, last_page_number + 1):
yield Request(f'https://gravatai.atende.net/?pg=diariooficia... | RsGravataiSpider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RsGravataiSpider:
def parse(self, response):
"""@url https://gravatai.atende.net/?pg=diariooficial @returns requests 1"""
<|body_0|>
def parse_gazette(self, response):
"""@url https://gravatai.atende.net/?pg=diariooficial&pagina=1 @returns items 1 @scrapes date file_... | stack_v2_sparse_classes_75kplus_train_002605 | 1,976 | permissive | [
{
"docstring": "@url https://gravatai.atende.net/?pg=diariooficial @returns requests 1",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "@url https://gravatai.atende.net/?pg=diariooficial&pagina=1 @returns items 1 @scrapes date file_urls is_extra_edition power",
... | 2 | stack_v2_sparse_classes_30k_train_008922 | Implement the Python class `RsGravataiSpider` described below.
Class description:
Implement the RsGravataiSpider class.
Method signatures and docstrings:
- def parse(self, response): @url https://gravatai.atende.net/?pg=diariooficial @returns requests 1
- def parse_gazette(self, response): @url https://gravatai.atend... | Implement the Python class `RsGravataiSpider` described below.
Class description:
Implement the RsGravataiSpider class.
Method signatures and docstrings:
- def parse(self, response): @url https://gravatai.atende.net/?pg=diariooficial @returns requests 1
- def parse_gazette(self, response): @url https://gravatai.atend... | 548a9b1b2718dc78ba8ccb06b36cf337543ad71d | <|skeleton|>
class RsGravataiSpider:
def parse(self, response):
"""@url https://gravatai.atende.net/?pg=diariooficial @returns requests 1"""
<|body_0|>
def parse_gazette(self, response):
"""@url https://gravatai.atende.net/?pg=diariooficial&pagina=1 @returns items 1 @scrapes date file_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RsGravataiSpider:
def parse(self, response):
"""@url https://gravatai.atende.net/?pg=diariooficial @returns requests 1"""
last_page_number_css = '#paginacao > ul > li:nth-child(7) > button::attr(value)'
last_page_number = int(response.css(last_page_number_css).extract_first())
... | the_stack_v2_python_sparse | data_collection/gazette/spiders/rs_gravatai.py | okfn-brasil/querido-diario | train | 402 | |
508379a6da7d28af15ed0f1d661a0c6490d125e9 | [
"if table == self.USERTABLE:\n query = sql.SQL('SELECT {fields} from {table} where {pkey} = %s;').format(fields=sql.SQL(',').join([sql.Identifier('uid'), sql.Identifier('email'), sql.Identifier('display_name'), sql.Identifier('type'), sql.Identifier('roleid'), sql.Identifier('roleissuer')]), table=sql.Identifier... | <|body_start_0|>
if table == self.USERTABLE:
query = sql.SQL('SELECT {fields} from {table} where {pkey} = %s;').format(fields=sql.SQL(',').join([sql.Identifier('uid'), sql.Identifier('email'), sql.Identifier('display_name'), sql.Identifier('type'), sql.Identifier('roleid'), sql.Identifier('roleissue... | AuditDAO | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuditDAO:
def getTableValueByIntID(self, table, pkeyname, pkeyval, cursor):
"""Get all values on a given table with a given primary key. TO BE USED INTERNALLY ONLY. :param table: string representing the table name. :param pkeyname: string identifying the primary key's column name. :param... | stack_v2_sparse_classes_75kplus_train_002606 | 4,281 | no_license | [
{
"docstring": "Get all values on a given table with a given primary key. TO BE USED INTERNALLY ONLY. :param table: string representing the table name. :param pkeyname: string identifying the primary key's column name. :param pkeyval: representing the primary key's value. :param cursor: psycopg2 connection curs... | 3 | stack_v2_sparse_classes_30k_train_007401 | Implement the Python class `AuditDAO` described below.
Class description:
Implement the AuditDAO class.
Method signatures and docstrings:
- def getTableValueByIntID(self, table, pkeyname, pkeyval, cursor): Get all values on a given table with a given primary key. TO BE USED INTERNALLY ONLY. :param table: string repre... | Implement the Python class `AuditDAO` described below.
Class description:
Implement the AuditDAO class.
Method signatures and docstrings:
- def getTableValueByIntID(self, table, pkeyname, pkeyval, cursor): Get all values on a given table with a given primary key. TO BE USED INTERNALLY ONLY. :param table: string repre... | 24e1e25d2e512105c9bf70b5e33b1afed4790f71 | <|skeleton|>
class AuditDAO:
def getTableValueByIntID(self, table, pkeyname, pkeyval, cursor):
"""Get all values on a given table with a given primary key. TO BE USED INTERNALLY ONLY. :param table: string representing the table name. :param pkeyname: string identifying the primary key's column name. :param... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AuditDAO:
def getTableValueByIntID(self, table, pkeyname, pkeyval, cursor):
"""Get all values on a given table with a given primary key. TO BE USED INTERNALLY ONLY. :param table: string representing the table name. :param pkeyname: string identifying the primary key's column name. :param pkeyval: repr... | the_stack_v2_python_sparse | flask/app/DAOs/AuditDAO.py | InTheNou/InTheNou-Backend | train | 0 | |
ec6e67f09287a8f413d4729384291976730e0711 | [
"self.nodes = nodes\nself.p = Polynomial(roots=self.nodes)\nself.dp = self.p.derive()\nself.ddp = self.dp.derive()\nself.dpi = self.dp(self.nodes)\nself.ddpi = self.ddp(self.nodes)\nself.basis = numpy.array([LagrangeBasisDenominator(nd, dpi) for nd, dpi in zip(self.nodes, self.dpi)], dtype=LagrangeBasisDenominator)... | <|body_start_0|>
self.nodes = nodes
self.p = Polynomial(roots=self.nodes)
self.dp = self.p.derive()
self.ddp = self.dp.derive()
self.dpi = self.dp(self.nodes)
self.ddpi = self.ddp(self.nodes)
self.basis = numpy.array([LagrangeBasisDenominator(nd, dpi) for nd, dpi ... | LagrangeBasis | LagrangeBasis | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LagrangeBasis:
"""LagrangeBasis"""
def __init__(self, nodes):
"""__init__ Args: nodes: Returns:"""
<|body_0|>
def __call__(self, x):
"""__call__ Args: x: Returns:"""
<|body_1|>
def _call_single(self, x):
"""__call_single Args: x: Returns:"""
... | stack_v2_sparse_classes_75kplus_train_002607 | 4,088 | permissive | [
{
"docstring": "__init__ Args: nodes: Returns:",
"name": "__init__",
"signature": "def __init__(self, nodes)"
},
{
"docstring": "__call__ Args: x: Returns:",
"name": "__call__",
"signature": "def __call__(self, x)"
},
{
"docstring": "__call_single Args: x: Returns:",
"name": ... | 5 | stack_v2_sparse_classes_30k_train_041941 | Implement the Python class `LagrangeBasis` described below.
Class description:
LagrangeBasis
Method signatures and docstrings:
- def __init__(self, nodes): __init__ Args: nodes: Returns:
- def __call__(self, x): __call__ Args: x: Returns:
- def _call_single(self, x): __call_single Args: x: Returns:
- def derivative(s... | Implement the Python class `LagrangeBasis` described below.
Class description:
LagrangeBasis
Method signatures and docstrings:
- def __init__(self, nodes): __init__ Args: nodes: Returns:
- def __call__(self, x): __call__ Args: x: Returns:
- def _call_single(self, x): __call_single Args: x: Returns:
- def derivative(s... | d25e6c1bc609022189952d97488828113cfb2206 | <|skeleton|>
class LagrangeBasis:
"""LagrangeBasis"""
def __init__(self, nodes):
"""__init__ Args: nodes: Returns:"""
<|body_0|>
def __call__(self, x):
"""__call__ Args: x: Returns:"""
<|body_1|>
def _call_single(self, x):
"""__call_single Args: x: Returns:"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LagrangeBasis:
"""LagrangeBasis"""
def __init__(self, nodes):
"""__init__ Args: nodes: Returns:"""
self.nodes = nodes
self.p = Polynomial(roots=self.nodes)
self.dp = self.p.derive()
self.ddp = self.dp.derive()
self.dpi = self.dp(self.nodes)
self.ddp... | the_stack_v2_python_sparse | utils/poly/LagrangeBasis.py | zhucer2003/SEM-Toolbox | train | 0 |
83636e39e85066aef2c3a96a0cb3c4a8fbfa4e1a | [
"super(ACF, self).__init__()\nself.sr = sr\nself.numframes = lambda sig: numframes(sig, wind, hop, center=True)\nself.laglen = len(wind)\n\ndef __stacf(sig):\n \"\"\"Proceed ACF with LPC.\"\"\"\n frames = stana(sig, wind, hop, center=True)\n if not lpc_order:\n return np.asarray([xcorr(f, norm=True)... | <|body_start_0|>
super(ACF, self).__init__()
self.sr = sr
self.numframes = lambda sig: numframes(sig, wind, hop, center=True)
self.laglen = len(wind)
def __stacf(sig):
"""Proceed ACF with LPC."""
frames = stana(sig, wind, hop, center=True)
if ... | Pitch detection using the autocorrelation function. | ACF | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ACF:
"""Pitch detection using the autocorrelation function."""
def __init__(self, sr, wind, hop, lpc_order=0):
"""Instantiate a ACF pitch tracker. Parameters ---------- sr: int Sampling rate. wind: array_like Window function. hop: float/int Hop fraction or samples See Also -------- s... | stack_v2_sparse_classes_75kplus_train_002608 | 17,835 | permissive | [
{
"docstring": "Instantiate a ACF pitch tracker. Parameters ---------- sr: int Sampling rate. wind: array_like Window function. hop: float/int Hop fraction or samples See Also -------- sig.fbanks, sig.stproc, sig.window",
"name": "__init__",
"signature": "def __init__(self, sr, wind, hop, lpc_order=0)"
... | 2 | stack_v2_sparse_classes_30k_train_018417 | Implement the Python class `ACF` described below.
Class description:
Pitch detection using the autocorrelation function.
Method signatures and docstrings:
- def __init__(self, sr, wind, hop, lpc_order=0): Instantiate a ACF pitch tracker. Parameters ---------- sr: int Sampling rate. wind: array_like Window function. h... | Implement the Python class `ACF` described below.
Class description:
Pitch detection using the autocorrelation function.
Method signatures and docstrings:
- def __init__(self, sr, wind, hop, lpc_order=0): Instantiate a ACF pitch tracker. Parameters ---------- sr: int Sampling rate. wind: array_like Window function. h... | 740139490208ca7605e9b520f1a28214fa3903dc | <|skeleton|>
class ACF:
"""Pitch detection using the autocorrelation function."""
def __init__(self, sr, wind, hop, lpc_order=0):
"""Instantiate a ACF pitch tracker. Parameters ---------- sr: int Sampling rate. wind: array_like Window function. hop: float/int Hop fraction or samples See Also -------- s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ACF:
"""Pitch detection using the autocorrelation function."""
def __init__(self, sr, wind, hop, lpc_order=0):
"""Instantiate a ACF pitch tracker. Parameters ---------- sr: int Sampling rate. wind: array_like Window function. hop: float/int Hop fraction or samples See Also -------- sig.fbanks, si... | the_stack_v2_python_sparse | audlib/pitch.py | templeblock/pyaudlib | train | 0 |
1c0ebcdc1e44afd7bca20556666517778b63c8e8 | [
"super(InstanceGraph, self).__init__(outputDir)\nself.filesPerInstance = dict()\nself.printClusterInstances = True",
"self.vertices[app.uid()] = 'app'\ninst = self.instances.get(app.desktopid) or []\ninst.append(app.uid())\nself.instances[app.desktopid] = inst\nself.vertices[app.desktopid] = 'appstate'\nself.edge... | <|body_start_0|>
super(InstanceGraph, self).__init__(outputDir)
self.filesPerInstance = dict()
self.printClusterInstances = True
<|end_body_0|>
<|body_start_1|>
self.vertices[app.uid()] = 'app'
inst = self.instances.get(app.desktopid) or []
inst.append(app.uid())
... | A graph modelling communities where instances are disjoint. | InstanceGraph | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstanceGraph:
"""A graph modelling communities where instances are disjoint."""
def __init__(self, outputDir: str=None):
"""Construct an ActivityGraph."""
<|body_0|>
def _addAppNode(self, app: Application):
"""Add an Application vertex to the graph."""
<... | stack_v2_sparse_classes_75kplus_train_002609 | 34,990 | no_license | [
{
"docstring": "Construct an ActivityGraph.",
"name": "__init__",
"signature": "def __init__(self, outputDir: str=None)"
},
{
"docstring": "Add an Application vertex to the graph.",
"name": "_addAppNode",
"signature": "def _addAppNode(self, app: Application)"
},
{
"docstring": "A... | 4 | stack_v2_sparse_classes_30k_train_004885 | Implement the Python class `InstanceGraph` described below.
Class description:
A graph modelling communities where instances are disjoint.
Method signatures and docstrings:
- def __init__(self, outputDir: str=None): Construct an ActivityGraph.
- def _addAppNode(self, app: Application): Add an Application vertex to th... | Implement the Python class `InstanceGraph` described below.
Class description:
A graph modelling communities where instances are disjoint.
Method signatures and docstrings:
- def __init__(self, outputDir: str=None): Construct an ActivityGraph.
- def _addAppNode(self, app: Application): Add an Application vertex to th... | 757c9644bceb941a4d4d2e9719d0a9da0d069c5f | <|skeleton|>
class InstanceGraph:
"""A graph modelling communities where instances are disjoint."""
def __init__(self, outputDir: str=None):
"""Construct an ActivityGraph."""
<|body_0|>
def _addAppNode(self, app: Application):
"""Add an Application vertex to the graph."""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InstanceGraph:
"""A graph modelling communities where instances are disjoint."""
def __init__(self, outputDir: str=None):
"""Construct an ActivityGraph."""
super(InstanceGraph, self).__init__(outputDir)
self.filesPerInstance = dict()
self.printClusterInstances = True
... | the_stack_v2_python_sparse | GraphEngine.py | Sidnioulz/PolicyAnalysis | train | 0 |
acdb5b1748fb3610f90917bfe27b057767a97e5b | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn OpenShift()",
"from .change_tracked_entity import ChangeTrackedEntity\nfrom .open_shift_item import OpenShiftItem\nfrom .change_tracked_entity import ChangeTrackedEntity\nfrom .open_shift_item import OpenShiftItem\nfields: Dict[str, Ca... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return OpenShift()
<|end_body_0|>
<|body_start_1|>
from .change_tracked_entity import ChangeTrackedEntity
from .open_shift_item import OpenShiftItem
from .change_tracked_entity import C... | OpenShift | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenShift:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OpenShift:
"""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: OpenSh... | stack_v2_sparse_classes_75kplus_train_002610 | 2,856 | 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: OpenShift",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(par... | 3 | stack_v2_sparse_classes_30k_train_027197 | Implement the Python class `OpenShift` described below.
Class description:
Implement the OpenShift class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OpenShift: Creates a new instance of the appropriate class based on discriminator value Args: parse... | Implement the Python class `OpenShift` described below.
Class description:
Implement the OpenShift class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OpenShift: Creates a new instance of the appropriate class based on discriminator value Args: parse... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class OpenShift:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OpenShift:
"""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: OpenSh... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OpenShift:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OpenShift:
"""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: OpenShift"""
... | the_stack_v2_python_sparse | msgraph/generated/models/open_shift.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
8aeb3e04e6adda4f3bba79ed50a83b3718ead9f6 | [
"self.threshold = threshold\nself.controller = controller\nself._previous_input = None\nself.previous_input = None\nself.input_valid = True",
"self.previous_input = self._previous_input\njoycon_input = self.normalize_joystick(controller)\nparsed_input = []\nif 0 not in joycon_input:\n if self._previous_input i... | <|body_start_0|>
self.threshold = threshold
self.controller = controller
self._previous_input = None
self.previous_input = None
self.input_valid = True
<|end_body_0|>
<|body_start_1|>
self.previous_input = self._previous_input
joycon_input = self.normalize_joysti... | ControllerManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ControllerManager:
def __init__(self, controller, threshold):
"""Creates a controller manager which can map controller inputs to keyboard inputs."""
<|body_0|>
def parse_input(self, controller):
"""Takes a given input from a contoller, normalizes, and returns the par... | stack_v2_sparse_classes_75kplus_train_002611 | 5,048 | no_license | [
{
"docstring": "Creates a controller manager which can map controller inputs to keyboard inputs.",
"name": "__init__",
"signature": "def __init__(self, controller, threshold)"
},
{
"docstring": "Takes a given input from a contoller, normalizes, and returns the parsed data",
"name": "parse_in... | 6 | stack_v2_sparse_classes_30k_train_029311 | Implement the Python class `ControllerManager` described below.
Class description:
Implement the ControllerManager class.
Method signatures and docstrings:
- def __init__(self, controller, threshold): Creates a controller manager which can map controller inputs to keyboard inputs.
- def parse_input(self, controller):... | Implement the Python class `ControllerManager` described below.
Class description:
Implement the ControllerManager class.
Method signatures and docstrings:
- def __init__(self, controller, threshold): Creates a controller manager which can map controller inputs to keyboard inputs.
- def parse_input(self, controller):... | 6718fdb6555d87f0b7b331c10d64a604431f8e81 | <|skeleton|>
class ControllerManager:
def __init__(self, controller, threshold):
"""Creates a controller manager which can map controller inputs to keyboard inputs."""
<|body_0|>
def parse_input(self, controller):
"""Takes a given input from a contoller, normalizes, and returns the par... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ControllerManager:
def __init__(self, controller, threshold):
"""Creates a controller manager which can map controller inputs to keyboard inputs."""
self.threshold = threshold
self.controller = controller
self._previous_input = None
self.previous_input = None
se... | the_stack_v2_python_sparse | pokered/modules/utils/managers/controller_manager.py | surranc20/pokered | train | 44 | |
792244baeaa9e7bccfc5bf7e7dde918344244f09 | [
"easy = set()\nfor i in nums:\n easy.add(i)\nfor i in xrange(len(nums)):\n if i not in easy:\n return i\nreturn len(nums)",
"missing = len(nums)\nfor i, num in enumerate(nums):\n missing ^= i ^ num\nreturn missing"
] | <|body_start_0|>
easy = set()
for i in nums:
easy.add(i)
for i in xrange(len(nums)):
if i not in easy:
return i
return len(nums)
<|end_body_0|>
<|body_start_1|>
missing = len(nums)
for i, num in enumerate(nums):
missing... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def missingNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def missingNumberConstantMemory(self, nums):
"""if we initialize an integer to nn and XOR it with every index and value, we will be left with the missing number. :type nums: L... | stack_v2_sparse_classes_75kplus_train_002612 | 881 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "missingNumber",
"signature": "def missingNumber(self, nums)"
},
{
"docstring": "if we initialize an integer to nn and XOR it with every index and value, we will be left with the missing number. :type nums: List[int] :rtype: int",
"... | 2 | stack_v2_sparse_classes_30k_train_016991 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def missingNumber(self, nums): :type nums: List[int] :rtype: int
- def missingNumberConstantMemory(self, nums): if we initialize an integer to nn and XOR it with every index and ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def missingNumber(self, nums): :type nums: List[int] :rtype: int
- def missingNumberConstantMemory(self, nums): if we initialize an integer to nn and XOR it with every index and ... | 2f7df25d0d735f726b7012e4aa2417dee50526d9 | <|skeleton|>
class Solution:
def missingNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def missingNumberConstantMemory(self, nums):
"""if we initialize an integer to nn and XOR it with every index and value, we will be left with the missing number. :type nums: L... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def missingNumber(self, nums):
""":type nums: List[int] :rtype: int"""
easy = set()
for i in nums:
easy.add(i)
for i in xrange(len(nums)):
if i not in easy:
return i
return len(nums)
def missingNumberConstantMemory(... | the_stack_v2_python_sparse | leetcode/arrays/missing_number.py | marquesarthur/programming_problems | train | 2 | |
dc7a2eac21a7357ea54adb3d522bcc08060e6879 | [
"pattern = self.content\nmatch = re.search(pattern, ctx.content, flags=re.IGNORECASE)\nif match:\n ctx.matches.append(match[0])\n return True\nreturn False",
"try:\n re.compile(content)\nexcept re.error as e:\n raise BadArgument(str(e))\nreturn (content, description)"
] | <|body_start_0|>
pattern = self.content
match = re.search(pattern, ctx.content, flags=re.IGNORECASE)
if match:
ctx.matches.append(match[0])
return True
return False
<|end_body_0|>
<|body_start_1|>
try:
re.compile(content)
except re.err... | A filter which looks for a specific token given by regex. | TokenFilter | [
"MIT",
"BSD-3-Clause",
"Python-2.0",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TokenFilter:
"""A filter which looks for a specific token given by regex."""
async def triggered_on(self, ctx: FilterContext) -> bool:
"""Searches for a regex pattern within a given context."""
<|body_0|>
async def process_input(cls, content: str, description: str) -> tu... | stack_v2_sparse_classes_75kplus_train_002613 | 1,062 | permissive | [
{
"docstring": "Searches for a regex pattern within a given context.",
"name": "triggered_on",
"signature": "async def triggered_on(self, ctx: FilterContext) -> bool"
},
{
"docstring": "Process the content and description into a form which will work with the filtering. A BadArgument should be ra... | 2 | null | Implement the Python class `TokenFilter` described below.
Class description:
A filter which looks for a specific token given by regex.
Method signatures and docstrings:
- async def triggered_on(self, ctx: FilterContext) -> bool: Searches for a regex pattern within a given context.
- async def process_input(cls, conte... | Implement the Python class `TokenFilter` described below.
Class description:
A filter which looks for a specific token given by regex.
Method signatures and docstrings:
- async def triggered_on(self, ctx: FilterContext) -> bool: Searches for a regex pattern within a given context.
- async def process_input(cls, conte... | f2048684291cc6358565e96ef3562512fbeb2505 | <|skeleton|>
class TokenFilter:
"""A filter which looks for a specific token given by regex."""
async def triggered_on(self, ctx: FilterContext) -> bool:
"""Searches for a regex pattern within a given context."""
<|body_0|>
async def process_input(cls, content: str, description: str) -> tu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TokenFilter:
"""A filter which looks for a specific token given by regex."""
async def triggered_on(self, ctx: FilterContext) -> bool:
"""Searches for a regex pattern within a given context."""
pattern = self.content
match = re.search(pattern, ctx.content, flags=re.IGNORECASE)
... | the_stack_v2_python_sparse | bot/exts/filtering/_filters/token.py | python-discord/bot | train | 1,479 |
af658ec897b63d798e34763250d7a8f7f514771e | [
"sparql_results = self.query('\\n SELECT distinct ?site ?label ?inst ?city (count(distinct ?part) as ?partcount)\\n WHERE {\\n ?site rdf:type austalk:RecordingSite .\\n ?site austalk:institution ?inst .\\n ?site austalk:city ?city .\\n ... | <|body_start_0|>
sparql_results = self.query('\n SELECT distinct ?site ?label ?inst ?city (count(distinct ?part) as ?partcount)\n WHERE {\n ?site rdf:type austalk:RecordingSite .\n ?site austalk:institution ?inst .\n ?site austalk:city ?city .... | Class responsible for returning instances of type Site. | SiteManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SiteManager:
"""Class responsible for returning instances of type Site."""
def all(self):
"""Returns all the recording locations stored in the rdf store. The endpoint and the return format are set by the sparql parameter. The function Returns objects of type site."""
<|body_0... | stack_v2_sparse_classes_75kplus_train_002614 | 5,470 | no_license | [
{
"docstring": "Returns all the recording locations stored in the rdf store. The endpoint and the return format are set by the sparql parameter. The function Returns objects of type site.",
"name": "all",
"signature": "def all(self)"
},
{
"docstring": "Returns a list containing a dictionary of t... | 3 | stack_v2_sparse_classes_30k_train_037319 | Implement the Python class `SiteManager` described below.
Class description:
Class responsible for returning instances of type Site.
Method signatures and docstrings:
- def all(self): Returns all the recording locations stored in the rdf store. The endpoint and the return format are set by the sparql parameter. The f... | Implement the Python class `SiteManager` described below.
Class description:
Class responsible for returning instances of type Site.
Method signatures and docstrings:
- def all(self): Returns all the recording locations stored in the rdf store. The endpoint and the return format are set by the sparql parameter. The f... | 88000a79f0a18c92de0092814de3dbb2409f5515 | <|skeleton|>
class SiteManager:
"""Class responsible for returning instances of type Site."""
def all(self):
"""Returns all the recording locations stored in the rdf store. The endpoint and the return format are set by the sparql parameter. The function Returns objects of type site."""
<|body_0... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SiteManager:
"""Class responsible for returning instances of type Site."""
def all(self):
"""Returns all the recording locations stored in the rdf store. The endpoint and the return format are set by the sparql parameter. The function Returns objects of type site."""
sparql_results = self... | the_stack_v2_python_sparse | browse/modelspackage/sites.py | Alveo/smallasc | train | 0 |
45a05e88726ce5825532888dcfa09a0f0038e6f2 | [
"rval = []\nfor role in trans.sa_session.query(trans.app.model.Role).filter(trans.app.model.Role.table.c.deleted == false()):\n if trans.user_is_admin or trans.app.security_agent.ok_to_display(trans.user, role):\n item = role.to_dict(value_mapper={'id': trans.security.encode_id})\n encoded_id = tra... | <|body_start_0|>
rval = []
for role in trans.sa_session.query(trans.app.model.Role).filter(trans.app.model.Role.table.c.deleted == false()):
if trans.user_is_admin or trans.app.security_agent.ok_to_display(trans.user, role):
item = role.to_dict(value_mapper={'id': trans.secur... | RoleAPIController | [
"CC-BY-2.5",
"AFL-2.1",
"AFL-3.0",
"CC-BY-3.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoleAPIController:
def index(self, trans, **kwd):
"""GET /api/roles Displays a collection (list) of roles."""
<|body_0|>
def show(self, trans, id, **kwd):
"""GET /api/roles/{encoded_role_id} Displays information about a role."""
<|body_1|>
def create(sel... | stack_v2_sparse_classes_75kplus_train_002615 | 3,686 | permissive | [
{
"docstring": "GET /api/roles Displays a collection (list) of roles.",
"name": "index",
"signature": "def index(self, trans, **kwd)"
},
{
"docstring": "GET /api/roles/{encoded_role_id} Displays information about a role.",
"name": "show",
"signature": "def show(self, trans, id, **kwd)"
... | 3 | stack_v2_sparse_classes_30k_train_007755 | Implement the Python class `RoleAPIController` described below.
Class description:
Implement the RoleAPIController class.
Method signatures and docstrings:
- def index(self, trans, **kwd): GET /api/roles Displays a collection (list) of roles.
- def show(self, trans, id, **kwd): GET /api/roles/{encoded_role_id} Displa... | Implement the Python class `RoleAPIController` described below.
Class description:
Implement the RoleAPIController class.
Method signatures and docstrings:
- def index(self, trans, **kwd): GET /api/roles Displays a collection (list) of roles.
- def show(self, trans, id, **kwd): GET /api/roles/{encoded_role_id} Displa... | d194520fdfe08e48c0b3d0d2299cd2adcb8f5952 | <|skeleton|>
class RoleAPIController:
def index(self, trans, **kwd):
"""GET /api/roles Displays a collection (list) of roles."""
<|body_0|>
def show(self, trans, id, **kwd):
"""GET /api/roles/{encoded_role_id} Displays information about a role."""
<|body_1|>
def create(sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RoleAPIController:
def index(self, trans, **kwd):
"""GET /api/roles Displays a collection (list) of roles."""
rval = []
for role in trans.sa_session.query(trans.app.model.Role).filter(trans.app.model.Role.table.c.deleted == false()):
if trans.user_is_admin or trans.app.secu... | the_stack_v2_python_sparse | lib/galaxy/webapps/galaxy/api/roles.py | bwlang/galaxy | train | 0 | |
15c87d4742a17bab9f19927567f9cab6a21d1a45 | [
"header = {'typ': 'JWT', 'alg': 'HS256'}\nheader = json.dumps(header, separators=(',', ':')).encode('utf-8')\nheader = base64.urlsafe_b64encode(header).replace(b'=', b'')\np = json.dumps(data, separators=(',', ':')).encode('utf-8')\np = base64.urlsafe_b64encode(p).replace(b'=', b'')\nsecret_key = properties.get('se... | <|body_start_0|>
header = {'typ': 'JWT', 'alg': 'HS256'}
header = json.dumps(header, separators=(',', ':')).encode('utf-8')
header = base64.urlsafe_b64encode(header).replace(b'=', b'')
p = json.dumps(data, separators=(',', ':')).encode('utf-8')
p = base64.urlsafe_b64encode(p).rep... | JWT | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JWT:
def encode(data):
"""JWT签名 :param data: :return:"""
<|body_0|>
def verify(access_token):
"""JWT验签 :param access_token: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
header = {'typ': 'JWT', 'alg': 'HS256'}
header = json.dumps(... | stack_v2_sparse_classes_75kplus_train_002616 | 2,016 | no_license | [
{
"docstring": "JWT签名 :param data: :return:",
"name": "encode",
"signature": "def encode(data)"
},
{
"docstring": "JWT验签 :param access_token: :return:",
"name": "verify",
"signature": "def verify(access_token)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003872 | Implement the Python class `JWT` described below.
Class description:
Implement the JWT class.
Method signatures and docstrings:
- def encode(data): JWT签名 :param data: :return:
- def verify(access_token): JWT验签 :param access_token: :return: | Implement the Python class `JWT` described below.
Class description:
Implement the JWT class.
Method signatures and docstrings:
- def encode(data): JWT签名 :param data: :return:
- def verify(access_token): JWT验签 :param access_token: :return:
<|skeleton|>
class JWT:
def encode(data):
"""JWT签名 :param data: ... | 6156ba7e3b87552b80fe20b886fa476d8fc4a277 | <|skeleton|>
class JWT:
def encode(data):
"""JWT签名 :param data: :return:"""
<|body_0|>
def verify(access_token):
"""JWT验签 :param access_token: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JWT:
def encode(data):
"""JWT签名 :param data: :return:"""
header = {'typ': 'JWT', 'alg': 'HS256'}
header = json.dumps(header, separators=(',', ':')).encode('utf-8')
header = base64.urlsafe_b64encode(header).replace(b'=', b'')
p = json.dumps(data, separators=(',', ':')).e... | the_stack_v2_python_sparse | tools/jwt.py | Duo-Shou-Store/DSSP | train | 0 | |
796586866a0924c6e2aae0f964067f7e2af7c499 | [
"kwargs = {}\nkwargs['status'] = 1\ntday = datetime.utcnow().replace(tzinfo=utc)\nkwargs['startingdate__lte'] = datetime(tday.year, tday.month, tday.day, tday.hour, tday.minute, tday.second, tday.microsecond).replace(tzinfo=utc)\nkwargs['expirationdate__gte'] = datetime(tday.year, tday.month, tday.day, tday.hour, t... | <|body_start_0|>
kwargs = {}
kwargs['status'] = 1
tday = datetime.utcnow().replace(tzinfo=utc)
kwargs['startingdate__lte'] = datetime(tday.year, tday.month, tday.day, tday.hour, tday.minute, tday.second, tday.microsecond).replace(tzinfo=utc)
kwargs['expirationdate__gte'] = dateti... | Campaign Manager | CampaignManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CampaignManager:
"""Campaign Manager"""
def get_running_campaign(self):
"""Return all the active campaigns which will be running based on the expiry date, the daily start/stop time and days of the week"""
<|body_0|>
def get_expired_campaign(self):
"""Return all t... | stack_v2_sparse_classes_75kplus_train_002617 | 27,513 | no_license | [
{
"docstring": "Return all the active campaigns which will be running based on the expiry date, the daily start/stop time and days of the week",
"name": "get_running_campaign",
"signature": "def get_running_campaign(self)"
},
{
"docstring": "Return all the campaigns which are expired or going to... | 2 | stack_v2_sparse_classes_30k_train_022532 | Implement the Python class `CampaignManager` described below.
Class description:
Campaign Manager
Method signatures and docstrings:
- def get_running_campaign(self): Return all the active campaigns which will be running based on the expiry date, the daily start/stop time and days of the week
- def get_expired_campaig... | Implement the Python class `CampaignManager` described below.
Class description:
Campaign Manager
Method signatures and docstrings:
- def get_running_campaign(self): Return all the active campaigns which will be running based on the expiry date, the daily start/stop time and days of the week
- def get_expired_campaig... | 2923a7d974f362af91b7c7c8f2e208cb2353c921 | <|skeleton|>
class CampaignManager:
"""Campaign Manager"""
def get_running_campaign(self):
"""Return all the active campaigns which will be running based on the expiry date, the daily start/stop time and days of the week"""
<|body_0|>
def get_expired_campaign(self):
"""Return all t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CampaignManager:
"""Campaign Manager"""
def get_running_campaign(self):
"""Return all the active campaigns which will be running based on the expiry date, the daily start/stop time and days of the week"""
kwargs = {}
kwargs['status'] = 1
tday = datetime.utcnow().replace(tz... | the_stack_v2_python_sparse | dialer_campaign/models.py | goksie/TheFies | train | 0 |
6d00027bc2ce07503efbf6d0a034558688368a13 | [
"key = tokey(source.key, geometry_string, serialize(options))\nfilename, _ext = os.path.splitext(os.path.basename(source.name))\npath = '%s/%s' % (key, filename)\nreturn '%s%s.%s' % (settings.THUMBNAIL_PREFIX, path, EXTENSIONS[options['format']])",
"source_image = source_image.convert('RGB')\nlogger.debug('Creati... | <|body_start_0|>
key = tokey(source.key, geometry_string, serialize(options))
filename, _ext = os.path.splitext(os.path.basename(source.name))
path = '%s/%s' % (key, filename)
return '%s%s.%s' % (settings.THUMBNAIL_PREFIX, path, EXTENSIONS[options['format']])
<|end_body_0|>
<|body_start... | SEOThumbnailBackend | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SEOThumbnailBackend:
def _get_thumbnail_filename(self, source, geometry_string, options):
"""Computes the destination filename."""
<|body_0|>
def _create_thumbnail(self, source_image, geometry_string, options, thumbnail):
"""Creates the thumbnail by using default.eng... | stack_v2_sparse_classes_75kplus_train_002618 | 1,602 | permissive | [
{
"docstring": "Computes the destination filename.",
"name": "_get_thumbnail_filename",
"signature": "def _get_thumbnail_filename(self, source, geometry_string, options)"
},
{
"docstring": "Creates the thumbnail by using default.engine",
"name": "_create_thumbnail",
"signature": "def _cr... | 2 | stack_v2_sparse_classes_30k_train_022162 | Implement the Python class `SEOThumbnailBackend` described below.
Class description:
Implement the SEOThumbnailBackend class.
Method signatures and docstrings:
- def _get_thumbnail_filename(self, source, geometry_string, options): Computes the destination filename.
- def _create_thumbnail(self, source_image, geometry... | Implement the Python class `SEOThumbnailBackend` described below.
Class description:
Implement the SEOThumbnailBackend class.
Method signatures and docstrings:
- def _get_thumbnail_filename(self, source, geometry_string, options): Computes the destination filename.
- def _create_thumbnail(self, source_image, geometry... | e21aa8fa62df96f41ddbea913f386ee7c6780ed0 | <|skeleton|>
class SEOThumbnailBackend:
def _get_thumbnail_filename(self, source, geometry_string, options):
"""Computes the destination filename."""
<|body_0|>
def _create_thumbnail(self, source_image, geometry_string, options, thumbnail):
"""Creates the thumbnail by using default.eng... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SEOThumbnailBackend:
def _get_thumbnail_filename(self, source, geometry_string, options):
"""Computes the destination filename."""
key = tokey(source.key, geometry_string, serialize(options))
filename, _ext = os.path.splitext(os.path.basename(source.name))
path = '%s/%s' % (key... | the_stack_v2_python_sparse | jobsp/thumbnailname.py | MicroPyramid/opensource-job-portal | train | 360 | |
7d2bf70a1736b50409a315ef6f4f601f3d63e250 | [
"super(Matern52, self).__init__(n_dims=n_dims, active_dims=active_dims, name=name)\nlogger.debug('Initializing %s kernel.' % self.name)\nself.variance = np.float64(variance)\nself.lengthscale = np.float64(lengthscale)\nself.parameter_list = ['variance', 'lengthscale']\nself.constraint_map = {'variance': '+ve', 'len... | <|body_start_0|>
super(Matern52, self).__init__(n_dims=n_dims, active_dims=active_dims, name=name)
logger.debug('Initializing %s kernel.' % self.name)
self.variance = np.float64(variance)
self.lengthscale = np.float64(lengthscale)
self.parameter_list = ['variance', 'lengthscale']... | Matern52 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Matern52:
def __init__(self, n_dims, variance=1.0, lengthscale=1.0, active_dims=None, name=None):
"""squared exponential kernel Inputs: n_dims : number of dimensions variance : kernel variance lengthscale : kernel lengthscale active_dims : all dims active by default, subset can be specif... | stack_v2_sparse_classes_75kplus_train_002619 | 9,047 | no_license | [
{
"docstring": "squared exponential kernel Inputs: n_dims : number of dimensions variance : kernel variance lengthscale : kernel lengthscale active_dims : all dims active by default, subset can be specified",
"name": "__init__",
"signature": "def __init__(self, n_dims, variance=1.0, lengthscale=1.0, act... | 2 | stack_v2_sparse_classes_30k_train_054398 | Implement the Python class `Matern52` described below.
Class description:
Implement the Matern52 class.
Method signatures and docstrings:
- def __init__(self, n_dims, variance=1.0, lengthscale=1.0, active_dims=None, name=None): squared exponential kernel Inputs: n_dims : number of dimensions variance : kernel varianc... | Implement the Python class `Matern52` described below.
Class description:
Implement the Matern52 class.
Method signatures and docstrings:
- def __init__(self, n_dims, variance=1.0, lengthscale=1.0, active_dims=None, name=None): squared exponential kernel Inputs: n_dims : number of dimensions variance : kernel varianc... | 1bed882b8a94ee58fd0bde6920ee85f81ffb77bb | <|skeleton|>
class Matern52:
def __init__(self, n_dims, variance=1.0, lengthscale=1.0, active_dims=None, name=None):
"""squared exponential kernel Inputs: n_dims : number of dimensions variance : kernel variance lengthscale : kernel lengthscale active_dims : all dims active by default, subset can be specif... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Matern52:
def __init__(self, n_dims, variance=1.0, lengthscale=1.0, active_dims=None, name=None):
"""squared exponential kernel Inputs: n_dims : number of dimensions variance : kernel variance lengthscale : kernel lengthscale active_dims : all dims active by default, subset can be specified"""
... | the_stack_v2_python_sparse | gp_grief/kern/stationary.py | scwolof/gp_grief | train | 2 | |
f05c5d5258bb504c7b3e825408e25b3ff8b7731a | [
"super(UVto3D, self).__init__()\nself.face_inds = mean_shape['face_inds']\nself.verts_uv = mean_shape['uv_verts']\nself.verts_3d = mean_shape['verts']\nself.faces = mean_shape['faces']\nself.uv_res = mean_shape['uv_map'].shape\nself.uv_map_size = torch.nn.Parameter(torch.tensor([self.uv_res[1] - 1, self.uv_res[0] -... | <|body_start_0|>
super(UVto3D, self).__init__()
self.face_inds = mean_shape['face_inds']
self.verts_uv = mean_shape['uv_verts']
self.verts_3d = mean_shape['verts']
self.faces = mean_shape['faces']
self.uv_res = mean_shape['uv_map'].shape
self.uv_map_size = torch.n... | Module to calculate 3D points from UV values | UVto3D | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UVto3D:
"""Module to calculate 3D points from UV values"""
def __init__(self, mean_shape):
""":param mean_shape: is a dictionary containing the following parameters - uv_map: A R X R tensor of defining the UV steps. Where R is the resolution of the UV map. - verts: A (None, 3) tensor... | stack_v2_sparse_classes_75kplus_train_002620 | 3,140 | no_license | [
{
"docstring": ":param mean_shape: is a dictionary containing the following parameters - uv_map: A R X R tensor of defining the UV steps. Where R is the resolution of the UV map. - verts: A (None, 3) tensor of vertex coordinates of the mean shape - faces: A (None, 3) tensor of faces of the mean shape - face_ind... | 2 | null | Implement the Python class `UVto3D` described below.
Class description:
Module to calculate 3D points from UV values
Method signatures and docstrings:
- def __init__(self, mean_shape): :param mean_shape: is a dictionary containing the following parameters - uv_map: A R X R tensor of defining the UV steps. Where R is ... | Implement the Python class `UVto3D` described below.
Class description:
Module to calculate 3D points from UV values
Method signatures and docstrings:
- def __init__(self, mean_shape): :param mean_shape: is a dictionary containing the following parameters - uv_map: A R X R tensor of defining the UV steps. Where R is ... | 75853a26e30516e9685224ec2e99b05257be2d52 | <|skeleton|>
class UVto3D:
"""Module to calculate 3D points from UV values"""
def __init__(self, mean_shape):
""":param mean_shape: is a dictionary containing the following parameters - uv_map: A R X R tensor of defining the UV steps. Where R is the resolution of the UV map. - verts: A (None, 3) tensor... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UVto3D:
"""Module to calculate 3D points from UV values"""
def __init__(self, mean_shape):
""":param mean_shape: is a dictionary containing the following parameters - uv_map: A R X R tensor of defining the UV steps. Where R is the resolution of the UV map. - verts: A (None, 3) tensor of vertex co... | the_stack_v2_python_sparse | src/model/uv_to_3d.py | harinandan1995/csm | train | 3 |
47fd1b021f7517319075ffb88fa46644a88e80c2 | [
"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. | TakticianServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TakticianServicer:
"""Missing associated documentation comment in .proto file."""
def Analyze(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def Canonicalize(self, request, context):
"""Missing associated docume... | stack_v2_sparse_classes_75kplus_train_002621 | 5,925 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "Analyze",
"signature": "def Analyze(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "Canonicalize",
"signature": "def Canonicalize(self, requ... | 3 | stack_v2_sparse_classes_30k_train_028495 | Implement the Python class `TakticianServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Analyze(self, request, context): Missing associated documentation comment in .proto file.
- def Canonicalize(self, request, context): Miss... | Implement the Python class `TakticianServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Analyze(self, request, context): Missing associated documentation comment in .proto file.
- def Canonicalize(self, request, context): Miss... | 8ab398ad8ce65a7615da476c6e99c3f6d5d24d76 | <|skeleton|>
class TakticianServicer:
"""Missing associated documentation comment in .proto file."""
def Analyze(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def Canonicalize(self, request, context):
"""Missing associated docume... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TakticianServicer:
"""Missing associated documentation comment in .proto file."""
def Analyze(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 | python/tak/proto/taktician_pb2_grpc.py | nelhage/taktician | train | 60 |
9e4afeb548454f8155f448f10acbdb09f26465c4 | [
"self.batch_size = batch_size\nself.use_gram = opt['train']['use_gram']\nself.loss_fn = None\nif opt['train']['feature_criterion'] == 'l1':\n self.loss_fn = tf.losses.MeanAbsoluteError(reduction=tf.losses.Reduction.SUM)\nelif opt['train']['feature_criterion'] == 'l2':\n self.loss_fn = tf.losses.MeanSquaredErr... | <|body_start_0|>
self.batch_size = batch_size
self.use_gram = opt['train']['use_gram']
self.loss_fn = None
if opt['train']['feature_criterion'] == 'l1':
self.loss_fn = tf.losses.MeanAbsoluteError(reduction=tf.losses.Reduction.SUM)
elif opt['train']['feature_criterion'... | Representation of a content (feature) loss function that is the loss extracted from a classifier model | FeatureLoss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureLoss:
"""Representation of a content (feature) loss function that is the loss extracted from a classifier model"""
def __init__(self, batch_size, opt):
"""Initializes the loss function. Attributes: batch_size: the batch size of a network instance (batch size on a device) opt: ... | stack_v2_sparse_classes_75kplus_train_002622 | 8,444 | no_license | [
{
"docstring": "Initializes the loss function. Attributes: batch_size: the batch size of a network instance (batch size on a device) opt: the config file",
"name": "__init__",
"signature": "def __init__(self, batch_size, opt)"
},
{
"docstring": "Compute the loss Args: out: the computed image bat... | 2 | stack_v2_sparse_classes_30k_test_000078 | Implement the Python class `FeatureLoss` described below.
Class description:
Representation of a content (feature) loss function that is the loss extracted from a classifier model
Method signatures and docstrings:
- def __init__(self, batch_size, opt): Initializes the loss function. Attributes: batch_size: the batch ... | Implement the Python class `FeatureLoss` described below.
Class description:
Representation of a content (feature) loss function that is the loss extracted from a classifier model
Method signatures and docstrings:
- def __init__(self, batch_size, opt): Initializes the loss function. Attributes: batch_size: the batch ... | 4809e454512fefe168bebc31cfc8f78e138b7790 | <|skeleton|>
class FeatureLoss:
"""Representation of a content (feature) loss function that is the loss extracted from a classifier model"""
def __init__(self, batch_size, opt):
"""Initializes the loss function. Attributes: batch_size: the batch size of a network instance (batch size on a device) opt: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FeatureLoss:
"""Representation of a content (feature) loss function that is the loss extracted from a classifier model"""
def __init__(self, batch_size, opt):
"""Initializes the loss function. Attributes: batch_size: the batch size of a network instance (batch size on a device) opt: the config fi... | the_stack_v2_python_sparse | utils/train_util.py | mchatton/w2s-tensorflow | train | 16 |
86df2e8614a3a4ae59eb49e5d22457c8813d6281 | [
"constraints = {}\nfor model in config.analysis_models:\n constraints[model.model_name()] = model.constraints()\nif 'constraints' in config.get_all_config():\n constraints['default'] = config.get_all_config()['constraints']\nreturn constraints",
"if constraints:\n for metric in measurement.data():\n ... | <|body_start_0|>
constraints = {}
for model in config.analysis_models:
constraints[model.model_name()] = model.constraints()
if 'constraints' in config.get_all_config():
constraints['default'] = config.get_all_config()['constraints']
return constraints
<|end_body_... | Handles processing and applying constraints on a given measurements | ConstraintManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConstraintManager:
"""Handles processing and applying constraints on a given measurements"""
def get_constraints_for_all_models(config):
"""Parameters ---------- config :ConfigCommandProfile The model analyzer config Returns ------- dict keys are model names, and values are constrain... | stack_v2_sparse_classes_75kplus_train_002623 | 2,367 | permissive | [
{
"docstring": "Parameters ---------- config :ConfigCommandProfile The model analyzer config Returns ------- dict keys are model names, and values are constraints",
"name": "get_constraints_for_all_models",
"signature": "def get_constraints_for_all_models(config)"
},
{
"docstring": "Takes a meas... | 2 | stack_v2_sparse_classes_30k_train_008340 | Implement the Python class `ConstraintManager` described below.
Class description:
Handles processing and applying constraints on a given measurements
Method signatures and docstrings:
- def get_constraints_for_all_models(config): Parameters ---------- config :ConfigCommandProfile The model analyzer config Returns --... | Implement the Python class `ConstraintManager` described below.
Class description:
Handles processing and applying constraints on a given measurements
Method signatures and docstrings:
- def get_constraints_for_all_models(config): Parameters ---------- config :ConfigCommandProfile The model analyzer config Returns --... | 4dbd47c0e71d66d90526d5523570e2c6f717d5bc | <|skeleton|>
class ConstraintManager:
"""Handles processing and applying constraints on a given measurements"""
def get_constraints_for_all_models(config):
"""Parameters ---------- config :ConfigCommandProfile The model analyzer config Returns ------- dict keys are model names, and values are constrain... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConstraintManager:
"""Handles processing and applying constraints on a given measurements"""
def get_constraints_for_all_models(config):
"""Parameters ---------- config :ConfigCommandProfile The model analyzer config Returns ------- dict keys are model names, and values are constraints"""
... | the_stack_v2_python_sparse | model_analyzer/result/constraint_manager.py | ahiroto/model_analyzer | train | 0 |
25ec04ebe914acdc9dc54134a75dc7539c164a8e | [
"super().__init__()\nnum_filters = 32\nself.feature_extractor = nn.Sequential(nn.Conv2d(in_channels=image_channels, out_channels=num_filters, kernel_size=3, stride=1, padding=2), nn.ReLU(), nn.BatchNorm2d(32), nn.Dropout(p=0.2), nn.Conv2d(in_channels=num_filters, out_channels=num_filters, kernel_size=3, stride=1, p... | <|body_start_0|>
super().__init__()
num_filters = 32
self.feature_extractor = nn.Sequential(nn.Conv2d(in_channels=image_channels, out_channels=num_filters, kernel_size=3, stride=1, padding=2), nn.ReLU(), nn.BatchNorm2d(32), nn.Dropout(p=0.2), nn.Conv2d(in_channels=num_filters, out_channels=num_f... | VinnerModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VinnerModel:
def __init__(self, image_channels, num_classes):
"""Is called when model is initialized. Args: image_channels. Number of color channels in image (3) num_classes: Number of classes we want to predict (10)"""
<|body_0|>
def forward(self, x):
"""Performs a ... | stack_v2_sparse_classes_75kplus_train_002624 | 6,804 | no_license | [
{
"docstring": "Is called when model is initialized. Args: image_channels. Number of color channels in image (3) num_classes: Number of classes we want to predict (10)",
"name": "__init__",
"signature": "def __init__(self, image_channels, num_classes)"
},
{
"docstring": "Performs a forward pass ... | 2 | stack_v2_sparse_classes_30k_train_052176 | Implement the Python class `VinnerModel` described below.
Class description:
Implement the VinnerModel class.
Method signatures and docstrings:
- def __init__(self, image_channels, num_classes): Is called when model is initialized. Args: image_channels. Number of color channels in image (3) num_classes: Number of cla... | Implement the Python class `VinnerModel` described below.
Class description:
Implement the VinnerModel class.
Method signatures and docstrings:
- def __init__(self, image_channels, num_classes): Is called when model is initialized. Args: image_channels. Number of color channels in image (3) num_classes: Number of cla... | e08522e3428863253bdb5e0e9162da85555f745f | <|skeleton|>
class VinnerModel:
def __init__(self, image_channels, num_classes):
"""Is called when model is initialized. Args: image_channels. Number of color channels in image (3) num_classes: Number of classes we want to predict (10)"""
<|body_0|>
def forward(self, x):
"""Performs a ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VinnerModel:
def __init__(self, image_channels, num_classes):
"""Is called when model is initialized. Args: image_channels. Number of color channels in image (3) num_classes: Number of classes we want to predict (10)"""
super().__init__()
num_filters = 32
self.feature_extractor... | the_stack_v2_python_sparse | Datasyn/Assignment3/models.py | hellkyb/TDT4265 | train | 0 | |
348edc1bd20b92a99cd98fde7925f153481246de | [
"if len(s1) != len(s2):\n return False\ncompare = s2 + s2\nreturn s1 in compare",
"if s1 == s2:\n return True\nfor i in s1:\n if s1[i:] + s1[:i] == s2:\n return True\nreturn False"
] | <|body_start_0|>
if len(s1) != len(s2):
return False
compare = s2 + s2
return s1 in compare
<|end_body_0|>
<|body_start_1|>
if s1 == s2:
return True
for i in s1:
if s1[i:] + s1[:i] == s2:
return True
return False
<|end_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isFlipedString(self, s1: str, s2: str) -> bool:
"""首先判断长度是否一致,不相同返回False, 其次拼接两个 s2,如果是由 s1旋转而成,则拼接后的s 一定包含 s1。 复杂度分析: 时间复杂度:O(N) 空间复杂度:O(N)"""
<|body_0|>
def isFlipedString2(self, s1: str, s2: str) -> bool:
"""逐个比较,笨方法 注意: s1, s2 = '', ''"""
<|... | stack_v2_sparse_classes_75kplus_train_002625 | 1,406 | no_license | [
{
"docstring": "首先判断长度是否一致,不相同返回False, 其次拼接两个 s2,如果是由 s1旋转而成,则拼接后的s 一定包含 s1。 复杂度分析: 时间复杂度:O(N) 空间复杂度:O(N)",
"name": "isFlipedString",
"signature": "def isFlipedString(self, s1: str, s2: str) -> bool"
},
{
"docstring": "逐个比较,笨方法 注意: s1, s2 = '', ''",
"name": "isFlipedString2",
"signature"... | 2 | stack_v2_sparse_classes_30k_train_045631 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isFlipedString(self, s1: str, s2: str) -> bool: 首先判断长度是否一致,不相同返回False, 其次拼接两个 s2,如果是由 s1旋转而成,则拼接后的s 一定包含 s1。 复杂度分析: 时间复杂度:O(N) 空间复杂度:O(N)
- def isFlipedString2(self, s1: str,... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isFlipedString(self, s1: str, s2: str) -> bool: 首先判断长度是否一致,不相同返回False, 其次拼接两个 s2,如果是由 s1旋转而成,则拼接后的s 一定包含 s1。 复杂度分析: 时间复杂度:O(N) 空间复杂度:O(N)
- def isFlipedString2(self, s1: str,... | 51943e2c2c4ec70c7c1d5b53c9fdf0a719428d7a | <|skeleton|>
class Solution:
def isFlipedString(self, s1: str, s2: str) -> bool:
"""首先判断长度是否一致,不相同返回False, 其次拼接两个 s2,如果是由 s1旋转而成,则拼接后的s 一定包含 s1。 复杂度分析: 时间复杂度:O(N) 空间复杂度:O(N)"""
<|body_0|>
def isFlipedString2(self, s1: str, s2: str) -> bool:
"""逐个比较,笨方法 注意: s1, s2 = '', ''"""
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isFlipedString(self, s1: str, s2: str) -> bool:
"""首先判断长度是否一致,不相同返回False, 其次拼接两个 s2,如果是由 s1旋转而成,则拼接后的s 一定包含 s1。 复杂度分析: 时间复杂度:O(N) 空间复杂度:O(N)"""
if len(s1) != len(s2):
return False
compare = s2 + s2
return s1 in compare
def isFlipedString2(self, s1... | the_stack_v2_python_sparse | LCCI/01_09_StringRotation.py | LeBron-Jian/BasicAlgorithmPractice | train | 13 | |
ed6eb9de4292261311f07df761622b390711a0aa | [
"if id is not None:\n self.id = id\nelse:\n Base.__nb_objects += 1\n self.id = self.__nb_objects",
"if list_dictionaries is None:\n return '[]'\nelse:\n if type(list_dictionaries) is not list:\n raise TypeError('list_dictionaries must be a list')\n jsoned = json.dumps(list_dictionaries)\n... | <|body_start_0|>
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = self.__nb_objects
<|end_body_0|>
<|body_start_1|>
if list_dictionaries is None:
return '[]'
else:
if type(list_dictionaries) is not list:
... | A Base class Attributes: __nb_objects: counter for the number of objects in class | Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base:
"""A Base class Attributes: __nb_objects: counter for the number of objects in class"""
def __init__(self, id=None):
"""class constructor Args: id: memory id of object"""
<|body_0|>
def to_json_string(list_dictionaries):
"""Returns the JSON string represent... | stack_v2_sparse_classes_75kplus_train_002626 | 2,281 | no_license | [
{
"docstring": "class constructor Args: id: memory id of object",
"name": "__init__",
"signature": "def __init__(self, id=None)"
},
{
"docstring": "Returns the JSON string representation of list_dictionaries",
"name": "to_json_string",
"signature": "def to_json_string(list_dictionaries)"... | 6 | stack_v2_sparse_classes_30k_train_051593 | Implement the Python class `Base` described below.
Class description:
A Base class Attributes: __nb_objects: counter for the number of objects in class
Method signatures and docstrings:
- def __init__(self, id=None): class constructor Args: id: memory id of object
- def to_json_string(list_dictionaries): Returns the ... | Implement the Python class `Base` described below.
Class description:
A Base class Attributes: __nb_objects: counter for the number of objects in class
Method signatures and docstrings:
- def __init__(self, id=None): class constructor Args: id: memory id of object
- def to_json_string(list_dictionaries): Returns the ... | 2068b35a649d5b791937bd90c9992a0e36976a80 | <|skeleton|>
class Base:
"""A Base class Attributes: __nb_objects: counter for the number of objects in class"""
def __init__(self, id=None):
"""class constructor Args: id: memory id of object"""
<|body_0|>
def to_json_string(list_dictionaries):
"""Returns the JSON string represent... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Base:
"""A Base class Attributes: __nb_objects: counter for the number of objects in class"""
def __init__(self, id=None):
"""class constructor Args: id: memory id of object"""
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id... | the_stack_v2_python_sparse | 0x0C-python-almost_a_circle/models/base.py | abenetsol/holbertonschool-higher_level_programming | train | 0 |
0c2a099823d5ccba1ae9c71384818ac57ce242a9 | [
"if not isinstance(model, FixedNoiseGP):\n raise UnsupportedError('Only FixedNoiseGPs are currently supported for fantasy LogNEI')\nfrom botorch.sampling.normal import SobolQMCNormalSampler\nwith nullcontext() if X_observed.requires_grad else torch.no_grad():\n posterior = model.posterior(X=X_observed)\nsampl... | <|body_start_0|>
if not isinstance(model, FixedNoiseGP):
raise UnsupportedError('Only FixedNoiseGPs are currently supported for fantasy LogNEI')
from botorch.sampling.normal import SobolQMCNormalSampler
with nullcontext() if X_observed.requires_grad else torch.no_grad():
... | Single-outcome Log Noisy Expected Improvement (via fantasies). This computes Log Noisy Expected Improvement by averaging over the Expected Improvement values of a number of fantasy models. Only supports the case `q=1`. Assumes that the posterior distribution of the model is Gaussian. The model must be single-outcome. `... | LogNoisyExpectedImprovement | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogNoisyExpectedImprovement:
"""Single-outcome Log Noisy Expected Improvement (via fantasies). This computes Log Noisy Expected Improvement by averaging over the Expected Improvement values of a number of fantasy models. Only supports the case `q=1`. Assumes that the posterior distribution of the... | stack_v2_sparse_classes_75kplus_train_002627 | 46,601 | permissive | [
{
"docstring": "Single-outcome Noisy Log Expected Improvement (via fantasies). Args: model: A fitted single-outcome model. X_observed: A `n x d` Tensor of observed points that are likely to be the best observed points so far. num_fantasies: The number of fantasies to generate. The higher this number the more ac... | 2 | stack_v2_sparse_classes_30k_train_025479 | Implement the Python class `LogNoisyExpectedImprovement` described below.
Class description:
Single-outcome Log Noisy Expected Improvement (via fantasies). This computes Log Noisy Expected Improvement by averaging over the Expected Improvement values of a number of fantasy models. Only supports the case `q=1`. Assumes... | Implement the Python class `LogNoisyExpectedImprovement` described below.
Class description:
Single-outcome Log Noisy Expected Improvement (via fantasies). This computes Log Noisy Expected Improvement by averaging over the Expected Improvement values of a number of fantasy models. Only supports the case `q=1`. Assumes... | 4cc5ed59b2e8a9c780f786830c548e05cc74d53c | <|skeleton|>
class LogNoisyExpectedImprovement:
"""Single-outcome Log Noisy Expected Improvement (via fantasies). This computes Log Noisy Expected Improvement by averaging over the Expected Improvement values of a number of fantasy models. Only supports the case `q=1`. Assumes that the posterior distribution of the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LogNoisyExpectedImprovement:
"""Single-outcome Log Noisy Expected Improvement (via fantasies). This computes Log Noisy Expected Improvement by averaging over the Expected Improvement values of a number of fantasy models. Only supports the case `q=1`. Assumes that the posterior distribution of the model is Gau... | the_stack_v2_python_sparse | botorch/acquisition/analytic.py | pytorch/botorch | train | 2,891 |
a93298307b922dc52690651f676a911b32fedf83 | [
"db_file = self.db_file\nif logger.isEnabledFor(logging.DEBUG):\n logger.debug(f'creating connection to {db_file}')\ncreated = False\nif not db_file.exists():\n if not self.create_db:\n raise DBError(f'database file {db_file} does not exist')\n if not db_file.parent.exists():\n if logger.isEn... | <|body_start_0|>
db_file = self.db_file
if logger.isEnabledFor(logging.DEBUG):
logger.debug(f'creating connection to {db_file}')
created = False
if not db_file.exists():
if not self.create_db:
raise DBError(f'database file {db_file} does not exist'... | An SQLite connection factory. | SqliteConnectionManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SqliteConnectionManager:
"""An SQLite connection factory."""
def create(self) -> sqlite3.Connection:
"""Create a connection by accessing the SQLite file. :raise DBError: if the SQLite file does not exist (caveat see :`obj:create_db`)"""
<|body_0|>
def drop(self):
... | stack_v2_sparse_classes_75kplus_train_002628 | 2,337 | permissive | [
{
"docstring": "Create a connection by accessing the SQLite file. :raise DBError: if the SQLite file does not exist (caveat see :`obj:create_db`)",
"name": "create",
"signature": "def create(self) -> sqlite3.Connection"
},
{
"docstring": "Delete the SQLite database file from the file system.",
... | 2 | stack_v2_sparse_classes_30k_train_013338 | Implement the Python class `SqliteConnectionManager` described below.
Class description:
An SQLite connection factory.
Method signatures and docstrings:
- def create(self) -> sqlite3.Connection: Create a connection by accessing the SQLite file. :raise DBError: if the SQLite file does not exist (caveat see :`obj:creat... | Implement the Python class `SqliteConnectionManager` described below.
Class description:
An SQLite connection factory.
Method signatures and docstrings:
- def create(self) -> sqlite3.Connection: Create a connection by accessing the SQLite file. :raise DBError: if the SQLite file does not exist (caveat see :`obj:creat... | a1984c23adaad6e8f12fb6f77b2298aa6c4eff5d | <|skeleton|>
class SqliteConnectionManager:
"""An SQLite connection factory."""
def create(self) -> sqlite3.Connection:
"""Create a connection by accessing the SQLite file. :raise DBError: if the SQLite file does not exist (caveat see :`obj:create_db`)"""
<|body_0|>
def drop(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SqliteConnectionManager:
"""An SQLite connection factory."""
def create(self) -> sqlite3.Connection:
"""Create a connection by accessing the SQLite file. :raise DBError: if the SQLite file does not exist (caveat see :`obj:create_db`)"""
db_file = self.db_file
if logger.isEnabledFo... | the_stack_v2_python_sparse | src/python/zensols/db/sqlite.py | plandes/dbutil | train | 0 |
ca9dea3d3c0eba3e8403d17bc98621fac91824d5 | [
"super().__init__(layer_options, *args, **kwargs)\nif 'dropout_rate' in layer_options:\n self._dropout_rate = float(layer_options['dropout_rate'])\n self._dropout_rate = min(0.9999, self._dropout_rate)\nelse:\n self._dropout_rate = 0.5\nlogging.debug(' dropout_rate=%f', self._dropout_rate)\ninput_size = s... | <|body_start_0|>
super().__init__(layer_options, *args, **kwargs)
if 'dropout_rate' in layer_options:
self._dropout_rate = float(layer_options['dropout_rate'])
self._dropout_rate = min(0.9999, self._dropout_rate)
else:
self._dropout_rate = 0.5
logging.... | Dropout Layer A dropout layer is not a regular layer in the sense that it doesn't contain any neurons. It simply randomly sets some activations to zero at train time to prevent overfitting. N. Srivastava et al. (2014) Dropout: A Simple Way to Prevent Neural Networks from Overfitting Journal of Machine Learning Research... | DropoutLayer | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DropoutLayer:
"""Dropout Layer A dropout layer is not a regular layer in the sense that it doesn't contain any neurons. It simply randomly sets some activations to zero at train time to prevent overfitting. N. Srivastava et al. (2014) Dropout: A Simple Way to Prevent Neural Networks from Overfitt... | stack_v2_sparse_classes_75kplus_train_002629 | 2,727 | permissive | [
{
"docstring": "Validates the parameters of this layer.",
"name": "__init__",
"signature": "def __init__(self, layer_options, *args, **kwargs)"
},
{
"docstring": "Creates the symbolic graph of this layer. Sets ``self.output`` to a symbolic matrix that describes the output of this layer. During t... | 2 | stack_v2_sparse_classes_30k_train_025718 | Implement the Python class `DropoutLayer` described below.
Class description:
Dropout Layer A dropout layer is not a regular layer in the sense that it doesn't contain any neurons. It simply randomly sets some activations to zero at train time to prevent overfitting. N. Srivastava et al. (2014) Dropout: A Simple Way t... | Implement the Python class `DropoutLayer` described below.
Class description:
Dropout Layer A dropout layer is not a regular layer in the sense that it doesn't contain any neurons. It simply randomly sets some activations to zero at train time to prevent overfitting. N. Srivastava et al. (2014) Dropout: A Simple Way t... | 9904faec19ad5718470f21927229aad2656e5686 | <|skeleton|>
class DropoutLayer:
"""Dropout Layer A dropout layer is not a regular layer in the sense that it doesn't contain any neurons. It simply randomly sets some activations to zero at train time to prevent overfitting. N. Srivastava et al. (2014) Dropout: A Simple Way to Prevent Neural Networks from Overfitt... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DropoutLayer:
"""Dropout Layer A dropout layer is not a regular layer in the sense that it doesn't contain any neurons. It simply randomly sets some activations to zero at train time to prevent overfitting. N. Srivastava et al. (2014) Dropout: A Simple Way to Prevent Neural Networks from Overfitting Journal o... | the_stack_v2_python_sparse | theanolm/network/dropoutlayer.py | senarvi/theanolm | train | 95 |
d5280fecd521085a537d5459d8df526e7e29fe0f | [
"G = [0] * (n + 1)\nG[0], G[1] = (1, 1)\nfor i in range(2, n + 1):\n for j in range(1, i + 1):\n G[i] += G[j - 1] * G[i - j]\nreturn G[n]",
"C = 1\nfor i in range(0, n):\n C = 2 * (2 * i + 1) / (i + 2) * C\nreturn int(C)"
] | <|body_start_0|>
G = [0] * (n + 1)
G[0], G[1] = (1, 1)
for i in range(2, n + 1):
for j in range(1, i + 1):
G[i] += G[j - 1] * G[i - j]
return G[n]
<|end_body_0|>
<|body_start_1|>
C = 1
for i in range(0, n):
C = 2 * (2 * i + 1) / (i... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numTrees(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def catalanNumber(self, n):
"""The above number is actually known as Catalan number. :type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
G = [0] * (n + 1... | stack_v2_sparse_classes_75kplus_train_002630 | 1,680 | permissive | [
{
"docstring": ":type n: int :rtype: int",
"name": "numTrees",
"signature": "def numTrees(self, n)"
},
{
"docstring": "The above number is actually known as Catalan number. :type n: int :rtype: int",
"name": "catalanNumber",
"signature": "def catalanNumber(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numTrees(self, n): :type n: int :rtype: int
- def catalanNumber(self, n): The above number is actually known as Catalan number. :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numTrees(self, n): :type n: int :rtype: int
- def catalanNumber(self, n): The above number is actually known as Catalan number. :type n: int :rtype: int
<|skeleton|>
class S... | bf03743a3676ca9a8c107f92cf3858b6887d0308 | <|skeleton|>
class Solution:
def numTrees(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def catalanNumber(self, n):
"""The above number is actually known as Catalan number. :type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def numTrees(self, n):
""":type n: int :rtype: int"""
G = [0] * (n + 1)
G[0], G[1] = (1, 1)
for i in range(2, n + 1):
for j in range(1, i + 1):
G[i] += G[j - 1] * G[i - j]
return G[n]
def catalanNumber(self, n):
"""The ... | the_stack_v2_python_sparse | python/96_numberOfUniqueBST.py | liaison/LeetCode | train | 17 | |
e990c8f2e895c48801aecd7b16f8bc27a6d924d6 | [
"dp = self._dp\nwhile len(dp) <= n:\n dp += (min((dp[-i * i] for i in range(1, int(len(dp) ** 0.5 + 1)))) + 1,)\nreturn dp[n]",
"dp = defaultdict(int)\ny = 1\nwhile y * y <= n:\n dp[y * y] = 1\n y += 1\nfor x in range(1, n + 1):\n y = 1\n while x + y * y <= n:\n if x + y * y not in dp or dp[... | <|body_start_0|>
dp = self._dp
while len(dp) <= n:
dp += (min((dp[-i * i] for i in range(1, int(len(dp) ** 0.5 + 1)))) + 1,)
return dp[n]
<|end_body_0|>
<|body_start_1|>
dp = defaultdict(int)
y = 1
while y * y <= n:
dp[y * y] = 1
y += ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSquares(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def numSquares_v0(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dp = self._dp
while len(dp) <= n:
dp += (min((dp... | stack_v2_sparse_classes_75kplus_train_002631 | 4,366 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "numSquares",
"signature": "def numSquares(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "numSquares_v0",
"signature": "def numSquares_v0(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares(self, n): :type n: int :rtype: int
- def numSquares_v0(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 numSquares(self, n): :type n: int :rtype: int
- def numSquares_v0(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def numSquares(self, n):
""":t... | b5e09f24e8e96454dc99e20281e853fb9fcc85ed | <|skeleton|>
class Solution:
def numSquares(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def numSquares_v0(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def numSquares(self, n):
""":type n: int :rtype: int"""
dp = self._dp
while len(dp) <= n:
dp += (min((dp[-i * i] for i in range(1, int(len(dp) ** 0.5 + 1)))) + 1,)
return dp[n]
def numSquares_v0(self, n):
""":type n: int :rtype: int"""
... | the_stack_v2_python_sparse | python/279_Perfect_Squares.py | Moby5/myleetcode | train | 2 | |
42c8cacf1247d6146c1884916c8eb9d5d266a763 | [
"path_of_preorder = []\n\ndef helper(node):\n if node:\n path_of_preorder.append(node.val)\n helper(node.left)\n helper(node.right)\nhelper(root)\nreturn '#'.join(map(str, path_of_preorder))",
"if not data:\n return None\nnode_values = deque((int(value) for value in data.split('#')))\n\... | <|body_start_0|>
path_of_preorder = []
def helper(node):
if node:
path_of_preorder.append(node.val)
helper(node.left)
helper(node.right)
helper(root)
return '#'.join(map(str, path_of_preorder))
<|end_body_0|>
<|body_start_1|>
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
path_of_preord... | stack_v2_sparse_classes_75kplus_train_002632 | 2,343 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_046148 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | 5f71ba34f7198841fefaa68eee5b95f2f989296b | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
path_of_preorder = []
def helper(node):
if node:
path_of_preorder.append(node.val)
helper(node.left)
helper(node.right)
helpe... | the_stack_v2_python_sparse | LeetCode/medium/29_SerializeBST.py | Kohdz/Algorithms | train | 5 | |
90acc4c6f64af9f0513417fca149d619450bc5c7 | [
"self.name = name\nself.pos = []\nself.Pn = []\nself.flux = []\nself.pointCloud = []\nself.readpil3d()",
"res = np.loadtxt(self.name, delimiter=' ')\nself.pos = res[:, 0:3]\nself.Pn = res[:, 3:4]\nself.flux = res[:, -1]",
"self.pointCloud = VtkPointCloud()\nfor k in range(np.size(self.pos, 0)):\n self.pointC... | <|body_start_0|>
self.name = name
self.pos = []
self.Pn = []
self.flux = []
self.pointCloud = []
self.readpil3d()
<|end_body_0|>
<|body_start_1|>
res = np.loadtxt(self.name, delimiter=' ')
self.pos = res[:, 0:3]
self.Pn = res[:, 3:4]
self.... | Class representing a PILAGER3D output file. | PIL3D | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PIL3D:
"""Class representing a PILAGER3D output file."""
def __init__(self, name):
"""Method to initialize class."""
<|body_0|>
def readpil3d(self):
"""Method to read in the pil3d txt file."""
<|body_1|>
def make_point_cloud(self):
"""Method ... | stack_v2_sparse_classes_75kplus_train_002633 | 3,136 | no_license | [
{
"docstring": "Method to initialize class.",
"name": "__init__",
"signature": "def __init__(self, name)"
},
{
"docstring": "Method to read in the pil3d txt file.",
"name": "readpil3d",
"signature": "def readpil3d(self)"
},
{
"docstring": "Method to plot the point cloud.",
"n... | 3 | stack_v2_sparse_classes_30k_train_022181 | Implement the Python class `PIL3D` described below.
Class description:
Class representing a PILAGER3D output file.
Method signatures and docstrings:
- def __init__(self, name): Method to initialize class.
- def readpil3d(self): Method to read in the pil3d txt file.
- def make_point_cloud(self): Method to plot the poi... | Implement the Python class `PIL3D` described below.
Class description:
Class representing a PILAGER3D output file.
Method signatures and docstrings:
- def __init__(self, name): Method to initialize class.
- def readpil3d(self): Method to read in the pil3d txt file.
- def make_point_cloud(self): Method to plot the poi... | 6b37842203ff4318a48dbf0258cbe2b253436e7d | <|skeleton|>
class PIL3D:
"""Class representing a PILAGER3D output file."""
def __init__(self, name):
"""Method to initialize class."""
<|body_0|>
def readpil3d(self):
"""Method to read in the pil3d txt file."""
<|body_1|>
def make_point_cloud(self):
"""Method ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PIL3D:
"""Class representing a PILAGER3D output file."""
def __init__(self, name):
"""Method to initialize class."""
self.name = name
self.pos = []
self.Pn = []
self.flux = []
self.pointCloud = []
self.readpil3d()
def readpil3d(self):
"... | the_stack_v2_python_sparse | plume/pil3d.py | tslowery78/PyLnD | train | 0 |
89dcbe0a1e14c94a93fab6bb500551d70b2fabfe | [
"if self.user:\n post = Post.get_by_id(int(post_id))\n if not post:\n self.error(404)\n if post.user.key().id() == int(self.user):\n self.render('edit_blog.html', post=post)\n else:\n error = 'You cannot edit this post.'\n self.render('edit_blog.html', access_error=error)\nel... | <|body_start_0|>
if self.user:
post = Post.get_by_id(int(post_id))
if not post:
self.error(404)
if post.user.key().id() == int(self.user):
self.render('edit_blog.html', post=post)
else:
error = 'You cannot edit this ... | To create a new blog post | EditBlog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditBlog:
"""To create a new blog post"""
def get(self, post_id):
"""Renders the form for adding post"""
<|body_0|>
def post(self, post_id):
"""To process ans store blog post information into database"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_002634 | 4,859 | no_license | [
{
"docstring": "Renders the form for adding post",
"name": "get",
"signature": "def get(self, post_id)"
},
{
"docstring": "To process ans store blog post information into database",
"name": "post",
"signature": "def post(self, post_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009181 | Implement the Python class `EditBlog` described below.
Class description:
To create a new blog post
Method signatures and docstrings:
- def get(self, post_id): Renders the form for adding post
- def post(self, post_id): To process ans store blog post information into database | Implement the Python class `EditBlog` described below.
Class description:
To create a new blog post
Method signatures and docstrings:
- def get(self, post_id): Renders the form for adding post
- def post(self, post_id): To process ans store blog post information into database
<|skeleton|>
class EditBlog:
"""To c... | 74c6e821c2fdb4198de8be2e83c64164e23f9992 | <|skeleton|>
class EditBlog:
"""To create a new blog post"""
def get(self, post_id):
"""Renders the form for adding post"""
<|body_0|>
def post(self, post_id):
"""To process ans store blog post information into database"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EditBlog:
"""To create a new blog post"""
def get(self, post_id):
"""Renders the form for adding post"""
if self.user:
post = Post.get_by_id(int(post_id))
if not post:
self.error(404)
if post.user.key().id() == int(self.user):
... | the_stack_v2_python_sparse | Multi User Blog/Multi User Blog/handlers/blog.py | mascot6699/udacity-full-stack | train | 8 |
83c03f4527a2df4c5994f985d6e2c750d72e59d9 | [
"self.client = texttospeech.TextToSpeechClient(credentials=credentials)\nself.ws_path = ws_path\nself.temp_path = ''",
"gender_nb = 'B'\ngender = texttospeech.SsmlVoiceGender.MALE\nif voice_gender == 1:\n gender = texttospeech.SsmlVoiceGender.FEMALE\n gender_nb = 'A'\nif voice_quality == 'w':\n name = la... | <|body_start_0|>
self.client = texttospeech.TextToSpeechClient(credentials=credentials)
self.ws_path = ws_path
self.temp_path = ''
<|end_body_0|>
<|body_start_1|>
gender_nb = 'B'
gender = texttospeech.SsmlVoiceGender.MALE
if voice_gender == 1:
gender = textto... | Class to interface with Google Translate’s text-to-speech API | GoogleTTS | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoogleTTS:
"""Class to interface with Google Translate’s text-to-speech API"""
def __init__(self, ws_path='/home/flavien/Documents/TTS/audio_files/', credentials=service_account.Credentials.from_service_account_file('inmoovkey.json')):
"""Instantiates a client with the following para... | stack_v2_sparse_classes_75kplus_train_002635 | 19,139 | no_license | [
{
"docstring": "Instantiates a client with the following parameters: - ws_path: path of the workspace directory (ex: /home/user/...) - credentials: credentials to use the google api",
"name": "__init__",
"signature": "def __init__(self, ws_path='/home/flavien/Documents/TTS/audio_files/', credentials=ser... | 3 | stack_v2_sparse_classes_30k_train_014590 | Implement the Python class `GoogleTTS` described below.
Class description:
Class to interface with Google Translate’s text-to-speech API
Method signatures and docstrings:
- def __init__(self, ws_path='/home/flavien/Documents/TTS/audio_files/', credentials=service_account.Credentials.from_service_account_file('inmoovk... | Implement the Python class `GoogleTTS` described below.
Class description:
Class to interface with Google Translate’s text-to-speech API
Method signatures and docstrings:
- def __init__(self, ws_path='/home/flavien/Documents/TTS/audio_files/', credentials=service_account.Credentials.from_service_account_file('inmoovk... | d1ba87ff5b0f2b58c98f02519073b335cdc55c58 | <|skeleton|>
class GoogleTTS:
"""Class to interface with Google Translate’s text-to-speech API"""
def __init__(self, ws_path='/home/flavien/Documents/TTS/audio_files/', credentials=service_account.Credentials.from_service_account_file('inmoovkey.json')):
"""Instantiates a client with the following para... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GoogleTTS:
"""Class to interface with Google Translate’s text-to-speech API"""
def __init__(self, ws_path='/home/flavien/Documents/TTS/audio_files/', credentials=service_account.Credentials.from_service_account_file('inmoovkey.json')):
"""Instantiates a client with the following parameters: - ws_... | the_stack_v2_python_sparse | AI/Google_voice/STT-TTS/gstt.py | cemot/DaVinciBot-InMoov-2020-2021 | train | 0 |
27a9995676b055c0fdbef5c2fb8df0007d6e5e67 | [
"super().__init__()\nself.blocks = len(rnns)\nfor index, rnn in enumerate(rnns, 1):\n setattr(self, 'rnn' + str(index), rnn)\nself.output_layer = cnn",
"if len(inputs) > 0:\n inputs = inputs.transpose(0, 1)\ncur_rnn = getattr(self, 'rnn1')\nres = []\nhidden_states = []\ninputs, state_stage = cur_rnn(seq_len... | <|body_start_0|>
super().__init__()
self.blocks = len(rnns)
for index, rnn in enumerate(rnns, 1):
setattr(self, 'rnn' + str(index), rnn)
self.output_layer = cnn
<|end_body_0|>
<|body_start_1|>
if len(inputs) > 0:
inputs = inputs.transpose(0, 1)
cu... | decode a sequence given an initial tuple of hidden states and cell states It consists of multiple convlstm cells and one convcell layer. | Decoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
"""decode a sequence given an initial tuple of hidden states and cell states It consists of multiple convlstm cells and one convcell layer."""
def __init__(self, rnns, cnn):
"""rnns are a list of convlstm cells, and cnn is a convcell"""
<|body_0|>
def forward(se... | stack_v2_sparse_classes_75kplus_train_002636 | 41,120 | no_license | [
{
"docstring": "rnns are a list of convlstm cells, and cnn is a convcell",
"name": "__init__",
"signature": "def __init__(self, rnns, cnn)"
},
{
"docstring": "forward pass of the decoder :param seq_len: how long the sequence is decoded to be :param initial_state: a list of tuples [(h, c), ..., (... | 2 | stack_v2_sparse_classes_30k_train_022837 | Implement the Python class `Decoder` described below.
Class description:
decode a sequence given an initial tuple of hidden states and cell states It consists of multiple convlstm cells and one convcell layer.
Method signatures and docstrings:
- def __init__(self, rnns, cnn): rnns are a list of convlstm cells, and cn... | Implement the Python class `Decoder` described below.
Class description:
decode a sequence given an initial tuple of hidden states and cell states It consists of multiple convlstm cells and one convcell layer.
Method signatures and docstrings:
- def __init__(self, rnns, cnn): rnns are a list of convlstm cells, and cn... | b6a3161635bfa3b5da8ec871e1025e01f878e732 | <|skeleton|>
class Decoder:
"""decode a sequence given an initial tuple of hidden states and cell states It consists of multiple convlstm cells and one convcell layer."""
def __init__(self, rnns, cnn):
"""rnns are a list of convlstm cells, and cnn is a convcell"""
<|body_0|>
def forward(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Decoder:
"""decode a sequence given an initial tuple of hidden states and cell states It consists of multiple convlstm cells and one convcell layer."""
def __init__(self, rnns, cnn):
"""rnns are a list of convlstm cells, and cnn is a convcell"""
super().__init__()
self.blocks = le... | the_stack_v2_python_sparse | src/bayesian_neural_net.py | KEHUIYAO/BCLS | train | 0 |
1443fb56bdaa5faff76fb302e7d33b7263af4452 | [
"self.last_name = value\nif not self.allow_empty_string and value.strip() == '':\n raise TraitError('Empty string not allowed.')\nreturn super(MyViewController, self).setattr(info, object, traitname, value)",
"if not self.allow_empty_string and self.model.myname == '':\n self.model.myname = '?'\nelse:\n ... | <|body_start_0|>
self.last_name = value
if not self.allow_empty_string and value.strip() == '':
raise TraitError('Empty string not allowed.')
return super(MyViewController, self).setattr(info, object, traitname, value)
<|end_body_0|>
<|body_start_1|>
if not self.allow_empty_... | Define a combined controller/view class that validates that MyModel.myname is consistent with the 'allow_empty_string' flag. | MyViewController | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyViewController:
"""Define a combined controller/view class that validates that MyModel.myname is consistent with the 'allow_empty_string' flag."""
def myname_setattr(self, info, object, traitname, value):
"""Validate the request to change the named trait on object to the specified ... | stack_v2_sparse_classes_75kplus_train_002637 | 3,027 | permissive | [
{
"docstring": "Validate the request to change the named trait on object to the specified value. Validation errors raise TraitError, which by default causes the editor's entry field to be shown in red. (This is a specially named method <model trait name>_setattr, which is available inside a Controller.)",
"... | 2 | stack_v2_sparse_classes_30k_train_052109 | Implement the Python class `MyViewController` described below.
Class description:
Define a combined controller/view class that validates that MyModel.myname is consistent with the 'allow_empty_string' flag.
Method signatures and docstrings:
- def myname_setattr(self, info, object, traitname, value): Validate the requ... | Implement the Python class `MyViewController` described below.
Class description:
Define a combined controller/view class that validates that MyModel.myname is consistent with the 'allow_empty_string' flag.
Method signatures and docstrings:
- def myname_setattr(self, info, object, traitname, value): Validate the requ... | 95479cd0c298de4c18718b0477baada3384bcad2 | <|skeleton|>
class MyViewController:
"""Define a combined controller/view class that validates that MyModel.myname is consistent with the 'allow_empty_string' flag."""
def myname_setattr(self, info, object, traitname, value):
"""Validate the request to change the named trait on object to the specified ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyViewController:
"""Define a combined controller/view class that validates that MyModel.myname is consistent with the 'allow_empty_string' flag."""
def myname_setattr(self, info, object, traitname, value):
"""Validate the request to change the named trait on object to the specified value. Valida... | the_stack_v2_python_sparse | Python/Book/scipybook2/codes/traitsuidemo/Advanced/MVC_demo.py | leeweizhe1993/Individual_project | train | 2 |
892cbc07a1524f47caaf9eddeb1e1485bb79c915 | [
"data = form.cleaned_data\nself.success_url = reverse('mark_scripts', kwargs={'course': data['course'].id})\nreturn super().form_valid(form)",
"context = super().get_context_data(**kwargs)\ncontext['title_text'] = 'Choose Exam Scripts To Mark'\ncontext['detail_text'] = 'Please select details of the exam\\n ... | <|body_start_0|>
data = form.cleaned_data
self.success_url = reverse('mark_scripts', kwargs={'course': data['course'].id})
return super().form_valid(form)
<|end_body_0|>
<|body_start_1|>
context = super().get_context_data(**kwargs)
context['title_text'] = 'Choose Exam Scripts To... | View for choosing which exam script to mark. Check that the user is a lecturer and that the account is still active. Redirects to Mark Scripts page on success. | MarkScriptView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MarkScriptView:
"""View for choosing which exam script to mark. Check that the user is a lecturer and that the account is still active. Redirects to Mark Scripts page on success."""
def form_valid(self, form):
"""Compute the success URL and call super.form_valid()"""
<|body_0... | stack_v2_sparse_classes_75kplus_train_002638 | 29,759 | no_license | [
{
"docstring": "Compute the success URL and call super.form_valid()",
"name": "form_valid",
"signature": "def form_valid(self, form)"
},
{
"docstring": "Return the data used in the templates rendering.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
... | 2 | stack_v2_sparse_classes_30k_val_000367 | Implement the Python class `MarkScriptView` described below.
Class description:
View for choosing which exam script to mark. Check that the user is a lecturer and that the account is still active. Redirects to Mark Scripts page on success.
Method signatures and docstrings:
- def form_valid(self, form): Compute the su... | Implement the Python class `MarkScriptView` described below.
Class description:
View for choosing which exam script to mark. Check that the user is a lecturer and that the account is still active. Redirects to Mark Scripts page on success.
Method signatures and docstrings:
- def form_valid(self, form): Compute the su... | 06bc577d01d3dbf6c425e03dcb903977a38e377c | <|skeleton|>
class MarkScriptView:
"""View for choosing which exam script to mark. Check that the user is a lecturer and that the account is still active. Redirects to Mark Scripts page on success."""
def form_valid(self, form):
"""Compute the success URL and call super.form_valid()"""
<|body_0... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MarkScriptView:
"""View for choosing which exam script to mark. Check that the user is a lecturer and that the account is still active. Redirects to Mark Scripts page on success."""
def form_valid(self, form):
"""Compute the success URL and call super.form_valid()"""
data = form.cleaned_d... | the_stack_v2_python_sparse | cbt/views.py | Festusali/CBTest | train | 6 |
208f8d72da4f08423c7e63cc5482564ccf5f5b33 | [
"_logger.info(f'Computing cluster qc for {folder_probe}')\nspikes = alf.io.load_object(folder_probe, 'spikes')\nclusters = alf.io.load_object(folder_probe, 'clusters')\ndf_units, drift = ephysqc.spike_sorting_metrics(spikes.times, spikes.clusters, spikes.amps, spikes.depths, cluster_ids=np.arange(clusters.channels.... | <|body_start_0|>
_logger.info(f'Computing cluster qc for {folder_probe}')
spikes = alf.io.load_object(folder_probe, 'spikes')
clusters = alf.io.load_object(folder_probe, 'clusters')
df_units, drift = ephysqc.spike_sorting_metrics(spikes.times, spikes.clusters, spikes.amps, spikes.depths,... | EphysCellsQc | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EphysCellsQc:
def _compute_cell_qc(self, folder_probe):
"""Computes the cell QC given an extracted probe alf path :param folder_probe: folder :return:"""
<|body_0|>
def _label_probe_qc(self, folder_probe, df_units, drift):
"""Labels the json field of the alyx corresp... | stack_v2_sparse_classes_75kplus_train_002639 | 17,734 | permissive | [
{
"docstring": "Computes the cell QC given an extracted probe alf path :param folder_probe: folder :return:",
"name": "_compute_cell_qc",
"signature": "def _compute_cell_qc(self, folder_probe)"
},
{
"docstring": "Labels the json field of the alyx corresponding probe insertion :param folder_probe... | 3 | stack_v2_sparse_classes_30k_train_031523 | Implement the Python class `EphysCellsQc` described below.
Class description:
Implement the EphysCellsQc class.
Method signatures and docstrings:
- def _compute_cell_qc(self, folder_probe): Computes the cell QC given an extracted probe alf path :param folder_probe: folder :return:
- def _label_probe_qc(self, folder_p... | Implement the Python class `EphysCellsQc` described below.
Class description:
Implement the EphysCellsQc class.
Method signatures and docstrings:
- def _compute_cell_qc(self, folder_probe): Computes the cell QC given an extracted probe alf path :param folder_probe: folder :return:
- def _label_probe_qc(self, folder_p... | 61d2c4c945f5d1f42a963c87817e04c7c5bfe1e0 | <|skeleton|>
class EphysCellsQc:
def _compute_cell_qc(self, folder_probe):
"""Computes the cell QC given an extracted probe alf path :param folder_probe: folder :return:"""
<|body_0|>
def _label_probe_qc(self, folder_probe, df_units, drift):
"""Labels the json field of the alyx corresp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EphysCellsQc:
def _compute_cell_qc(self, folder_probe):
"""Computes the cell QC given an extracted probe alf path :param folder_probe: folder :return:"""
_logger.info(f'Computing cluster qc for {folder_probe}')
spikes = alf.io.load_object(folder_probe, 'spikes')
clusters = alf.... | the_stack_v2_python_sparse | ibllib/pipes/ephys_preprocessing.py | LiuDaveLiu/ibllib | train | 0 | |
b254786e0548f41e016ff24f2d06945f28a075b3 | [
"super().__init__()\nself.bn = bn\nself.groups = 1\nself.conv1 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=not self.bn, groups=self.groups)\nself.conv2 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=not self.bn, groups=self.groups)\nif self.bn is True:\n sel... | <|body_start_0|>
super().__init__()
self.bn = bn
self.groups = 1
self.conv1 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=not self.bn, groups=self.groups)
self.conv2 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=not self.bn, g... | Residual convolution module. | ResidualConvUnit_custom | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResidualConvUnit_custom:
"""Residual convolution module."""
def __init__(self, features, activation, bn):
"""Init. Args: features (int): number of features"""
<|body_0|>
def forward(self, x):
"""Forward pass. Args: x (tensor): input Returns: tensor: output"""
... | stack_v2_sparse_classes_75kplus_train_002640 | 7,587 | permissive | [
{
"docstring": "Init. Args: features (int): number of features",
"name": "__init__",
"signature": "def __init__(self, features, activation, bn)"
},
{
"docstring": "Forward pass. Args: x (tensor): input Returns: tensor: output",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_037106 | Implement the Python class `ResidualConvUnit_custom` described below.
Class description:
Residual convolution module.
Method signatures and docstrings:
- def __init__(self, features, activation, bn): Init. Args: features (int): number of features
- def forward(self, x): Forward pass. Args: x (tensor): input Returns: ... | Implement the Python class `ResidualConvUnit_custom` described below.
Class description:
Residual convolution module.
Method signatures and docstrings:
- def __init__(self, features, activation, bn): Init. Args: features (int): number of features
- def forward(self, x): Forward pass. Args: x (tensor): input Returns: ... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class ResidualConvUnit_custom:
"""Residual convolution module."""
def __init__(self, features, activation, bn):
"""Init. Args: features (int): number of features"""
<|body_0|>
def forward(self, x):
"""Forward pass. Args: x (tensor): input Returns: tensor: output"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResidualConvUnit_custom:
"""Residual convolution module."""
def __init__(self, features, activation, bn):
"""Init. Args: features (int): number of features"""
super().__init__()
self.bn = bn
self.groups = 1
self.conv1 = nn.Conv2d(features, features, kernel_size=3, ... | the_stack_v2_python_sparse | ai/modelscope/modelscope/models/cv/text_driven_segmentation/lseg_blocks.py | alldatacenter/alldata | train | 774 |
d646cb1df0afe8fbe23d81f04d56e56be8a4980d | [
"def sumNumbersRec(nd, sum, total):\n sum = sum * 10 + nd.val\n if not nd.left and (not nd.right):\n total.append(sum)\n if nd.left:\n sumNumbersRec(nd.left, sum, total)\n if nd.right:\n sumNumbersRec(nd.right, sum, total)\nif not root:\n return\nret = []\nsumNumbersRec(root, 0, ... | <|body_start_0|>
def sumNumbersRec(nd, sum, total):
sum = sum * 10 + nd.val
if not nd.left and (not nd.right):
total.append(sum)
if nd.left:
sumNumbersRec(nd.left, sum, total)
if nd.right:
sumNumbersRec(nd.right, sum... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sumNumbers1(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def sumNumbers2(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def sumNumbersRec(nd, sum, total):
... | stack_v2_sparse_classes_75kplus_train_002641 | 1,579 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "sumNumbers1",
"signature": "def sumNumbers1(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "sumNumbers2",
"signature": "def sumNumbers2(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_035502 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumNumbers1(self, root): :type root: TreeNode :rtype: int
- def sumNumbers2(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumNumbers1(self, root): :type root: TreeNode :rtype: int
- def sumNumbers2(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def sumNumbers1(s... | d3e8669f932fc2e22711e8b7590d3365d020e189 | <|skeleton|>
class Solution:
def sumNumbers1(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def sumNumbers2(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def sumNumbers1(self, root):
""":type root: TreeNode :rtype: int"""
def sumNumbersRec(nd, sum, total):
sum = sum * 10 + nd.val
if not nd.left and (not nd.right):
total.append(sum)
if nd.left:
sumNumbersRec(nd.left, s... | the_stack_v2_python_sparse | leetcode/129.py | liuweilin17/algorithm | train | 3 | |
d62980def12e68141d151f07296bd48216de0ca8 | [
"left = 0\nright = x // 2 + 1\nwhile left < right:\n mid = left + right + 1 >> 1\n if mid ** 2 > x:\n right = mid - 1\n else:\n left = mid\nreturn int(left)",
"y0 = x // 2 + 1\nwhile y0 ** 2 > x:\n y0 = (y0 + x / y0) / 2\nreturn int(y0)"
] | <|body_start_0|>
left = 0
right = x // 2 + 1
while left < right:
mid = left + right + 1 >> 1
if mid ** 2 > x:
right = mid - 1
else:
left = mid
return int(left)
<|end_body_0|>
<|body_start_1|>
y0 = x // 2 + 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mySqrt_v1(self, x):
"""二分法 :param x: :return:"""
<|body_0|>
def mySqrt_v2(self, x):
"""牛顿迭代法求方程的根 :param x: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
left = 0
right = x // 2 + 1
while left < right:
... | stack_v2_sparse_classes_75kplus_train_002642 | 1,473 | no_license | [
{
"docstring": "二分法 :param x: :return:",
"name": "mySqrt_v1",
"signature": "def mySqrt_v1(self, x)"
},
{
"docstring": "牛顿迭代法求方程的根 :param x: :return:",
"name": "mySqrt_v2",
"signature": "def mySqrt_v2(self, x)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mySqrt_v1(self, x): 二分法 :param x: :return:
- def mySqrt_v2(self, x): 牛顿迭代法求方程的根 :param x: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mySqrt_v1(self, x): 二分法 :param x: :return:
- def mySqrt_v2(self, x): 牛顿迭代法求方程的根 :param x: :return:
<|skeleton|>
class Solution:
def mySqrt_v1(self, x):
"""二分法 :... | 7bf9b992acb5c3db22b52f1ee70816296a41af9d | <|skeleton|>
class Solution:
def mySqrt_v1(self, x):
"""二分法 :param x: :return:"""
<|body_0|>
def mySqrt_v2(self, x):
"""牛顿迭代法求方程的根 :param x: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def mySqrt_v1(self, x):
"""二分法 :param x: :return:"""
left = 0
right = x // 2 + 1
while left < right:
mid = left + right + 1 >> 1
if mid ** 2 > x:
right = mid - 1
else:
left = mid
return int(le... | the_stack_v2_python_sparse | 069Sqrt(x).py | slsefe/leetcode | train | 0 | |
e3017c4032b885296c3ee67c5d64b0e7f8ebf528 | [
"res = ListNode(-1)\nhead = res\nwhile l1 and l2:\n if l2.val < l1.val:\n res.next = l2\n l2 = l2.next\n else:\n res.next = l1\n l1 = l1.next\n res = res.next\nif l2:\n res.next = l2\nif l1:\n res.next = l1\nreturn head.next",
"if l1 is None:\n if l2 is None:\n ... | <|body_start_0|>
res = ListNode(-1)
head = res
while l1 and l2:
if l2.val < l1.val:
res.next = l2
l2 = l2.next
else:
res.next = l1
l1 = l1.next
res = res.next
if l2:
res.next =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_002643 | 1,601 | no_license | [
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "mergeTwoLists",
"signature": "def mergeTwoLists(self, l1, l2)"
},
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "mergeTwoLists",
"signature": "def mergeTwoLists(self, l1, ... | 2 | stack_v2_sparse_classes_30k_train_013887 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
... | a52ab5909a4c94035c80361c5b06f6a06d6de9e1 | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
res = ListNode(-1)
head = res
while l1 and l2:
if l2.val < l1.val:
res.next = l2
l2 = l2.next
else:
re... | the_stack_v2_python_sparse | 21. Merge Two Sorted Lists(Easy).py | iamqingmei/Leetcode-Practice-Python | train | 1 | |
65738d8012f08a3f1f6ce97f214a3d5a732760b9 | [
"gift = get_gifts_by_user_id(user_id)\nschema = GiftSchema(many=True)\nresult = schema.dump(gift).data\nreturn (result, status.HTTP_200_OK)",
"gifts = get_gifts_by_user_id(request.json['user_ids'])\nschema = GiftSchema(many=True)\nresult = schema.dump(gifts).data\nreturn (result, status.HTTP_200_OK)"
] | <|body_start_0|>
gift = get_gifts_by_user_id(user_id)
schema = GiftSchema(many=True)
result = schema.dump(gift).data
return (result, status.HTTP_200_OK)
<|end_body_0|>
<|body_start_1|>
gifts = get_gifts_by_user_id(request.json['user_ids'])
schema = GiftSchema(many=True)
... | Flask-RESTful resource endpoints GiftModel for retrieval by user ID. | GiftByUserId | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GiftByUserId:
"""Flask-RESTful resource endpoints GiftModel for retrieval by user ID."""
def get(self, user_id):
"""Endpoint to return several Gifts from table given a user ID."""
<|body_0|>
def post(self):
"""Endpoint to return several Gifts from table given a l... | stack_v2_sparse_classes_75kplus_train_002644 | 6,785 | no_license | [
{
"docstring": "Endpoint to return several Gifts from table given a user ID.",
"name": "get",
"signature": "def get(self, user_id)"
},
{
"docstring": "Endpoint to return several Gifts from table given a list of user ID's.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | null | Implement the Python class `GiftByUserId` described below.
Class description:
Flask-RESTful resource endpoints GiftModel for retrieval by user ID.
Method signatures and docstrings:
- def get(self, user_id): Endpoint to return several Gifts from table given a user ID.
- def post(self): Endpoint to return several Gifts... | Implement the Python class `GiftByUserId` described below.
Class description:
Flask-RESTful resource endpoints GiftModel for retrieval by user ID.
Method signatures and docstrings:
- def get(self, user_id): Endpoint to return several Gifts from table given a user ID.
- def post(self): Endpoint to return several Gifts... | d5ffcc5d276692d1578cea704125b1b3952beb1c | <|skeleton|>
class GiftByUserId:
"""Flask-RESTful resource endpoints GiftModel for retrieval by user ID."""
def get(self, user_id):
"""Endpoint to return several Gifts from table given a user ID."""
<|body_0|>
def post(self):
"""Endpoint to return several Gifts from table given a l... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GiftByUserId:
"""Flask-RESTful resource endpoints GiftModel for retrieval by user ID."""
def get(self, user_id):
"""Endpoint to return several Gifts from table given a user ID."""
gift = get_gifts_by_user_id(user_id)
schema = GiftSchema(many=True)
result = schema.dump(gift... | the_stack_v2_python_sparse | application/resources/gift.py | transreductionist/API-Project-1 | train | 0 |
73d67deb2b33517744f2fa03192e41fa115352de | [
"recipe = {'flour': 500, 'sugar': 200, 'eggs': 1}\navailable = {'flour': 1200, 'sugar': 1200, 'eggs': 5, 'milk': 200}\nself.assertEqual(main.cakes(recipe, available), 2)",
"recipe = {'apples': 3, 'flour': 300, 'sugar': 150, 'milk': 100, 'oil': 100}\navailable = {'sugar': 500, 'flour': 2000, 'milk': 2000}\nself.as... | <|body_start_0|>
recipe = {'flour': 500, 'sugar': 200, 'eggs': 1}
available = {'flour': 1200, 'sugar': 1200, 'eggs': 5, 'milk': 200}
self.assertEqual(main.cakes(recipe, available), 2)
<|end_body_0|>
<|body_start_1|>
recipe = {'apples': 3, 'flour': 300, 'sugar': 150, 'milk': 100, 'oil': ... | SampleTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SampleTests:
def test_extra_stock(self):
"""Should ignore extra available ingredients"""
<|body_0|>
def test_missing_ingredient(self):
"""Should count missing available ingredients as 0"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
recipe = {'flou... | stack_v2_sparse_classes_75kplus_train_002645 | 718 | no_license | [
{
"docstring": "Should ignore extra available ingredients",
"name": "test_extra_stock",
"signature": "def test_extra_stock(self)"
},
{
"docstring": "Should count missing available ingredients as 0",
"name": "test_missing_ingredient",
"signature": "def test_missing_ingredient(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_037850 | Implement the Python class `SampleTests` described below.
Class description:
Implement the SampleTests class.
Method signatures and docstrings:
- def test_extra_stock(self): Should ignore extra available ingredients
- def test_missing_ingredient(self): Should count missing available ingredients as 0 | Implement the Python class `SampleTests` described below.
Class description:
Implement the SampleTests class.
Method signatures and docstrings:
- def test_extra_stock(self): Should ignore extra available ingredients
- def test_missing_ingredient(self): Should count missing available ingredients as 0
<|skeleton|>
cla... | 48b27bca47133357be68735e68b97e68e36246be | <|skeleton|>
class SampleTests:
def test_extra_stock(self):
"""Should ignore extra available ingredients"""
<|body_0|>
def test_missing_ingredient(self):
"""Should count missing available ingredients as 0"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SampleTests:
def test_extra_stock(self):
"""Should ignore extra available ingredients"""
recipe = {'flour': 500, 'sugar': 200, 'eggs': 1}
available = {'flour': 1200, 'sugar': 1200, 'eggs': 5, 'milk': 200}
self.assertEqual(main.cakes(recipe, available), 2)
def test_missing_... | the_stack_v2_python_sparse | @Codewars/5_pete-the-baker/tests.py | hosmanadam/coding-challenges | train | 0 | |
da9d2935acaf59f8ead8104da1267d06d8216b4c | [
"self.plain_modulus = params.plain_modulus\nself.coeff_modulus = params.ciph_modulus\nself.scaling_factor = params.scaling_factor",
"assert isinstance(ciph1, Ciphertext)\nassert isinstance(ciph2, Ciphertext)\nnew_ciph_c0 = ciph1.c0.add(ciph2.c0, self.coeff_modulus)\nnew_ciph_c1 = ciph1.c1.add(ciph2.c1, self.coeff... | <|body_start_0|>
self.plain_modulus = params.plain_modulus
self.coeff_modulus = params.ciph_modulus
self.scaling_factor = params.scaling_factor
<|end_body_0|>
<|body_start_1|>
assert isinstance(ciph1, Ciphertext)
assert isinstance(ciph2, Ciphertext)
new_ciph_c0 = ciph1.c... | An instance of an evaluator for ciphertexts. This allows us to add, multiply, and relinearize ciphertexts. Attributes: plain_modulus (int): Coefficient modulus of plaintexts (t). coeff_modulus (int): Modulus q of coefficients of polynomial ring R_q. | BFVEvaluator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BFVEvaluator:
"""An instance of an evaluator for ciphertexts. This allows us to add, multiply, and relinearize ciphertexts. Attributes: plain_modulus (int): Coefficient modulus of plaintexts (t). coeff_modulus (int): Modulus q of coefficients of polynomial ring R_q."""
def __init__(self, par... | stack_v2_sparse_classes_75kplus_train_002646 | 3,484 | permissive | [
{
"docstring": "Inits Evaluator. Args: params (Parameters): Parameters including polynomial degree, plaintext modulus, and ciphertext modulus.",
"name": "__init__",
"signature": "def __init__(self, params)"
},
{
"docstring": "Adds two ciphertexts. Adds two ciphertexts within the context. Args: c... | 4 | null | Implement the Python class `BFVEvaluator` described below.
Class description:
An instance of an evaluator for ciphertexts. This allows us to add, multiply, and relinearize ciphertexts. Attributes: plain_modulus (int): Coefficient modulus of plaintexts (t). coeff_modulus (int): Modulus q of coefficients of polynomial r... | Implement the Python class `BFVEvaluator` described below.
Class description:
An instance of an evaluator for ciphertexts. This allows us to add, multiply, and relinearize ciphertexts. Attributes: plain_modulus (int): Coefficient modulus of plaintexts (t). coeff_modulus (int): Modulus q of coefficients of polynomial r... | be700505547b81671c37026e55c4eefbd44dcaae | <|skeleton|>
class BFVEvaluator:
"""An instance of an evaluator for ciphertexts. This allows us to add, multiply, and relinearize ciphertexts. Attributes: plain_modulus (int): Coefficient modulus of plaintexts (t). coeff_modulus (int): Modulus q of coefficients of polynomial ring R_q."""
def __init__(self, par... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BFVEvaluator:
"""An instance of an evaluator for ciphertexts. This allows us to add, multiply, and relinearize ciphertexts. Attributes: plain_modulus (int): Coefficient modulus of plaintexts (t). coeff_modulus (int): Modulus q of coefficients of polynomial ring R_q."""
def __init__(self, params):
... | the_stack_v2_python_sparse | bfv/bfv_evaluator.py | seounghwan-oh/py_FHE_for_homomorphic_encryption | train | 3 |
40debfad93fba56e264e84ce4dab1576eb93df89 | [
"super().__init__()\nself.group_authority = group_authority\nself.default_authority = default_authority",
"appstruct = super().validate(data)\nappstruct = self._whitelisted_fields_only(appstruct)\nself._validate_groupid(appstruct)\nreturn appstruct",
"groupid = appstruct.get('groupid', None)\nif groupid is None... | <|body_start_0|>
super().__init__()
self.group_authority = group_authority
self.default_authority = default_authority
<|end_body_0|>
<|body_start_1|>
appstruct = super().validate(data)
appstruct = self._whitelisted_fields_only(appstruct)
self._validate_groupid(appstruct)... | Base class for validating group resource API data. | GroupAPISchema | [
"BSD-2-Clause",
"BSD-3-Clause",
"BSD-2-Clause-Views"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupAPISchema:
"""Base class for validating group resource API data."""
def __init__(self, group_authority=None, default_authority=None):
"""Initialize a new group schema instance. The ``group_authority`` and ``default_authority`` args are used for validating any ``groupid`` present... | stack_v2_sparse_classes_75kplus_train_002647 | 4,250 | permissive | [
{
"docstring": "Initialize a new group schema instance. The ``group_authority`` and ``default_authority`` args are used for validating any ``groupid`` present in the data being validated. :arg group_authority: The authority associated with the group resource. (default None) :arg default_authority: The service's... | 4 | null | Implement the Python class `GroupAPISchema` described below.
Class description:
Base class for validating group resource API data.
Method signatures and docstrings:
- def __init__(self, group_authority=None, default_authority=None): Initialize a new group schema instance. The ``group_authority`` and ``default_authori... | Implement the Python class `GroupAPISchema` described below.
Class description:
Base class for validating group resource API data.
Method signatures and docstrings:
- def __init__(self, group_authority=None, default_authority=None): Initialize a new group schema instance. The ``group_authority`` and ``default_authori... | 232446d776fdb906d2fb253cf0a409c6813a08d6 | <|skeleton|>
class GroupAPISchema:
"""Base class for validating group resource API data."""
def __init__(self, group_authority=None, default_authority=None):
"""Initialize a new group schema instance. The ``group_authority`` and ``default_authority`` args are used for validating any ``groupid`` present... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GroupAPISchema:
"""Base class for validating group resource API data."""
def __init__(self, group_authority=None, default_authority=None):
"""Initialize a new group schema instance. The ``group_authority`` and ``default_authority`` args are used for validating any ``groupid`` present in the data ... | the_stack_v2_python_sparse | h/schemas/api/group.py | hypothesis/h | train | 2,558 |
b7862cff3acf7f167240ce999417ead2d257e66e | [
"if not grid:\n return 0\nrows, cols = (len(grid), len(grid[0]))\ntotal_islands = 0\nq = deque()\n\ndef bfs(grid: List[List[int]], q: 'deque'):\n while q:\n row, col = q.popleft()\n for dr, dc in ((row + 1, col), (row - 1, col), (row, col + 1), (row, col - 1)):\n if 0 <= dr < rows and... | <|body_start_0|>
if not grid:
return 0
rows, cols = (len(grid), len(grid[0]))
total_islands = 0
q = deque()
def bfs(grid: List[List[int]], q: 'deque'):
while q:
row, col = q.popleft()
for dr, dc in ((row + 1, col), (row - 1... | Islands | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Islands:
def total_number_bfs(self, grid: List[List[int]]) -> int:
"""Approach: BFS Time Complexity: O(M * N) Space Complexity: O(min(M,N)) :param grid: :return:"""
<|body_0|>
def total_number_dfs(self, grid: List[List[int]]) -> int:
"""Approach: DFS Time Complexity:... | stack_v2_sparse_classes_75kplus_train_002648 | 2,849 | no_license | [
{
"docstring": "Approach: BFS Time Complexity: O(M * N) Space Complexity: O(min(M,N)) :param grid: :return:",
"name": "total_number_bfs",
"signature": "def total_number_bfs(self, grid: List[List[int]]) -> int"
},
{
"docstring": "Approach: DFS Time Complexity: O(M * N) Space Complexity: O(M * N) ... | 2 | stack_v2_sparse_classes_30k_train_034305 | Implement the Python class `Islands` described below.
Class description:
Implement the Islands class.
Method signatures and docstrings:
- def total_number_bfs(self, grid: List[List[int]]) -> int: Approach: BFS Time Complexity: O(M * N) Space Complexity: O(min(M,N)) :param grid: :return:
- def total_number_dfs(self, g... | Implement the Python class `Islands` described below.
Class description:
Implement the Islands class.
Method signatures and docstrings:
- def total_number_bfs(self, grid: List[List[int]]) -> int: Approach: BFS Time Complexity: O(M * N) Space Complexity: O(min(M,N)) :param grid: :return:
- def total_number_dfs(self, g... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Islands:
def total_number_bfs(self, grid: List[List[int]]) -> int:
"""Approach: BFS Time Complexity: O(M * N) Space Complexity: O(min(M,N)) :param grid: :return:"""
<|body_0|>
def total_number_dfs(self, grid: List[List[int]]) -> int:
"""Approach: DFS Time Complexity:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Islands:
def total_number_bfs(self, grid: List[List[int]]) -> int:
"""Approach: BFS Time Complexity: O(M * N) Space Complexity: O(min(M,N)) :param grid: :return:"""
if not grid:
return 0
rows, cols = (len(grid), len(grid[0]))
total_islands = 0
q = deque()
... | the_stack_v2_python_sparse | goldman_sachs/number_of_islands.py | Shiv2157k/leet_code | train | 1 | |
97c1d21673a3f3af25871d2cc9bdd69d6603d0a7 | [
"self.L = L\nself.E = E\nself.I = I\nself.G = G\nself.kA = kA",
"g = 6 * self.E * self.I / (self.kA * self.G * self.L * self.L)\nCOF_fixed = (1 - g) / (2 + g)\nCOF = [i * COF_fixed for i in fixed]\nreturn COF",
"g = 6 * self.E * self.I / (self.kA * self.G * self.L * self.L)\nK_farfixed = 4 * self.E * self.I / s... | <|body_start_0|>
self.L = L
self.E = E
self.I = I
self.G = G
self.kA = kA
<|end_body_0|>
<|body_start_1|>
g = 6 * self.E * self.I / (self.kA * self.G * self.L * self.L)
COF_fixed = (1 - g) / (2 + g)
COF = [i * COF_fixed for i in fixed]
return COF
... | TimoshenkoBeam | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimoshenkoBeam:
def __init__(L, E, I, G, kA):
"""Timoshenko General form equations for beam stiffness and carry over factors ** Maintain consistent units among the inputs ** L = beam span E = beam modulus of elastacity I = beam second moment of area about the axis of bending G = beam she... | stack_v2_sparse_classes_75kplus_train_002649 | 22,585 | permissive | [
{
"docstring": "Timoshenko General form equations for beam stiffness and carry over factors ** Maintain consistent units among the inputs ** L = beam span E = beam modulus of elastacity I = beam second moment of area about the axis of bending G = beam shear modulus kA = beam shear area, typically the beam web a... | 3 | stack_v2_sparse_classes_30k_train_002909 | Implement the Python class `TimoshenkoBeam` described below.
Class description:
Implement the TimoshenkoBeam class.
Method signatures and docstrings:
- def __init__(L, E, I, G, kA): Timoshenko General form equations for beam stiffness and carry over factors ** Maintain consistent units among the inputs ** L = beam sp... | Implement the Python class `TimoshenkoBeam` described below.
Class description:
Implement the TimoshenkoBeam class.
Method signatures and docstrings:
- def __init__(L, E, I, G, kA): Timoshenko General form equations for beam stiffness and carry over factors ** Maintain consistent units among the inputs ** L = beam sp... | 47b025d7482461f7ee55b036f60c16a937b8d203 | <|skeleton|>
class TimoshenkoBeam:
def __init__(L, E, I, G, kA):
"""Timoshenko General form equations for beam stiffness and carry over factors ** Maintain consistent units among the inputs ** L = beam span E = beam modulus of elastacity I = beam second moment of area about the axis of bending G = beam she... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TimoshenkoBeam:
def __init__(L, E, I, G, kA):
"""Timoshenko General form equations for beam stiffness and carry over factors ** Maintain consistent units among the inputs ** L = beam span E = beam modulus of elastacity I = beam second moment of area about the axis of bending G = beam shear modulus kA ... | the_stack_v2_python_sparse | Analysis/TimoshenkoFormulas.py | Gia869/Structural-Engineering | train | 0 | |
de77408c3bab0a168edb61fd51b4c970c5e26fdd | [
"self.tau = p['tau']\nself.Tbase = p['Tbase']\nself.Smax = p['smax']\nself.fmin = p['fmin']\nself.X = p['Xo']\nself.f = 1.0",
"self.X = self.X + 1.0 / self.tau * (T - self.X)\nS = np.maximum(self.X - self.Tbase, 0.0)\nself.f = np.maximum(self.fmin, np.minimum(S / (self.Smax - self.Tbase), 1.0))\nif out:\n retu... | <|body_start_0|>
self.tau = p['tau']
self.Tbase = p['Tbase']
self.Smax = p['smax']
self.fmin = p['fmin']
self.X = p['Xo']
self.f = 1.0
<|end_body_0|>
<|body_start_1|>
self.X = self.X + 1.0 / self.tau * (T - self.X)
S = np.maximum(self.X - self.Tbase, 0.0)... | Seasonal cycle of photosynthetic machinery. References: Kolari et al. 2007 Tellus. | Photo_cycle | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Photo_cycle:
"""Seasonal cycle of photosynthetic machinery. References: Kolari et al. 2007 Tellus."""
def __init__(self, p):
"""Initializes photo cycle model. Args: p (dict): 'Xo': initial delayed temperature [degC] 'fmin': minimum photocapacity [-] 'Tbase': base temperature [degC] '... | stack_v2_sparse_classes_75kplus_train_002650 | 5,757 | no_license | [
{
"docstring": "Initializes photo cycle model. Args: p (dict): 'Xo': initial delayed temperature [degC] 'fmin': minimum photocapacity [-] 'Tbase': base temperature [degC] 'tau': time constant [days] 'smax': threshold for full acclimation [degC] Returns: self (object)",
"name": "__init__",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_017120 | Implement the Python class `Photo_cycle` described below.
Class description:
Seasonal cycle of photosynthetic machinery. References: Kolari et al. 2007 Tellus.
Method signatures and docstrings:
- def __init__(self, p): Initializes photo cycle model. Args: p (dict): 'Xo': initial delayed temperature [degC] 'fmin': min... | Implement the Python class `Photo_cycle` described below.
Class description:
Seasonal cycle of photosynthetic machinery. References: Kolari et al. 2007 Tellus.
Method signatures and docstrings:
- def __init__(self, p): Initializes photo cycle model. Args: p (dict): 'Xo': initial delayed temperature [degC] 'fmin': min... | c662ad355af798b5036c3b080dafcb39728b969c | <|skeleton|>
class Photo_cycle:
"""Seasonal cycle of photosynthetic machinery. References: Kolari et al. 2007 Tellus."""
def __init__(self, p):
"""Initializes photo cycle model. Args: p (dict): 'Xo': initial delayed temperature [degC] 'fmin': minimum photocapacity [-] 'Tbase': base temperature [degC] '... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Photo_cycle:
"""Seasonal cycle of photosynthetic machinery. References: Kolari et al. 2007 Tellus."""
def __init__(self, p):
"""Initializes photo cycle model. Args: p (dict): 'Xo': initial delayed temperature [degC] 'fmin': minimum photocapacity [-] 'Tbase': base temperature [degC] 'tau': time co... | the_stack_v2_python_sparse | canopy/planttype/phenology.py | zmoon/pyAPES_skeleton | train | 0 |
efe029700f5bd48612b484882f0964419a24bb77 | [
"modellist = ioUtils.getModelListForEnumProp(self, context)\nif len(modellist) > 1:\n return context.window_manager.invoke_props_dialog(self)\nelif modellist:\n self.modelname = modellist[0][0]\n return self.execute(context)\nlog('No properly defined models to export.', 'ERROR')\nreturn {'CANCELLED'}",
"... | <|body_start_0|>
modellist = ioUtils.getModelListForEnumProp(self, context)
if len(modellist) > 1:
return context.window_manager.invoke_props_dialog(self)
elif modellist:
self.modelname = modellist[0][0]
return self.execute(context)
log('No properly de... | Export the selected model | ExportModelOperator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExportModelOperator:
"""Export the selected model"""
def invoke(self, context, event):
"""Args: context: event: Returns:"""
<|body_0|>
def exportModel(self, root, exportpath='.'):
"""Exports model to a given path in the provided formats. Args: model(dict): dictio... | stack_v2_sparse_classes_75kplus_train_002651 | 34,326 | permissive | [
{
"docstring": "Args: context: event: Returns:",
"name": "invoke",
"signature": "def invoke(self, context, event)"
},
{
"docstring": "Exports model to a given path in the provided formats. Args: model(dict): dictionary of model to export exportpath(str, optional): path to export root (Default va... | 3 | stack_v2_sparse_classes_30k_train_009640 | Implement the Python class `ExportModelOperator` described below.
Class description:
Export the selected model
Method signatures and docstrings:
- def invoke(self, context, event): Args: context: event: Returns:
- def exportModel(self, root, exportpath='.'): Exports model to a given path in the provided formats. Args... | Implement the Python class `ExportModelOperator` described below.
Class description:
Export the selected model
Method signatures and docstrings:
- def invoke(self, context, event): Args: context: event: Returns:
- def exportModel(self, root, exportpath='.'): Exports model to a given path in the provided formats. Args... | 543d220c65bbee0e23e810d89307e23aa79eb0cd | <|skeleton|>
class ExportModelOperator:
"""Export the selected model"""
def invoke(self, context, event):
"""Args: context: event: Returns:"""
<|body_0|>
def exportModel(self, root, exportpath='.'):
"""Exports model to a given path in the provided formats. Args: model(dict): dictio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExportModelOperator:
"""Export the selected model"""
def invoke(self, context, event):
"""Args: context: event: Returns:"""
modellist = ioUtils.getModelListForEnumProp(self, context)
if len(modellist) > 1:
return context.window_manager.invoke_props_dialog(self)
... | the_stack_v2_python_sparse | phobos/blender/operators/io.py | dfki-ric/phobos | train | 483 |
89a838dffff6e60727cef10e8319fb38e84662f9 | [
"img_feats = self.extract_feat(img=img, img_metas=img_metas)\nlosses = dict()\nlosses_pts = self.forward_pts_train(img_feats, gt_bboxes_3d, gt_labels_3d, img_metas, gt_bboxes_ignore, prev_bev=prev_bev)\nlosses.update(losses_pts)\nreturn losses",
"img = data['img']\nimg_metas = data['img_metas']\nimg_feats = self.... | <|body_start_0|>
img_feats = self.extract_feat(img=img, img_metas=img_metas)
losses = dict()
losses_pts = self.forward_pts_train(img_feats, gt_bboxes_3d, gt_labels_3d, img_metas, gt_bboxes_ignore, prev_bev=prev_bev)
losses.update(losses_pts)
return losses
<|end_body_0|>
<|body_s... | The default version BEVFormer currently can not support FP16. We provide this version to resolve this issue. | BEVFormer_fp16 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BEVFormer_fp16:
"""The default version BEVFormer currently can not support FP16. We provide this version to resolve this issue."""
def forward_train(self, points=None, img_metas=None, gt_bboxes_3d=None, gt_labels_3d=None, gt_labels=None, gt_bboxes=None, img=None, proposals=None, gt_bboxes_ig... | stack_v2_sparse_classes_75kplus_train_002652 | 3,721 | permissive | [
{
"docstring": "Forward training function. Args: points (list[torch.Tensor], optional): Points of each sample. Defaults to None. img_metas (list[dict], optional): Meta information of each sample. Defaults to None. gt_bboxes_3d (list[:obj:`BaseInstance3DBoxes`], optional): Ground truth 3D boxes. Defaults to None... | 2 | stack_v2_sparse_classes_30k_train_053340 | Implement the Python class `BEVFormer_fp16` described below.
Class description:
The default version BEVFormer currently can not support FP16. We provide this version to resolve this issue.
Method signatures and docstrings:
- def forward_train(self, points=None, img_metas=None, gt_bboxes_3d=None, gt_labels_3d=None, gt... | Implement the Python class `BEVFormer_fp16` described below.
Class description:
The default version BEVFormer currently can not support FP16. We provide this version to resolve this issue.
Method signatures and docstrings:
- def forward_train(self, points=None, img_metas=None, gt_bboxes_3d=None, gt_labels_3d=None, gt... | feb0664e64684d3207859279f047fa54a1a806f6 | <|skeleton|>
class BEVFormer_fp16:
"""The default version BEVFormer currently can not support FP16. We provide this version to resolve this issue."""
def forward_train(self, points=None, img_metas=None, gt_bboxes_3d=None, gt_labels_3d=None, gt_labels=None, gt_bboxes=None, img=None, proposals=None, gt_bboxes_ig... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BEVFormer_fp16:
"""The default version BEVFormer currently can not support FP16. We provide this version to resolve this issue."""
def forward_train(self, points=None, img_metas=None, gt_bboxes_3d=None, gt_labels_3d=None, gt_labels=None, gt_bboxes=None, img=None, proposals=None, gt_bboxes_ignore=None, im... | the_stack_v2_python_sparse | projects/mmdet3d_plugin/bevformer/detectors/bevformer_fp16.py | hustvl/MapTR | train | 643 |
46e7617348762a678a05c95443a1129100038251 | [
"A = sum(nums)\nif A % 2 == 1:\n return False\na = A // 2\nself.nums = sorted(nums, reverse=True)\n\ndef dfs(a, count):\n if count >= len(self.nums):\n return False\n b = self.nums[count]\n if a - b == 0:\n return True\n if a - b < 0:\n return False\n if dfs(a - b, count + 1):... | <|body_start_0|>
A = sum(nums)
if A % 2 == 1:
return False
a = A // 2
self.nums = sorted(nums, reverse=True)
def dfs(a, count):
if count >= len(self.nums):
return False
b = self.nums[count]
if a - b == 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canPartition(self, nums):
""":type nums: List[int] :rtype: bool 48ms"""
<|body_0|>
def canPartition_1(self, nums):
""":type nums: List[int] :rtype: bool 865ms"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
A = sum(nums)
if A %... | stack_v2_sparse_classes_75kplus_train_002653 | 2,235 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool 48ms",
"name": "canPartition",
"signature": "def canPartition(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: bool 865ms",
"name": "canPartition_1",
"signature": "def canPartition_1(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_033449 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canPartition(self, nums): :type nums: List[int] :rtype: bool 48ms
- def canPartition_1(self, nums): :type nums: List[int] :rtype: bool 865ms | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canPartition(self, nums): :type nums: List[int] :rtype: bool 48ms
- def canPartition_1(self, nums): :type nums: List[int] :rtype: bool 865ms
<|skeleton|>
class Solution:
... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def canPartition(self, nums):
""":type nums: List[int] :rtype: bool 48ms"""
<|body_0|>
def canPartition_1(self, nums):
""":type nums: List[int] :rtype: bool 865ms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def canPartition(self, nums):
""":type nums: List[int] :rtype: bool 48ms"""
A = sum(nums)
if A % 2 == 1:
return False
a = A // 2
self.nums = sorted(nums, reverse=True)
def dfs(a, count):
if count >= len(self.nums):
... | the_stack_v2_python_sparse | PartitionEqualSubsetSum_MID_416.py | 953250587/leetcode-python | train | 2 | |
e7c06cc84f7c385ed0ad2e842cb762455e0c8214 | [
"res = ''\nfor i in range(len(strs)):\n new_str = ','.join([str(ord(c)) for c in strs[i]])\n res = res + ':' + new_str\nreturn res",
"if len(s) == 0:\n return []\nif s == ':':\n return ['']\nenc_strs = s.split(':')\nres = []\nfor i in range(1, len(enc_strs)):\n if len(enc_strs[i]) == 0:\n re... | <|body_start_0|>
res = ''
for i in range(len(strs)):
new_str = ','.join([str(ord(c)) for c in strs[i]])
res = res + ':' + new_str
return res
<|end_body_0|>
<|body_start_1|>
if len(s) == 0:
return []
if s == ':':
return ['']
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
<|body_0|>
def decode(self, s: str) -> [str]:
"""Decodes a single string to a list of strings."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = ''
... | stack_v2_sparse_classes_75kplus_train_002654 | 1,491 | no_license | [
{
"docstring": "Encodes a list of strings to a single string.",
"name": "encode",
"signature": "def encode(self, strs: [str]) -> str"
},
{
"docstring": "Decodes a single string to a list of strings.",
"name": "decode",
"signature": "def decode(self, s: str) -> [str]"
}
] | 2 | stack_v2_sparse_classes_30k_train_044304 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs: [str]) -> str: Encodes a list of strings to a single string.
- def decode(self, s: str) -> [str]: Decodes a single string to a list of strings. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs: [str]) -> str: Encodes a list of strings to a single string.
- def decode(self, s: str) -> [str]: Decodes a single string to a list of strings.
<|skeleton|>
cla... | 9cef9b11e16412449a46312d766f7eafcf162724 | <|skeleton|>
class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
<|body_0|>
def decode(self, s: str) -> [str]:
"""Decodes a single string to a list of strings."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
res = ''
for i in range(len(strs)):
new_str = ','.join([str(ord(c)) for c in strs[i]])
res = res + ':' + new_str
return res
def decode(self, s: str) -> ... | the_stack_v2_python_sparse | 271-Encode-and-Decode-Strings.py | zuqqhi2/my-leetcode-answers | train | 0 | |
09b97aed0991099d58d87bc3c2f01ce25eb3db39 | [
"super(DuelingNetworkMLP3, self).__init__()\nself._device = device\nself.fc1 = nn.Linear(in_features=n_states, out_features=n_hiddens).to(self._device)\nself.fc2 = nn.Linear(in_features=n_hiddens, out_features=n_hiddens).to(self._device)\nself.fc3_adv = nn.Linear(in_features=n_hiddens, out_features=n_actions).to(se... | <|body_start_0|>
super(DuelingNetworkMLP3, self).__init__()
self._device = device
self.fc1 = nn.Linear(in_features=n_states, out_features=n_hiddens).to(self._device)
self.fc2 = nn.Linear(in_features=n_hiddens, out_features=n_hiddens).to(self._device)
self.fc3_adv = nn.Linear(in_f... | Dueling Network のネットワーク構成 PyTorch の nn.Module を継承して実装 [public] fc1 : [nn.Linear] 入力層 fc2 : [nn.Linear] 隠れ層 fc3_adv : [nn.Linear] アドバンテージ関数のネットワーク fc3_vfunc : [nn.Linear] 状態価値関数のネットワーク | DuelingNetworkMLP3 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DuelingNetworkMLP3:
"""Dueling Network のネットワーク構成 PyTorch の nn.Module を継承して実装 [public] fc1 : [nn.Linear] 入力層 fc2 : [nn.Linear] 隠れ層 fc3_adv : [nn.Linear] アドバンテージ関数のネットワーク fc3_vfunc : [nn.Linear] 状態価値関数のネットワーク"""
def __init__(self, device, n_states, n_hiddens, n_actions):
"""[Args] devi... | stack_v2_sparse_classes_75kplus_train_002655 | 2,523 | no_license | [
{
"docstring": "[Args] device : 使用デバイス n_states : 状態数 |S| / 入力ノード数に対応する。 n_actions : 状態数 |A| / 出力ノード数に対応する。",
"name": "__init__",
"signature": "def __init__(self, device, n_states, n_hiddens, n_actions)"
},
{
"docstring": "ネットワークの順方向での更新処理",
"name": "forward",
"signature": "def forward(s... | 2 | stack_v2_sparse_classes_30k_train_026898 | Implement the Python class `DuelingNetworkMLP3` described below.
Class description:
Dueling Network のネットワーク構成 PyTorch の nn.Module を継承して実装 [public] fc1 : [nn.Linear] 入力層 fc2 : [nn.Linear] 隠れ層 fc3_adv : [nn.Linear] アドバンテージ関数のネットワーク fc3_vfunc : [nn.Linear] 状態価値関数のネットワーク
Method signatures and docstrings:
- def __init__(s... | Implement the Python class `DuelingNetworkMLP3` described below.
Class description:
Dueling Network のネットワーク構成 PyTorch の nn.Module を継承して実装 [public] fc1 : [nn.Linear] 入力層 fc2 : [nn.Linear] 隠れ層 fc3_adv : [nn.Linear] アドバンテージ関数のネットワーク fc3_vfunc : [nn.Linear] 状態価値関数のネットワーク
Method signatures and docstrings:
- def __init__(s... | b0bae63db6183cbaee15d6a96499e40c482a517d | <|skeleton|>
class DuelingNetworkMLP3:
"""Dueling Network のネットワーク構成 PyTorch の nn.Module を継承して実装 [public] fc1 : [nn.Linear] 入力層 fc2 : [nn.Linear] 隠れ層 fc3_adv : [nn.Linear] アドバンテージ関数のネットワーク fc3_vfunc : [nn.Linear] 状態価値関数のネットワーク"""
def __init__(self, device, n_states, n_hiddens, n_actions):
"""[Args] devi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DuelingNetworkMLP3:
"""Dueling Network のネットワーク構成 PyTorch の nn.Module を継承して実装 [public] fc1 : [nn.Linear] 入力層 fc2 : [nn.Linear] 隠れ層 fc3_adv : [nn.Linear] アドバンテージ関数のネットワーク fc3_vfunc : [nn.Linear] 状態価値関数のネットワーク"""
def __init__(self, device, n_states, n_hiddens, n_actions):
"""[Args] device : 使用デバイス n... | the_stack_v2_python_sparse | CartPole_DuelingNetwork_PyTorch_OpenAIGym/DuelingNetworkMLP3.py | Yagami360/ReinforcementLearning_Exercises | train | 14 |
b02731c023ebcd482e6c7c373ccf73c39226f136 | [
"self._attribute_details = CallableAttributeDetails(name=policy.name, owner_subtype_of=policy.subtype_of)\ncallable_policy = policy.policy\nself._arg_get = HandlerSubjectArgGet(name=callable_policy.subject_arg)\nself._handler_create = CallableHandlerCreate(subject_as_keyword=callable_policy.subject_as_keyword, arg_... | <|body_start_0|>
self._attribute_details = CallableAttributeDetails(name=policy.name, owner_subtype_of=policy.subtype_of)
callable_policy = policy.policy
self._arg_get = HandlerSubjectArgGet(name=callable_policy.subject_arg)
self._handler_create = CallableHandlerCreate(subject_as_keyword... | Method handler factory. Factory that produces callable handler from given object attribute - in most cases method. | MethodHandlerFactory | [
"Python-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MethodHandlerFactory:
"""Method handler factory. Factory that produces callable handler from given object attribute - in most cases method."""
def __init__(self, policy: MethodHandlerPolicy):
"""Initializes method handler factory. :param policy: policy used as a configuration or spec... | stack_v2_sparse_classes_75kplus_train_002656 | 3,167 | permissive | [
{
"docstring": "Initializes method handler factory. :param policy: policy used as a configuration or specification for producing handler object",
"name": "__init__",
"signature": "def __init__(self, policy: MethodHandlerPolicy)"
},
{
"docstring": "Creates handler from given object attribute acco... | 2 | stack_v2_sparse_classes_30k_train_051434 | Implement the Python class `MethodHandlerFactory` described below.
Class description:
Method handler factory. Factory that produces callable handler from given object attribute - in most cases method.
Method signatures and docstrings:
- def __init__(self, policy: MethodHandlerPolicy): Initializes method handler facto... | Implement the Python class `MethodHandlerFactory` described below.
Class description:
Method handler factory. Factory that produces callable handler from given object attribute - in most cases method.
Method signatures and docstrings:
- def __init__(self, policy: MethodHandlerPolicy): Initializes method handler facto... | 0e09c18187fcd7a68dcdec3056608370ea1da75e | <|skeleton|>
class MethodHandlerFactory:
"""Method handler factory. Factory that produces callable handler from given object attribute - in most cases method."""
def __init__(self, policy: MethodHandlerPolicy):
"""Initializes method handler factory. :param policy: policy used as a configuration or spec... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MethodHandlerFactory:
"""Method handler factory. Factory that produces callable handler from given object attribute - in most cases method."""
def __init__(self, policy: MethodHandlerPolicy):
"""Initializes method handler factory. :param policy: policy used as a configuration or specification for... | the_stack_v2_python_sparse | mediator/common/factory/factories.py | dlski/python-mediator | train | 27 |
0b9cd0d01da410a04ebc31793f743600d9781df4 | [
"is_batched = True if isinstance(text, (list, tuple)) else False\nif not is_batched:\n text = [text]\nresult = []\nfor t in text:\n if isinstance(t, str):\n bstr = t.encode()\n else:\n bstr = t\n result.append(self._tokenize(bstr, add_bos))\nif not is_batched:\n result = result[0]\nretu... | <|body_start_0|>
is_batched = True if isinstance(text, (list, tuple)) else False
if not is_batched:
text = [text]
result = []
for t in text:
if isinstance(t, str):
bstr = t.encode()
else:
bstr = t
result.appe... | A class containing all functions for auto-regressive text generation Pass custom parameter values to 'generate' . | GenerationMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenerationMixin:
"""A class containing all functions for auto-regressive text generation Pass custom parameter values to 'generate' ."""
def tokenize(self, text: Union[str, List[str]], add_bos: bool=True) -> List[int]:
"""Decode the id to words :param text: The text or batch of text ... | stack_v2_sparse_classes_75kplus_train_002657 | 6,354 | permissive | [
{
"docstring": "Decode the id to words :param text: The text or batch of text to be tokenized :param add_bos: :return: list of ids that indicates the tokens",
"name": "tokenize",
"signature": "def tokenize(self, text: Union[str, List[str]], add_bos: bool=True) -> List[int]"
},
{
"docstring": "De... | 4 | stack_v2_sparse_classes_30k_train_054034 | Implement the Python class `GenerationMixin` described below.
Class description:
A class containing all functions for auto-regressive text generation Pass custom parameter values to 'generate' .
Method signatures and docstrings:
- def tokenize(self, text: Union[str, List[str]], add_bos: bool=True) -> List[int]: Decod... | Implement the Python class `GenerationMixin` described below.
Class description:
A class containing all functions for auto-regressive text generation Pass custom parameter values to 'generate' .
Method signatures and docstrings:
- def tokenize(self, text: Union[str, List[str]], add_bos: bool=True) -> List[int]: Decod... | 4ffa012a426e0d16ed13b707b03d8787ddca6aa4 | <|skeleton|>
class GenerationMixin:
"""A class containing all functions for auto-regressive text generation Pass custom parameter values to 'generate' ."""
def tokenize(self, text: Union[str, List[str]], add_bos: bool=True) -> List[int]:
"""Decode the id to words :param text: The text or batch of text ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GenerationMixin:
"""A class containing all functions for auto-regressive text generation Pass custom parameter values to 'generate' ."""
def tokenize(self, text: Union[str, List[str]], add_bos: bool=True) -> List[int]:
"""Decode the id to words :param text: The text or batch of text to be tokeniz... | the_stack_v2_python_sparse | python/llm/src/bigdl/llm/ggml/model/generation/utils.py | intel-analytics/BigDL | train | 4,913 |
ca550ba9e31b9f3f742692a160945377697a16f9 | [
"if not LABEL_RESULTS in doc:\n raise err.InvalidTemplateError(\"missing element '{}'\".format(LABEL_RESULTS))\ntemplate = super(BenchmarkTemplateLoader, self).from_dict(doc=doc, identifier=identifier, base_dir=base_dir, validate=validate)\ntry:\n schema = BenchmarkResultSchema.from_dict(doc[LABEL_RESULTS])\n... | <|body_start_0|>
if not LABEL_RESULTS in doc:
raise err.InvalidTemplateError("missing element '{}'".format(LABEL_RESULTS))
template = super(BenchmarkTemplateLoader, self).from_dict(doc=doc, identifier=identifier, base_dir=base_dir, validate=validate)
try:
schema = Benchma... | Implementation of the template loader for benchmark workflow templates. | BenchmarkTemplateLoader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BenchmarkTemplateLoader:
"""Implementation of the template loader for benchmark workflow templates."""
def from_dict(self, doc, identifier=None, base_dir=None, validate=True):
"""Create an instance of the benchmark template from a dictionary serialization. Expects a dictionary that c... | stack_v2_sparse_classes_75kplus_train_002658 | 3,619 | permissive | [
{
"docstring": "Create an instance of the benchmark template from a dictionary serialization. Expects a dictionary that contains the three top-level elements of the template handle plus the 'result' schema. Parameters ---------- dict: dict Dictionary serialization of a workflow template identifier: string, opti... | 2 | null | Implement the Python class `BenchmarkTemplateLoader` described below.
Class description:
Implementation of the template loader for benchmark workflow templates.
Method signatures and docstrings:
- def from_dict(self, doc, identifier=None, base_dir=None, validate=True): Create an instance of the benchmark template fro... | Implement the Python class `BenchmarkTemplateLoader` described below.
Class description:
Implementation of the template loader for benchmark workflow templates.
Method signatures and docstrings:
- def from_dict(self, doc, identifier=None, base_dir=None, validate=True): Create an instance of the benchmark template fro... | 0b9c593b4281b30e42d49f486b55bf953adcb29d | <|skeleton|>
class BenchmarkTemplateLoader:
"""Implementation of the template loader for benchmark workflow templates."""
def from_dict(self, doc, identifier=None, base_dir=None, validate=True):
"""Create an instance of the benchmark template from a dictionary serialization. Expects a dictionary that c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BenchmarkTemplateLoader:
"""Implementation of the template loader for benchmark workflow templates."""
def from_dict(self, doc, identifier=None, base_dir=None, validate=True):
"""Create an instance of the benchmark template from a dictionary serialization. Expects a dictionary that contains the t... | the_stack_v2_python_sparse | benchtmpl/workflow/benchmark/loader.py | scailfin/benchmark-templates | train | 0 |
a6917e65bf6b9be81cb3e67230d298adc36738e6 | [
"params = []\nif all_tenants:\n params.append('all_tenants=1')\nif include:\n params.append('include=%s' % ','.join(include))\nelif exclude:\n params.append('exclude=%s' % ','.join(exclude))\nuri = '/os-fping'\nif params:\n uri = '%s?%s' % (uri, '&'.join(params))\nif response_key:\n return self._get(... | <|body_start_0|>
params = []
if all_tenants:
params.append('all_tenants=1')
if include:
params.append('include=%s' % ','.join(include))
elif exclude:
params.append('exclude=%s' % ','.join(exclude))
uri = '/os-fping'
if params:
... | FpingManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FpingManager:
def list(self, all_tenants=False, include=[], exclude=[], response_key=True, **kwargs):
"""Fping all servers. :rtype: list of :class:`Fping`."""
<|body_0|>
def get(self, server_id, response_key=True, **kwargs):
"""Fping a specific server. :param network... | stack_v2_sparse_classes_75kplus_train_002659 | 1,209 | no_license | [
{
"docstring": "Fping all servers. :rtype: list of :class:`Fping`.",
"name": "list",
"signature": "def list(self, all_tenants=False, include=[], exclude=[], response_key=True, **kwargs)"
},
{
"docstring": "Fping a specific server. :param network: ID of the server to fping. :rtype: :class:`Fping`... | 2 | stack_v2_sparse_classes_30k_train_030272 | Implement the Python class `FpingManager` described below.
Class description:
Implement the FpingManager class.
Method signatures and docstrings:
- def list(self, all_tenants=False, include=[], exclude=[], response_key=True, **kwargs): Fping all servers. :rtype: list of :class:`Fping`.
- def get(self, server_id, resp... | Implement the Python class `FpingManager` described below.
Class description:
Implement the FpingManager class.
Method signatures and docstrings:
- def list(self, all_tenants=False, include=[], exclude=[], response_key=True, **kwargs): Fping all servers. :rtype: list of :class:`Fping`.
- def get(self, server_id, resp... | 42f9197ba26ffb6b9dd336a524639ecbbf194365 | <|skeleton|>
class FpingManager:
def list(self, all_tenants=False, include=[], exclude=[], response_key=True, **kwargs):
"""Fping all servers. :rtype: list of :class:`Fping`."""
<|body_0|>
def get(self, server_id, response_key=True, **kwargs):
"""Fping a specific server. :param network... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FpingManager:
def list(self, all_tenants=False, include=[], exclude=[], response_key=True, **kwargs):
"""Fping all servers. :rtype: list of :class:`Fping`."""
params = []
if all_tenants:
params.append('all_tenants=1')
if include:
params.append('include=%... | the_stack_v2_python_sparse | ops_client/project/nova/fping.py | tokuzfunpi/ops_client | train | 0 | |
0c13511c4dc20ec314d05cb7544dd6eceefcee2a | [
"if not self.root:\n self.root = None\n return\nnode = Node(value)\nif value < self.root.value:\n if not self.root.left:\n self.root.left = node\nelif not self.root.right:\n self.root.right = node",
"node = node or self.root\nif not self.root:\n return False\nif node.value == value:\n ret... | <|body_start_0|>
if not self.root:
self.root = None
return
node = Node(value)
if value < self.root.value:
if not self.root.left:
self.root.left = node
elif not self.root.right:
self.root.right = node
<|end_body_0|>
<|body_s... | BinarySearchTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinarySearchTree:
def add(self, value):
"""Define a method named add that accepts a value, and adds a new node with that value in the correct location in the binary search tree."""
<|body_0|>
def contains(self, value, node=None):
"""Define a method named contains tha... | stack_v2_sparse_classes_75kplus_train_002660 | 2,902 | no_license | [
{
"docstring": "Define a method named add that accepts a value, and adds a new node with that value in the correct location in the binary search tree.",
"name": "add",
"signature": "def add(self, value)"
},
{
"docstring": "Define a method named contains that accepts a value, and returns a boolea... | 2 | stack_v2_sparse_classes_30k_train_030447 | Implement the Python class `BinarySearchTree` described below.
Class description:
Implement the BinarySearchTree class.
Method signatures and docstrings:
- def add(self, value): Define a method named add that accepts a value, and adds a new node with that value in the correct location in the binary search tree.
- def... | Implement the Python class `BinarySearchTree` described below.
Class description:
Implement the BinarySearchTree class.
Method signatures and docstrings:
- def add(self, value): Define a method named add that accepts a value, and adds a new node with that value in the correct location in the binary search tree.
- def... | a0d681ce73ae284980df3a88e437ebb23ffed5eb | <|skeleton|>
class BinarySearchTree:
def add(self, value):
"""Define a method named add that accepts a value, and adds a new node with that value in the correct location in the binary search tree."""
<|body_0|>
def contains(self, value, node=None):
"""Define a method named contains tha... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BinarySearchTree:
def add(self, value):
"""Define a method named add that accepts a value, and adds a new node with that value in the correct location in the binary search tree."""
if not self.root:
self.root = None
return
node = Node(value)
if value < s... | the_stack_v2_python_sparse | Data-Structures/tree/tree.py | AmyE29/python-data-structures-and-algorithms | train | 0 | |
2b8d87586eb6662c10256fc004b80eaafe221199 | [
"super(PointNetEstimation, self).__init__()\nself.conv1 = nn.Conv1d(3, 128, 1)\nself.conv2 = nn.Conv1d(128, 128, 1)\nself.conv3 = nn.Conv1d(128, 256, 1)\nself.conv4 = nn.Conv1d(256, 512, 1)\nself.bn1 = nn.BatchNorm1d(128)\nself.bn2 = nn.BatchNorm1d(128)\nself.bn3 = nn.BatchNorm1d(256)\nself.bn4 = nn.BatchNorm1d(512... | <|body_start_0|>
super(PointNetEstimation, self).__init__()
self.conv1 = nn.Conv1d(3, 128, 1)
self.conv2 = nn.Conv1d(128, 128, 1)
self.conv3 = nn.Conv1d(128, 256, 1)
self.conv4 = nn.Conv1d(256, 512, 1)
self.bn1 = nn.BatchNorm1d(128)
self.bn2 = nn.BatchNorm1d(128)
... | PointNetEstimation | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointNetEstimation:
def __init__(self, n_classes=3):
"""v1 Amodal 3D Box Estimation Pointnet :param n_classes:3 :param one_hot_vec:[bs,n_classes]"""
<|body_0|>
def forward(self, pts, one_hot_vec):
""":param pts: [bs,3,m]: x,y,z after InstanceSeg :return: box_pred: [b... | stack_v2_sparse_classes_75kplus_train_002661 | 11,900 | permissive | [
{
"docstring": "v1 Amodal 3D Box Estimation Pointnet :param n_classes:3 :param one_hot_vec:[bs,n_classes]",
"name": "__init__",
"signature": "def __init__(self, n_classes=3)"
},
{
"docstring": ":param pts: [bs,3,m]: x,y,z after InstanceSeg :return: box_pred: [bs,3+NUM_HEADING_BIN*2+NUM_SIZE_CLUS... | 2 | stack_v2_sparse_classes_30k_train_025621 | Implement the Python class `PointNetEstimation` described below.
Class description:
Implement the PointNetEstimation class.
Method signatures and docstrings:
- def __init__(self, n_classes=3): v1 Amodal 3D Box Estimation Pointnet :param n_classes:3 :param one_hot_vec:[bs,n_classes]
- def forward(self, pts, one_hot_ve... | Implement the Python class `PointNetEstimation` described below.
Class description:
Implement the PointNetEstimation class.
Method signatures and docstrings:
- def __init__(self, n_classes=3): v1 Amodal 3D Box Estimation Pointnet :param n_classes:3 :param one_hot_vec:[bs,n_classes]
- def forward(self, pts, one_hot_ve... | 64bcfa4b292dacc91f92f2542e11d489b1fa2c8a | <|skeleton|>
class PointNetEstimation:
def __init__(self, n_classes=3):
"""v1 Amodal 3D Box Estimation Pointnet :param n_classes:3 :param one_hot_vec:[bs,n_classes]"""
<|body_0|>
def forward(self, pts, one_hot_vec):
""":param pts: [bs,3,m]: x,y,z after InstanceSeg :return: box_pred: [b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PointNetEstimation:
def __init__(self, n_classes=3):
"""v1 Amodal 3D Box Estimation Pointnet :param n_classes:3 :param one_hot_vec:[bs,n_classes]"""
super(PointNetEstimation, self).__init__()
self.conv1 = nn.Conv1d(3, 128, 1)
self.conv2 = nn.Conv1d(128, 128, 1)
self.con... | the_stack_v2_python_sparse | frustum_pointnet/models/frustum_pointnets_v1_old.py | ayushjain1144/SeeingByMoving | train | 24 | |
65a3ff288c9be9f1e34852c434aad38637f13ac3 | [
"LaserProfile.__init__(self, 1)\nself.longitudinal_profile = longitudinal_profile\nself.transverse_profile = transverse_profile\nself.propag_direction = longitudinal_profile.propag_direction\nassert self.propag_direction == transverse_profile.propag_direction\nk0 = self.longitudinal_profile.k0\nassert k0 == self.tr... | <|body_start_0|>
LaserProfile.__init__(self, 1)
self.longitudinal_profile = longitudinal_profile
self.transverse_profile = transverse_profile
self.propag_direction = longitudinal_profile.propag_direction
assert self.propag_direction == transverse_profile.propag_direction
... | Class that defines a laser pulse by combining a longitudinal and transverse profile under the paraxial approxiation. | ParaxialApproximationLaser | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParaxialApproximationLaser:
"""Class that defines a laser pulse by combining a longitudinal and transverse profile under the paraxial approxiation."""
def __init__(self, longitudinal_profile, transverse_profile, E_laser, theta_pol=0.0):
"""Construct a laser profile E(x,y,z,t) by comb... | stack_v2_sparse_classes_75kplus_train_002662 | 35,703 | permissive | [
{
"docstring": "Construct a laser profile E(x,y,z,t) by combining a complex longitudinal E(z,t) and transverse E(x,y,z) profile, which is valid under the paraxial approximation. The combined profile is normalized to a given pulse energy. Parameters ---------- longitudinal_profile: an instance of :any:`LaserLong... | 2 | stack_v2_sparse_classes_30k_train_024342 | Implement the Python class `ParaxialApproximationLaser` described below.
Class description:
Class that defines a laser pulse by combining a longitudinal and transverse profile under the paraxial approxiation.
Method signatures and docstrings:
- def __init__(self, longitudinal_profile, transverse_profile, E_laser, the... | Implement the Python class `ParaxialApproximationLaser` described below.
Class description:
Class that defines a laser pulse by combining a longitudinal and transverse profile under the paraxial approxiation.
Method signatures and docstrings:
- def __init__(self, longitudinal_profile, transverse_profile, E_laser, the... | 5744598571eab40c4fb45cc3db21f346b69b1f37 | <|skeleton|>
class ParaxialApproximationLaser:
"""Class that defines a laser pulse by combining a longitudinal and transverse profile under the paraxial approxiation."""
def __init__(self, longitudinal_profile, transverse_profile, E_laser, theta_pol=0.0):
"""Construct a laser profile E(x,y,z,t) by comb... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ParaxialApproximationLaser:
"""Class that defines a laser pulse by combining a longitudinal and transverse profile under the paraxial approxiation."""
def __init__(self, longitudinal_profile, transverse_profile, E_laser, theta_pol=0.0):
"""Construct a laser profile E(x,y,z,t) by combining a compl... | the_stack_v2_python_sparse | fbpic/lpa_utils/laser/laser_profiles.py | fbpic/fbpic | train | 163 |
a99bdf36c53f37deced2f27d4246f25fdeb4098a | [
"self.c = ConvertImgMaskToTFrecord()\nself.img_dir = img_dir\nif masks_dir is not None:\n self.masks_dir = masks_dir\nelse:\n self.masks_dir = img_dir\nself.out_dir = out_dir\nself.desired_size = desired_size\nself.tf_records_list = []\nself.img_mask_list = []\nself.create_img_mask_list()\nself.create_tf_reco... | <|body_start_0|>
self.c = ConvertImgMaskToTFrecord()
self.img_dir = img_dir
if masks_dir is not None:
self.masks_dir = masks_dir
else:
self.masks_dir = img_dir
self.out_dir = out_dir
self.desired_size = desired_size
self.tf_records_list = [... | CreateImageDatabase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateImageDatabase:
def __init__(self, img_dir: str, out_dir: str, masks_dir: str=None, unit_test: bool=False, desired_size: tuple=(None, None)) -> None:
"""Args: img_dir: list of input image files masks_dir: list of segmentation mask files out_dir: directory to output TF records"""
... | stack_v2_sparse_classes_75kplus_train_002663 | 5,239 | no_license | [
{
"docstring": "Args: img_dir: list of input image files masks_dir: list of segmentation mask files out_dir: directory to output TF records",
"name": "__init__",
"signature": "def __init__(self, img_dir: str, out_dir: str, masks_dir: str=None, unit_test: bool=False, desired_size: tuple=(None, None)) -> ... | 6 | stack_v2_sparse_classes_30k_train_010411 | Implement the Python class `CreateImageDatabase` described below.
Class description:
Implement the CreateImageDatabase class.
Method signatures and docstrings:
- def __init__(self, img_dir: str, out_dir: str, masks_dir: str=None, unit_test: bool=False, desired_size: tuple=(None, None)) -> None: Args: img_dir: list of... | Implement the Python class `CreateImageDatabase` described below.
Class description:
Implement the CreateImageDatabase class.
Method signatures and docstrings:
- def __init__(self, img_dir: str, out_dir: str, masks_dir: str=None, unit_test: bool=False, desired_size: tuple=(None, None)) -> None: Args: img_dir: list of... | c16995110b4d6f69450378b82b40c18550228196 | <|skeleton|>
class CreateImageDatabase:
def __init__(self, img_dir: str, out_dir: str, masks_dir: str=None, unit_test: bool=False, desired_size: tuple=(None, None)) -> None:
"""Args: img_dir: list of input image files masks_dir: list of segmentation mask files out_dir: directory to output TF records"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CreateImageDatabase:
def __init__(self, img_dir: str, out_dir: str, masks_dir: str=None, unit_test: bool=False, desired_size: tuple=(None, None)) -> None:
"""Args: img_dir: list of input image files masks_dir: list of segmentation mask files out_dir: directory to output TF records"""
self.c = ... | the_stack_v2_python_sparse | model_1/segmentation/create_image_database.py | chaoneng/AAC_scoring | train | 0 | |
6100f1a09996674b67a958a7026ada368ae699fb | [
"nn.Module.__init__(self)\nself.tau = tau\nself.y_list = y_list\nself.batch_size = batch_size\nself.device = device",
"p = torch.cat((z_i, z_j), dim=0)\nsim = nn.CosineSimilarity(dim=2)(p.unsqueeze(1), p.unsqueeze(0)) / self.tau\ny2 = torch.cat([y, y], dim=0).view(-1, 1)\nif self.y_list == 'all':\n mask = torc... | <|body_start_0|>
nn.Module.__init__(self)
self.tau = tau
self.y_list = y_list
self.batch_size = batch_size
self.device = device
<|end_body_0|>
<|body_start_1|>
p = torch.cat((z_i, z_j), dim=0)
sim = nn.CosineSimilarity(dim=2)(p.unsqueeze(1), p.unsqueeze(0)) / sel... | Define the Supervised Contrastive Loss as a Pytorch Module. | SupervisedContrastiveLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SupervisedContrastiveLoss:
"""Define the Supervised Contrastive Loss as a Pytorch Module."""
def __init__(self, tau, batch_size, y_list='all', device='cuda'):
"""Initialize a Supervised Contrastive Loss Module. ---------- INPUT |---- tau (float) the temperature hyperparameter. |---- ... | stack_v2_sparse_classes_75kplus_train_002664 | 18,386 | permissive | [
{
"docstring": "Initialize a Supervised Contrastive Loss Module. ---------- INPUT |---- tau (float) the temperature hyperparameter. |---- y_list (list of int) the list of class to conisder for positive. | Default is using all classes. |---- batch_size (int) the batch_size used. |---- device (str) the device to ... | 2 | stack_v2_sparse_classes_30k_train_017204 | Implement the Python class `SupervisedContrastiveLoss` described below.
Class description:
Define the Supervised Contrastive Loss as a Pytorch Module.
Method signatures and docstrings:
- def __init__(self, tau, batch_size, y_list='all', device='cuda'): Initialize a Supervised Contrastive Loss Module. ---------- INPUT... | Implement the Python class `SupervisedContrastiveLoss` described below.
Class description:
Define the Supervised Contrastive Loss as a Pytorch Module.
Method signatures and docstrings:
- def __init__(self, tau, batch_size, y_list='all', device='cuda'): Initialize a Supervised Contrastive Loss Module. ---------- INPUT... | 850b6195d6290a50eee865b4d5a66f5db5260e8f | <|skeleton|>
class SupervisedContrastiveLoss:
"""Define the Supervised Contrastive Loss as a Pytorch Module."""
def __init__(self, tau, batch_size, y_list='all', device='cuda'):
"""Initialize a Supervised Contrastive Loss Module. ---------- INPUT |---- tau (float) the temperature hyperparameter. |---- ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SupervisedContrastiveLoss:
"""Define the Supervised Contrastive Loss as a Pytorch Module."""
def __init__(self, tau, batch_size, y_list='all', device='cuda'):
"""Initialize a Supervised Contrastive Loss Module. ---------- INPUT |---- tau (float) the temperature hyperparameter. |---- y_list (list ... | the_stack_v2_python_sparse | Code/src/models/optim/CustomLosses.py | antoine-spahr/X-ray-Anomaly-Detection | train | 3 |
d78897830b362e76a0a15a86d054208d54cad769 | [
"C = self.COEFFS[imt]\nmag = rup.mag\nhypo_depth = rup.hypo_depth\nmean = self._compute_mean(C, g, mag, hypo_depth, dists, imt)\nstddevs = self._get_stddevs(C, stddev_types, sites.vs30.shape[0])\nreturn (mean, stddevs)",
"delta = 0.0075 * 10 ** (0.507 * mag)\nif mag < 6.5:\n R = np.sqrt(dists.rhypo ** 2 + delt... | <|body_start_0|>
C = self.COEFFS[imt]
mag = rup.mag
hypo_depth = rup.hypo_depth
mean = self._compute_mean(C, g, mag, hypo_depth, dists, imt)
stddevs = self._get_stddevs(C, stddev_types, sites.vs30.shape[0])
return (mean, stddevs)
<|end_body_0|>
<|body_start_1|>
d... | Implements GMPE developed by Garcia, D., Singh, S. K., Harraiz, M, Ordaz, M., and Pacheco, J. F. and published in BSSA as: "Inslab earthquakes of Central Mexico: Peak ground-motion parameters and response spectra", vol. 95, No. 6, pp. 2272-2282." The original formulation predict peak ground acceleration (PGA), in cm/s*... | GarciaEtAl2005SSlab | [
"BSD-3-Clause",
"AGPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GarciaEtAl2005SSlab:
"""Implements GMPE developed by Garcia, D., Singh, S. K., Harraiz, M, Ordaz, M., and Pacheco, J. F. and published in BSSA as: "Inslab earthquakes of Central Mexico: Peak ground-motion parameters and response spectra", vol. 95, No. 6, pp. 2272-2282." The original formulation p... | stack_v2_sparse_classes_75kplus_train_002665 | 9,779 | permissive | [
{
"docstring": "See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.",
"name": "get_mean_and_stddevs",
"signature": "def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types)"
},
{
"docstring": "Compute mean accord... | 3 | stack_v2_sparse_classes_30k_train_041123 | Implement the Python class `GarciaEtAl2005SSlab` described below.
Class description:
Implements GMPE developed by Garcia, D., Singh, S. K., Harraiz, M, Ordaz, M., and Pacheco, J. F. and published in BSSA as: "Inslab earthquakes of Central Mexico: Peak ground-motion parameters and response spectra", vol. 95, No. 6, pp.... | Implement the Python class `GarciaEtAl2005SSlab` described below.
Class description:
Implements GMPE developed by Garcia, D., Singh, S. K., Harraiz, M, Ordaz, M., and Pacheco, J. F. and published in BSSA as: "Inslab earthquakes of Central Mexico: Peak ground-motion parameters and response spectra", vol. 95, No. 6, pp.... | 0da9ba5a575360081715e8b90c71d4b16c6687c8 | <|skeleton|>
class GarciaEtAl2005SSlab:
"""Implements GMPE developed by Garcia, D., Singh, S. K., Harraiz, M, Ordaz, M., and Pacheco, J. F. and published in BSSA as: "Inslab earthquakes of Central Mexico: Peak ground-motion parameters and response spectra", vol. 95, No. 6, pp. 2272-2282." The original formulation p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GarciaEtAl2005SSlab:
"""Implements GMPE developed by Garcia, D., Singh, S. K., Harraiz, M, Ordaz, M., and Pacheco, J. F. and published in BSSA as: "Inslab earthquakes of Central Mexico: Peak ground-motion parameters and response spectra", vol. 95, No. 6, pp. 2272-2282." The original formulation predict peak g... | the_stack_v2_python_sparse | openquake/hazardlib/gsim/garcia_2005.py | GFZ-Centre-for-Early-Warning/shakyground | train | 1 |
6783c9a283b8b326061df56faf0a9ce6c1dcf169 | [
"if k == 1:\n return head\nlists = self.partition(head, k)\nm = len(lists)\npieces = []\nfor i in range(m):\n myhead, reverse = lists[i]\n if reverse:\n new_head = self.reverseList(myhead)\n else:\n new_head = myhead\n pieces.append(new_head)\nfor i in range(m - 1):\n lists[i][0].nex... | <|body_start_0|>
if k == 1:
return head
lists = self.partition(head, k)
m = len(lists)
pieces = []
for i in range(m):
myhead, reverse = lists[i]
if reverse:
new_head = self.reverseList(myhead)
else:
n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseKGroup(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_0|>
def partition(self, head, k):
"""partition list in k-group"""
<|body_1|>
def reverseList(self, head):
"""reverse a linked list"""
... | stack_v2_sparse_classes_75kplus_train_002666 | 1,799 | no_license | [
{
"docstring": ":type head: ListNode :type k: int :rtype: ListNode",
"name": "reverseKGroup",
"signature": "def reverseKGroup(self, head, k)"
},
{
"docstring": "partition list in k-group",
"name": "partition",
"signature": "def partition(self, head, k)"
},
{
"docstring": "reverse... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseKGroup(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
- def partition(self, head, k): partition list in k-group
- def reverseList(self, head): reve... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseKGroup(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
- def partition(self, head, k): partition list in k-group
- def reverseList(self, head): reve... | e00cf94c5b86c8cca27e3bee69ad21e727b7679b | <|skeleton|>
class Solution:
def reverseKGroup(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_0|>
def partition(self, head, k):
"""partition list in k-group"""
<|body_1|>
def reverseList(self, head):
"""reverse a linked list"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverseKGroup(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
if k == 1:
return head
lists = self.partition(head, k)
m = len(lists)
pieces = []
for i in range(m):
myhead, reverse = lists[i]
... | the_stack_v2_python_sparse | interview/prob25.py | binchen15/leet-python | train | 1 | |
e633e509f33d54b90ba0902e4b79e96900ef5ead | [
"super(SimpleActorNet, self).__init__()\nself.bound = a_bound\nself.fc1 = nn.Linear(n_states, n_neurons)\nself.fc1.weight.data.normal_(0, 0.1)\nself.out = nn.Linear(n_neurons, n_actions)\nself.out.weight.data.normal_(0, 0.1)\nif CUDA:\n self.bound = torch.FloatTensor([self.bound]).cuda()\nelse:\n self.bound =... | <|body_start_0|>
super(SimpleActorNet, self).__init__()
self.bound = a_bound
self.fc1 = nn.Linear(n_states, n_neurons)
self.fc1.weight.data.normal_(0, 0.1)
self.out = nn.Linear(n_neurons, n_actions)
self.out.weight.data.normal_(0, 0.1)
if CUDA:
self.bo... | 定义Actor的网络结构 | SimpleActorNet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleActorNet:
"""定义Actor的网络结构"""
def __init__(self, n_states, n_actions, n_neurons=30, a_bound=1):
"""定义隐藏层和输出层参数 @param n_obs: number of observations @param n_actions: number of actions @param n_neurons: 隐藏层神经元数目 @param a_bound: action的倍率"""
<|body_0|>
def forward(sel... | stack_v2_sparse_classes_75kplus_train_002667 | 1,533 | permissive | [
{
"docstring": "定义隐藏层和输出层参数 @param n_obs: number of observations @param n_actions: number of actions @param n_neurons: 隐藏层神经元数目 @param a_bound: action的倍率",
"name": "__init__",
"signature": "def __init__(self, n_states, n_actions, n_neurons=30, a_bound=1)"
},
{
"docstring": "定义网络结构: 第一层网络->ReLU激活... | 2 | stack_v2_sparse_classes_30k_train_007743 | Implement the Python class `SimpleActorNet` described below.
Class description:
定义Actor的网络结构
Method signatures and docstrings:
- def __init__(self, n_states, n_actions, n_neurons=30, a_bound=1): 定义隐藏层和输出层参数 @param n_obs: number of observations @param n_actions: number of actions @param n_neurons: 隐藏层神经元数目 @param a_bo... | Implement the Python class `SimpleActorNet` described below.
Class description:
定义Actor的网络结构
Method signatures and docstrings:
- def __init__(self, n_states, n_actions, n_neurons=30, a_bound=1): 定义隐藏层和输出层参数 @param n_obs: number of observations @param n_actions: number of actions @param n_neurons: 隐藏层神经元数目 @param a_bo... | b1b694361c688f5e0055148a0cdcb4c6253cd7bd | <|skeleton|>
class SimpleActorNet:
"""定义Actor的网络结构"""
def __init__(self, n_states, n_actions, n_neurons=30, a_bound=1):
"""定义隐藏层和输出层参数 @param n_obs: number of observations @param n_actions: number of actions @param n_neurons: 隐藏层神经元数目 @param a_bound: action的倍率"""
<|body_0|>
def forward(sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SimpleActorNet:
"""定义Actor的网络结构"""
def __init__(self, n_states, n_actions, n_neurons=30, a_bound=1):
"""定义隐藏层和输出层参数 @param n_obs: number of observations @param n_actions: number of actions @param n_neurons: 隐藏层神经元数目 @param a_bound: action的倍率"""
super(SimpleActorNet, self).__init__()
... | the_stack_v2_python_sparse | rl4net/nets/actor_net.py | bupt-ipcr/RL4Net | train | 16 |
704cc84351a306274dca0cffccaadc603e918177 | [
"super(PipPage, self).__init__()\nself.setupUi(self)\nself.setObjectName('PipPage')\nself.__plugin = plugin\nself.__model = QStringListModel(self)\nself.__proxyModel = QSortFilterProxyModel(self)\nself.__proxyModel.setFilterCaseSensitivity(Qt.CaseInsensitive)\nself.__proxyModel.setSourceModel(self.__model)\nself.st... | <|body_start_0|>
super(PipPage, self).__init__()
self.setupUi(self)
self.setObjectName('PipPage')
self.__plugin = plugin
self.__model = QStringListModel(self)
self.__proxyModel = QSortFilterProxyModel(self)
self.__proxyModel.setFilterCaseSensitivity(Qt.CaseInsensi... | Class implementing the configuration page. | PipPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PipPage:
"""Class implementing the configuration page."""
def __init__(self, plugin):
"""Constructor @param plugin reference to the plugin object"""
<|body_0|>
def on_addButton_clicked(self):
"""Private slot used to add an executable to the list."""
<|bod... | stack_v2_sparse_classes_75kplus_train_002668 | 3,644 | no_license | [
{
"docstring": "Constructor @param plugin reference to the plugin object",
"name": "__init__",
"signature": "def __init__(self, plugin)"
},
{
"docstring": "Private slot used to add an executable to the list.",
"name": "on_addButton_clicked",
"signature": "def on_addButton_clicked(self)"
... | 4 | stack_v2_sparse_classes_30k_train_026371 | Implement the Python class `PipPage` described below.
Class description:
Class implementing the configuration page.
Method signatures and docstrings:
- def __init__(self, plugin): Constructor @param plugin reference to the plugin object
- def on_addButton_clicked(self): Private slot used to add an executable to the l... | Implement the Python class `PipPage` described below.
Class description:
Class implementing the configuration page.
Method signatures and docstrings:
- def __init__(self, plugin): Constructor @param plugin reference to the plugin object
- def on_addButton_clicked(self): Private slot used to add an executable to the l... | 3df0c805225a8d4f2709565d7eda4e07a050c986 | <|skeleton|>
class PipPage:
"""Class implementing the configuration page."""
def __init__(self, plugin):
"""Constructor @param plugin reference to the plugin object"""
<|body_0|>
def on_addButton_clicked(self):
"""Private slot used to add an executable to the list."""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PipPage:
"""Class implementing the configuration page."""
def __init__(self, plugin):
"""Constructor @param plugin reference to the plugin object"""
super(PipPage, self).__init__()
self.setupUi(self)
self.setObjectName('PipPage')
self.__plugin = plugin
self... | the_stack_v2_python_sparse | eric6/.eric6/eric6plugins/ToolPip/ConfigurationPage/PipPage.py | metamarcdw/.dotfiles | train | 0 |
4afee0b10b982e669613e4a8b4a2fb402612665f | [
"actionlist = [1, 2, 3, 4, 5]\nfor action in actionlist:\n if action == 1:\n val = getColumnSelection(action)\n self.assertEqual(val, 'bookID')\n if action == 2:\n val = getColumnSelection(action)\n self.assertEqual(val, 'bookAuthor')\n if action == 3:\n val = getColumnSe... | <|body_start_0|>
actionlist = [1, 2, 3, 4, 5]
for action in actionlist:
if action == 1:
val = getColumnSelection(action)
self.assertEqual(val, 'bookID')
if action == 2:
val = getColumnSelection(action)
self.assertEqu... | Test for getting action solution | TestgetColumnSelection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestgetColumnSelection:
"""Test for getting action solution"""
def testGetColumnSolution(self):
"""This a True test to see if the column is selected"""
<|body_0|>
def testBadGetColumnSolution(self):
"""This a False test to see if the column is selected"""
... | stack_v2_sparse_classes_75kplus_train_002669 | 1,495 | no_license | [
{
"docstring": "This a True test to see if the column is selected",
"name": "testGetColumnSolution",
"signature": "def testGetColumnSolution(self)"
},
{
"docstring": "This a False test to see if the column is selected",
"name": "testBadGetColumnSolution",
"signature": "def testBadGetColu... | 2 | stack_v2_sparse_classes_30k_train_026452 | Implement the Python class `TestgetColumnSelection` described below.
Class description:
Test for getting action solution
Method signatures and docstrings:
- def testGetColumnSolution(self): This a True test to see if the column is selected
- def testBadGetColumnSolution(self): This a False test to see if the column i... | Implement the Python class `TestgetColumnSelection` described below.
Class description:
Test for getting action solution
Method signatures and docstrings:
- def testGetColumnSolution(self): This a True test to see if the column is selected
- def testBadGetColumnSolution(self): This a False test to see if the column i... | c9fc7f312f9d73fef6af6d13459ea4a69b16cdca | <|skeleton|>
class TestgetColumnSelection:
"""Test for getting action solution"""
def testGetColumnSolution(self):
"""This a True test to see if the column is selected"""
<|body_0|>
def testBadGetColumnSolution(self):
"""This a False test to see if the column is selected"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestgetColumnSelection:
"""Test for getting action solution"""
def testGetColumnSolution(self):
"""This a True test to see if the column is selected"""
actionlist = [1, 2, 3, 4, 5]
for action in actionlist:
if action == 1:
val = getColumnSelection(actio... | the_stack_v2_python_sparse | IT - 412/databaseAssignment/testcases/testGetColumnSelection.py | vifezue/PythonWork | train | 0 |
def9ed39d4c0abfbb780a3a3ede1e75b057db946 | [
"self.sentence = sentence\nself.event_domain = event_domain\nself.event_type = event_type\nself._allocate_arrays(params.get_int('max_sent_length'), params.get_int('embedding.none_token_index'), params.get_string('cnn.int_type'))",
"num_labels = len(self.event_domain.event_types)\nself.label = np.zeros(num_labels,... | <|body_start_0|>
self.sentence = sentence
self.event_domain = event_domain
self.event_type = event_type
self._allocate_arrays(params.get_int('max_sent_length'), params.get_int('embedding.none_token_index'), params.get_string('cnn.int_type'))
<|end_body_0|>
<|body_start_1|>
num_l... | EventMentionExample | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventMentionExample:
def __init__(self, sentence, event_domain, params, event_type=None):
"""We are given a sentence as the tasks span, and event_type (present during training) :type sentence: nlplingo.text.text_span.Sentence :type event_domain: nlplingo.event.event_domain.EventDomain :t... | stack_v2_sparse_classes_75kplus_train_002670 | 23,383 | permissive | [
{
"docstring": "We are given a sentence as the tasks span, and event_type (present during training) :type sentence: nlplingo.text.text_span.Sentence :type event_domain: nlplingo.event.event_domain.EventDomain :type params: nlplingo.common.parameters.Parameters :type event_type: str",
"name": "__init__",
... | 2 | stack_v2_sparse_classes_30k_train_019777 | Implement the Python class `EventMentionExample` described below.
Class description:
Implement the EventMentionExample class.
Method signatures and docstrings:
- def __init__(self, sentence, event_domain, params, event_type=None): We are given a sentence as the tasks span, and event_type (present during training) :ty... | Implement the Python class `EventMentionExample` described below.
Class description:
Implement the EventMentionExample class.
Method signatures and docstrings:
- def __init__(self, sentence, event_domain, params, event_type=None): We are given a sentence as the tasks span, and event_type (present during training) :ty... | 32ff17b1320937faa3d3ebe727032f4b3e7a353d | <|skeleton|>
class EventMentionExample:
def __init__(self, sentence, event_domain, params, event_type=None):
"""We are given a sentence as the tasks span, and event_type (present during training) :type sentence: nlplingo.text.text_span.Sentence :type event_domain: nlplingo.event.event_domain.EventDomain :t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EventMentionExample:
def __init__(self, sentence, event_domain, params, event_type=None):
"""We are given a sentence as the tasks span, and event_type (present during training) :type sentence: nlplingo.text.text_span.Sentence :type event_domain: nlplingo.event.event_domain.EventDomain :type params: nl... | the_stack_v2_python_sparse | nlplingo/sandbox/misc/event_mention.py | BBN-E/nlplingo | train | 3 | |
8c92b85d7fd65836ccfebdc63523d73953e6148f | [
"if not root:\n return []\nres = []\n\ndef digui(root):\n if root:\n for i in root.children:\n digui(i)\n res.append(root.val)\ndigui(root)\nreturn res",
"if not root:\n return []\nres = []\nstack = [root]\nwhile stack:\n node = stack.pop()\n for i in node.children:\n ... | <|body_start_0|>
if not root:
return []
res = []
def digui(root):
if root:
for i in root.children:
digui(i)
res.append(root.val)
digui(root)
return res
<|end_body_0|>
<|body_start_1|>
if not roo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def postorder(self, root: 'Node') -> List[int]:
"""递归"""
<|body_0|>
def postorder1(self, root: 'Node') -> List[int]:
"""迭代"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return []
res = []
def dig... | stack_v2_sparse_classes_75kplus_train_002671 | 1,058 | no_license | [
{
"docstring": "递归",
"name": "postorder",
"signature": "def postorder(self, root: 'Node') -> List[int]"
},
{
"docstring": "迭代",
"name": "postorder1",
"signature": "def postorder1(self, root: 'Node') -> List[int]"
}
] | 2 | stack_v2_sparse_classes_30k_train_002700 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def postorder(self, root: 'Node') -> List[int]: 递归
- def postorder1(self, root: 'Node') -> List[int]: 迭代 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def postorder(self, root: 'Node') -> List[int]: 递归
- def postorder1(self, root: 'Node') -> List[int]: 迭代
<|skeleton|>
class Solution:
def postorder(self, root: 'Node') -> L... | 069bb0b751ef7f469036b9897436eb5d138ffa24 | <|skeleton|>
class Solution:
def postorder(self, root: 'Node') -> List[int]:
"""递归"""
<|body_0|>
def postorder1(self, root: 'Node') -> List[int]:
"""迭代"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def postorder(self, root: 'Node') -> List[int]:
"""递归"""
if not root:
return []
res = []
def digui(root):
if root:
for i in root.children:
digui(i)
res.append(root.val)
digui(root)
... | the_stack_v2_python_sparse | 算法/Week_02/590. N叉树的后序遍历.py | RichieSong/algorithm | train | 0 | |
b1f7fb27053b211b76530b98f0fa42b457ff0742 | [
"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. | GCSStorageServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GCSStorageServiceServicer:
"""Missing associated documentation comment in .proto file."""
def listGCSStorage(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def getGCSStorage(self, request, context):
"""Missing a... | stack_v2_sparse_classes_75kplus_train_002672 | 9,639 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "listGCSStorage",
"signature": "def listGCSStorage(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "getGCSStorage",
"signature": "def getGCSSt... | 5 | null | Implement the Python class `GCSStorageServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def listGCSStorage(self, request, context): Missing associated documentation comment in .proto file.
- def getGCSStorage(self, request... | Implement the Python class `GCSStorageServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def listGCSStorage(self, request, context): Missing associated documentation comment in .proto file.
- def getGCSStorage(self, request... | c69e14b409add099d151434b9add711e41f41b20 | <|skeleton|>
class GCSStorageServiceServicer:
"""Missing associated documentation comment in .proto file."""
def listGCSStorage(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def getGCSStorage(self, request, context):
"""Missing a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GCSStorageServiceServicer:
"""Missing associated documentation comment in .proto file."""
def listGCSStorage(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not impl... | the_stack_v2_python_sparse | python-sdk/src/airavata_mft_sdk/gcs/GCSStorageService_pb2_grpc.py | apache/airavata-mft | train | 23 |
d2db9890ff7c62ab99fe8e428f7e7a55ba5c291f | [
"super(fastText, self).__init__()\nself.hidden_size = hidden_size\nself.embed_size = embed_size\nself.classes = classes\nself.embeddings = nn.Embedding(len(word_embeddings), self.embed_size)\nself.embeddings.weight.data.copy_(torch.from_numpy(word_embeddings))\nself.embeddings.weight.data.requires_grad = False\nsel... | <|body_start_0|>
super(fastText, self).__init__()
self.hidden_size = hidden_size
self.embed_size = embed_size
self.classes = classes
self.embeddings = nn.Embedding(len(word_embeddings), self.embed_size)
self.embeddings.weight.data.copy_(torch.from_numpy(word_embeddings))
... | fastText | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class fastText:
def __init__(self, word_embeddings, hidden_size, embed_size, classes):
""":param word_embeddings: numpy array [vocab_size,embedding_dim]"""
<|body_0|>
def forward(self, x):
"""前向传播 :param x:[batch_size,seq_len] :return: [batch,class]"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_002673 | 1,393 | no_license | [
{
"docstring": ":param word_embeddings: numpy array [vocab_size,embedding_dim]",
"name": "__init__",
"signature": "def __init__(self, word_embeddings, hidden_size, embed_size, classes)"
},
{
"docstring": "前向传播 :param x:[batch_size,seq_len] :return: [batch,class]",
"name": "forward",
"sig... | 2 | stack_v2_sparse_classes_30k_train_010306 | Implement the Python class `fastText` described below.
Class description:
Implement the fastText class.
Method signatures and docstrings:
- def __init__(self, word_embeddings, hidden_size, embed_size, classes): :param word_embeddings: numpy array [vocab_size,embedding_dim]
- def forward(self, x): 前向传播 :param x:[batch... | Implement the Python class `fastText` described below.
Class description:
Implement the fastText class.
Method signatures and docstrings:
- def __init__(self, word_embeddings, hidden_size, embed_size, classes): :param word_embeddings: numpy array [vocab_size,embedding_dim]
- def forward(self, x): 前向传播 :param x:[batch... | cb1ec3a91a0446a3bb515ae2052bd8d1c5856d24 | <|skeleton|>
class fastText:
def __init__(self, word_embeddings, hidden_size, embed_size, classes):
""":param word_embeddings: numpy array [vocab_size,embedding_dim]"""
<|body_0|>
def forward(self, x):
"""前向传播 :param x:[batch_size,seq_len] :return: [batch,class]"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class fastText:
def __init__(self, word_embeddings, hidden_size, embed_size, classes):
""":param word_embeddings: numpy array [vocab_size,embedding_dim]"""
super(fastText, self).__init__()
self.hidden_size = hidden_size
self.embed_size = embed_size
self.classes = classes
... | the_stack_v2_python_sparse | 1.Basic_Embedding_Model/1_3.FastText/code/model.py | fengjiaxin/nlp_model_learning | train | 1 | |
154a7b9d972ed9033495f161d622f4b10c38aa3a | [
"if args is None:\n args = []\nif context is None:\n context = {}\nif not context.get('closed', False):\n args.append(('state', '=', 'draft'))\nreturn super(account_period, self).name_search(cr, uid, name, args=args, operator='ilike', context=context, limit=limit)",
"if self.search(cr, uid, [('id', 'in',... | <|body_start_0|>
if args is None:
args = []
if context is None:
context = {}
if not context.get('closed', False):
args.append(('state', '=', 'draft'))
return super(account_period, self).name_search(cr, uid, name, args=args, operator='ilike', context=co... | account_period | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class account_period:
def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
"""Inherit name_search method to display only open period unless order close period by sending closed=True in context @return: super name_search"""
<|body_0|>
def acti... | stack_v2_sparse_classes_75kplus_train_002674 | 16,800 | no_license | [
{
"docstring": "Inherit name_search method to display only open period unless order close period by sending closed=True in context @return: super name_search",
"name": "name_search",
"signature": "def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100)"
},
{
"d... | 2 | stack_v2_sparse_classes_30k_train_026847 | Implement the Python class `account_period` described below.
Class description:
Implement the account_period class.
Method signatures and docstrings:
- def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100): Inherit name_search method to display only open period unless order close ... | Implement the Python class `account_period` described below.
Class description:
Implement the account_period class.
Method signatures and docstrings:
- def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100): Inherit name_search method to display only open period unless order close ... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class account_period:
def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
"""Inherit name_search method to display only open period unless order close period by sending closed=True in context @return: super name_search"""
<|body_0|>
def acti... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class account_period:
def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
"""Inherit name_search method to display only open period unless order close period by sending closed=True in context @return: super name_search"""
if args is None:
args = []... | the_stack_v2_python_sparse | v_7/Dongola/wafi/account_custom_wafi/account_custom(old).py | musabahmed/baba | train | 0 | |
24242c0b112986cf5eb29d191f719856dc8d77b9 | [
"validate_list_type_and_children_types(bundle_items, Product)\nself.bundle_items = [product.name for product in bundle_items]\nself.required_items = required_items",
"discount = 0\nqualifying_item_count = 0\nqualified_items = dict()\nfor product in basket_products:\n if product in self.bundle_items:\n q... | <|body_start_0|>
validate_list_type_and_children_types(bundle_items, Product)
self.bundle_items = [product.name for product in bundle_items]
self.required_items = required_items
<|end_body_0|>
<|body_start_1|>
discount = 0
qualifying_item_count = 0
qualified_items = dict... | The class for the offer of buying a group of items and getting the cheapest item for free | BundleOffer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BundleOffer:
"""The class for the offer of buying a group of items and getting the cheapest item for free"""
def __init__(self, bundle_items, required_items):
"""Constructor of the BuyAndGetFreeOffer --- Params: discount_percent: list, the list of products included in the bundle offe... | stack_v2_sparse_classes_75kplus_train_002675 | 5,881 | no_license | [
{
"docstring": "Constructor of the BuyAndGetFreeOffer --- Params: discount_percent: list, the list of products included in the bundle offer required_items: int, the required number of items required from the bundle items",
"name": "__init__",
"signature": "def __init__(self, bundle_items, required_items... | 2 | stack_v2_sparse_classes_30k_train_005197 | Implement the Python class `BundleOffer` described below.
Class description:
The class for the offer of buying a group of items and getting the cheapest item for free
Method signatures and docstrings:
- def __init__(self, bundle_items, required_items): Constructor of the BuyAndGetFreeOffer --- Params: discount_percen... | Implement the Python class `BundleOffer` described below.
Class description:
The class for the offer of buying a group of items and getting the cheapest item for free
Method signatures and docstrings:
- def __init__(self, bundle_items, required_items): Constructor of the BuyAndGetFreeOffer --- Params: discount_percen... | 75eeedb6b931fdc0ce1207cefdeccb7bb386c268 | <|skeleton|>
class BundleOffer:
"""The class for the offer of buying a group of items and getting the cheapest item for free"""
def __init__(self, bundle_items, required_items):
"""Constructor of the BuyAndGetFreeOffer --- Params: discount_percent: list, the list of products included in the bundle offe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BundleOffer:
"""The class for the offer of buying a group of items and getting the cheapest item for free"""
def __init__(self, bundle_items, required_items):
"""Constructor of the BuyAndGetFreeOffer --- Params: discount_percent: list, the list of products included in the bundle offer required_it... | the_stack_v2_python_sparse | shopping_basket/offer.py | zyadsober/cx-interview-questions | train | 0 |
e91db422cfa51cc16646b53f7c3e28bfa1eb264a | [
"if not self.numero_ordine.data:\n self.errlist.append('Manca numero ordine')\nif not self.data_ordine.data:\n self.errlist.append('Manca data ordine')\nif not self.descrizione_ordine.data:\n self.errlist.append('Manca descrizione ordine')\nif not self.costo_ordine.validate():\n self.errlist.append('Cos... | <|body_start_0|>
if not self.numero_ordine.data:
self.errlist.append('Manca numero ordine')
if not self.data_ordine.data:
self.errlist.append('Manca data ordine')
if not self.descrizione_ordine.data:
self.errlist.append('Manca descrizione ordine')
if n... | form per definizione ordine | Ordine | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ordine:
"""form per definizione ordine"""
def validate(self):
"""Validazione specifica per il form"""
<|body_0|>
def renderme(self, d_prat):
"""rendering del form"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not self.numero_ordine.data:
... | stack_v2_sparse_classes_75kplus_train_002676 | 29,683 | no_license | [
{
"docstring": "Validazione specifica per il form",
"name": "validate",
"signature": "def validate(self)"
},
{
"docstring": "rendering del form",
"name": "renderme",
"signature": "def renderme(self, d_prat)"
}
] | 2 | stack_v2_sparse_classes_30k_train_026134 | Implement the Python class `Ordine` described below.
Class description:
form per definizione ordine
Method signatures and docstrings:
- def validate(self): Validazione specifica per il form
- def renderme(self, d_prat): rendering del form | Implement the Python class `Ordine` described below.
Class description:
form per definizione ordine
Method signatures and docstrings:
- def validate(self): Validazione specifica per il form
- def renderme(self, d_prat): rendering del form
<|skeleton|>
class Ordine:
"""form per definizione ordine"""
def vali... | 66f5899eaddc4e0bfcb24cfa04f8573d6dc2eb47 | <|skeleton|>
class Ordine:
"""form per definizione ordine"""
def validate(self):
"""Validazione specifica per il form"""
<|body_0|>
def renderme(self, d_prat):
"""rendering del form"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Ordine:
"""form per definizione ordine"""
def validate(self):
"""Validazione specifica per il form"""
if not self.numero_ordine.data:
self.errlist.append('Manca numero ordine')
if not self.data_ordine.data:
self.errlist.append('Manca data ordine')
i... | the_stack_v2_python_sparse | bin/forms.py | lfini/acquisti | train | 0 |
4f405d7937eb377f5aad5d24b00a8d6f061ec5c5 | [
"super().__init__(x, y, width, height)\nself.current_frame = 0\nself.n_frames = n_frames\nself.update_per_frame = update_per_frame\nself.frame_count = 0",
"self.frame_count += 1\nif self.frame_count < self.update_per_frame:\n return\nself.frame_count = 0\nself.current_frame += 1\nif self.current_frame >= self.... | <|body_start_0|>
super().__init__(x, y, width, height)
self.current_frame = 0
self.n_frames = n_frames
self.update_per_frame = update_per_frame
self.frame_count = 0
<|end_body_0|>
<|body_start_1|>
self.frame_count += 1
if self.frame_count < self.update_per_frame:... | AnimatedEntity | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnimatedEntity:
def __init__(self, x, y, width, height, n_frames, update_per_frame=10):
"""n_frames = total number of frames included in animation. update_per_frame = number of frames to wait to update the current frame."""
<|body_0|>
def update_frame(self):
"""funct... | stack_v2_sparse_classes_75kplus_train_002677 | 864 | no_license | [
{
"docstring": "n_frames = total number of frames included in animation. update_per_frame = number of frames to wait to update the current frame.",
"name": "__init__",
"signature": "def __init__(self, x, y, width, height, n_frames, update_per_frame=10)"
},
{
"docstring": "function updates the cu... | 2 | stack_v2_sparse_classes_30k_train_022675 | Implement the Python class `AnimatedEntity` described below.
Class description:
Implement the AnimatedEntity class.
Method signatures and docstrings:
- def __init__(self, x, y, width, height, n_frames, update_per_frame=10): n_frames = total number of frames included in animation. update_per_frame = number of frames t... | Implement the Python class `AnimatedEntity` described below.
Class description:
Implement the AnimatedEntity class.
Method signatures and docstrings:
- def __init__(self, x, y, width, height, n_frames, update_per_frame=10): n_frames = total number of frames included in animation. update_per_frame = number of frames t... | c9a361b2f7441b6cf51fc777e01009b62188e6b2 | <|skeleton|>
class AnimatedEntity:
def __init__(self, x, y, width, height, n_frames, update_per_frame=10):
"""n_frames = total number of frames included in animation. update_per_frame = number of frames to wait to update the current frame."""
<|body_0|>
def update_frame(self):
"""funct... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AnimatedEntity:
def __init__(self, x, y, width, height, n_frames, update_per_frame=10):
"""n_frames = total number of frames included in animation. update_per_frame = number of frames to wait to update the current frame."""
super().__init__(x, y, width, height)
self.current_frame = 0
... | the_stack_v2_python_sparse | src/entity/animated_entity.py | OnkarKunjir/platformer | train | 0 | |
97904682e49c6d3dc696f99d17ae057d22d28604 | [
"self.sim = Simulation()\nmap_files = list()\nprofile_files = list()\nfor root, subdirs, files in os.walk(map_dir):\n map_files.extend([os.path.join(root, file) for file in files])\nfor root, subdirs, files in os.walk(profile_dir):\n profile_files.extend([os.path.join(root, file) for file in files])\nself.map... | <|body_start_0|>
self.sim = Simulation()
map_files = list()
profile_files = list()
for root, subdirs, files in os.walk(map_dir):
map_files.extend([os.path.join(root, file) for file in files])
for root, subdirs, files in os.walk(profile_dir):
profile_files.... | TrainingSimulation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrainingSimulation:
def __init__(self, map_dir, profile_dir, map_regex='\\.\\S*?map\\d+\\.txt', profile_regex='\\.\\S*?profile\\d+\\.txt'):
"""Constructor for TrainingSimulation :param map_dir: String - relative path to directory of maps :param profile_dir: String - relative path to dire... | stack_v2_sparse_classes_75kplus_train_002678 | 4,095 | no_license | [
{
"docstring": "Constructor for TrainingSimulation :param map_dir: String - relative path to directory of maps :param profile_dir: String - relative path to directory of profiles :param map_regex: String - regex pattern to search for maps :param profile_regex: String - regex pattern to search for profile",
... | 3 | null | Implement the Python class `TrainingSimulation` described below.
Class description:
Implement the TrainingSimulation class.
Method signatures and docstrings:
- def __init__(self, map_dir, profile_dir, map_regex='\\.\\S*?map\\d+\\.txt', profile_regex='\\.\\S*?profile\\d+\\.txt'): Constructor for TrainingSimulation :pa... | Implement the Python class `TrainingSimulation` described below.
Class description:
Implement the TrainingSimulation class.
Method signatures and docstrings:
- def __init__(self, map_dir, profile_dir, map_regex='\\.\\S*?map\\d+\\.txt', profile_regex='\\.\\S*?profile\\d+\\.txt'): Constructor for TrainingSimulation :pa... | 897391dc7612c58ffae54beaffb698fc11a7b11c | <|skeleton|>
class TrainingSimulation:
def __init__(self, map_dir, profile_dir, map_regex='\\.\\S*?map\\d+\\.txt', profile_regex='\\.\\S*?profile\\d+\\.txt'):
"""Constructor for TrainingSimulation :param map_dir: String - relative path to directory of maps :param profile_dir: String - relative path to dire... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TrainingSimulation:
def __init__(self, map_dir, profile_dir, map_regex='\\.\\S*?map\\d+\\.txt', profile_regex='\\.\\S*?profile\\d+\\.txt'):
"""Constructor for TrainingSimulation :param map_dir: String - relative path to directory of maps :param profile_dir: String - relative path to directory of profi... | the_stack_v2_python_sparse | interface/training_simulation.py | wmloh/RoadDesignSimulation | train | 5 | |
c3ab1961ed82d868b371bde8961f16db18868f03 | [
"essential_keys = ['nvars', 'dw', 'eps', 'newton_maxiter', 'newton_tol', 'interval']\nfor key in essential_keys:\n if key not in problem_params:\n msg = 'need %s to instantiate problem, only got %s' % (key, str(problem_params.keys()))\n raise ParameterError(msg)\nif (problem_params['nvars'] + 1) % ... | <|body_start_0|>
essential_keys = ['nvars', 'dw', 'eps', 'newton_maxiter', 'newton_tol', 'interval']
for key in essential_keys:
if key not in problem_params:
msg = 'need %s to instantiate problem, only got %s' % (key, str(problem_params.keys()))
raise Paramete... | Example implementing the Allen-Cahn equation in 1D with finite differences and inhomogeneous Dirichlet-BC, with driving force, 0-1 formulation (Bayreuth example), semi-implicit time-stepping Attributes: A: second-order FD discretization of the 1D laplace operator dx: distance between two spatial nodes | allencahn_front_semiimplicit | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class allencahn_front_semiimplicit:
"""Example implementing the Allen-Cahn equation in 1D with finite differences and inhomogeneous Dirichlet-BC, with driving force, 0-1 formulation (Bayreuth example), semi-implicit time-stepping Attributes: A: second-order FD discretization of the 1D laplace operator ... | stack_v2_sparse_classes_75kplus_train_002679 | 27,394 | permissive | [
{
"docstring": "Initialization routine Args: problem_params (dict): custom parameters for the example dtype_u: mesh data type (will be passed parent class) dtype_f: mesh data type with implicit and explicit components (will be passed parent class)",
"name": "__init__",
"signature": "def __init__(self, p... | 3 | stack_v2_sparse_classes_30k_train_029929 | Implement the Python class `allencahn_front_semiimplicit` described below.
Class description:
Example implementing the Allen-Cahn equation in 1D with finite differences and inhomogeneous Dirichlet-BC, with driving force, 0-1 formulation (Bayreuth example), semi-implicit time-stepping Attributes: A: second-order FD dis... | Implement the Python class `allencahn_front_semiimplicit` described below.
Class description:
Example implementing the Allen-Cahn equation in 1D with finite differences and inhomogeneous Dirichlet-BC, with driving force, 0-1 formulation (Bayreuth example), semi-implicit time-stepping Attributes: A: second-order FD dis... | de2cd523411276083355389d7e7993106cedf93d | <|skeleton|>
class allencahn_front_semiimplicit:
"""Example implementing the Allen-Cahn equation in 1D with finite differences and inhomogeneous Dirichlet-BC, with driving force, 0-1 formulation (Bayreuth example), semi-implicit time-stepping Attributes: A: second-order FD discretization of the 1D laplace operator ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class allencahn_front_semiimplicit:
"""Example implementing the Allen-Cahn equation in 1D with finite differences and inhomogeneous Dirichlet-BC, with driving force, 0-1 formulation (Bayreuth example), semi-implicit time-stepping Attributes: A: second-order FD discretization of the 1D laplace operator dx: distance ... | the_stack_v2_python_sparse | pySDC/implementations/problem_classes/AllenCahn_1D_FD.py | ruthschoebel/pySDC | train | 0 |
28137a378d229cb00826af1744d200547c5c3cd2 | [
"self.idx = index.Index()\nfor i, (area_id, polygon) in enumerate(itr):\n obj = Area(area_id=area_id, polygon=polygon)\n self.idx.insert(i, polygon.bounds, obj)",
"result = []\npoint = Point(lat, lon)\nfor hit in self.idx.intersection(point.bounds, objects=True):\n if hit.object.polygon.contains(point):\... | <|body_start_0|>
self.idx = index.Index()
for i, (area_id, polygon) in enumerate(itr):
obj = Area(area_id=area_id, polygon=polygon)
self.idx.insert(i, polygon.bounds, obj)
<|end_body_0|>
<|body_start_1|>
result = []
point = Point(lat, lon)
for hit in self... | RtreeAreaMatcher | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RtreeAreaMatcher:
def insert_from_iterator(self, itr):
"""(id, Polygon)を返すイテレータからRtreeを作る Polygon.boundをもとに作成したRtreeは、idとPolygonを保持する。 Args: itr: (id, Polygon)を返すイテレータ"""
<|body_0|>
def contains(self, lat, lon):
"""Point(lat, lon)を含むPolygonのarea_idを返す。 2つ以上のPolygonとマ... | stack_v2_sparse_classes_75kplus_train_002680 | 3,118 | permissive | [
{
"docstring": "(id, Polygon)を返すイテレータからRtreeを作る Polygon.boundをもとに作成したRtreeは、idとPolygonを保持する。 Args: itr: (id, Polygon)を返すイテレータ",
"name": "insert_from_iterator",
"signature": "def insert_from_iterator(self, itr)"
},
{
"docstring": "Point(lat, lon)を含むPolygonのarea_idを返す。 2つ以上のPolygonとマッチした場合は、面積の小さい... | 2 | stack_v2_sparse_classes_30k_train_016974 | Implement the Python class `RtreeAreaMatcher` described below.
Class description:
Implement the RtreeAreaMatcher class.
Method signatures and docstrings:
- def insert_from_iterator(self, itr): (id, Polygon)を返すイテレータからRtreeを作る Polygon.boundをもとに作成したRtreeは、idとPolygonを保持する。 Args: itr: (id, Polygon)を返すイテレータ
- def contains(... | Implement the Python class `RtreeAreaMatcher` described below.
Class description:
Implement the RtreeAreaMatcher class.
Method signatures and docstrings:
- def insert_from_iterator(self, itr): (id, Polygon)を返すイテレータからRtreeを作る Polygon.boundをもとに作成したRtreeは、idとPolygonを保持する。 Args: itr: (id, Polygon)を返すイテレータ
- def contains(... | 89dbbc489c862a3901c4599397dfc7ca3297fbed | <|skeleton|>
class RtreeAreaMatcher:
def insert_from_iterator(self, itr):
"""(id, Polygon)を返すイテレータからRtreeを作る Polygon.boundをもとに作成したRtreeは、idとPolygonを保持する。 Args: itr: (id, Polygon)を返すイテレータ"""
<|body_0|>
def contains(self, lat, lon):
"""Point(lat, lon)を含むPolygonのarea_idを返す。 2つ以上のPolygonとマ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RtreeAreaMatcher:
def insert_from_iterator(self, itr):
"""(id, Polygon)を返すイテレータからRtreeを作る Polygon.boundをもとに作成したRtreeは、idとPolygonを保持する。 Args: itr: (id, Polygon)を返すイテレータ"""
self.idx = index.Index()
for i, (area_id, polygon) in enumerate(itr):
obj = Area(area_id=area_id, polyg... | the_stack_v2_python_sparse | snlocest/scripts/areamatcher.py | elnikkis/snlocest | train | 2 | |
3f31cc61ce42c8bff65299ebaa2803b1218af43c | [
"self.url = url\nself.username = username\nself.password = password\nself.contexts = []\nif isinstance(contexts, list):\n self.contexts = contexts",
"if metric_name in self.contexts:\n return metric_name\nreturn 'default'",
"data_regex = '\\n ^[a-z\\\\s]+:\\\\s*\\n (?P<active_connect... | <|body_start_0|>
self.url = url
self.username = username
self.password = password
self.contexts = []
if isinstance(contexts, list):
self.contexts = contexts
<|end_body_0|>
<|body_start_1|>
if metric_name in self.contexts:
return metric_name
... | This ressource manage data in Nginx stub status page | StubStatusPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StubStatusPage:
"""This ressource manage data in Nginx stub status page"""
def __init__(self, url='', username='', password='', contexts=None):
"""Initialize ressource attributes :param url: Nginx stub status url :param username: Username authorized to view stats :param password: Pas... | stack_v2_sparse_classes_75kplus_train_002681 | 3,072 | no_license | [
{
"docstring": "Initialize ressource attributes :param url: Nginx stub status url :param username: Username authorized to view stats :param password: Password of username authorized to view stats :param contexts: Managed contexts for probe metrics :type url: string :type username: string :type password: string ... | 4 | stack_v2_sparse_classes_30k_train_052704 | Implement the Python class `StubStatusPage` described below.
Class description:
This ressource manage data in Nginx stub status page
Method signatures and docstrings:
- def __init__(self, url='', username='', password='', contexts=None): Initialize ressource attributes :param url: Nginx stub status url :param usernam... | Implement the Python class `StubStatusPage` described below.
Class description:
This ressource manage data in Nginx stub status page
Method signatures and docstrings:
- def __init__(self, url='', username='', password='', contexts=None): Initialize ressource attributes :param url: Nginx stub status url :param usernam... | 947199bf8525f64d2765f3b4e4e0e59bc56b5208 | <|skeleton|>
class StubStatusPage:
"""This ressource manage data in Nginx stub status page"""
def __init__(self, url='', username='', password='', contexts=None):
"""Initialize ressource attributes :param url: Nginx stub status url :param username: Username authorized to view stats :param password: Pas... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StubStatusPage:
"""This ressource manage data in Nginx stub status page"""
def __init__(self, url='', username='', password='', contexts=None):
"""Initialize ressource attributes :param url: Nginx stub status url :param username: Username authorized to view stats :param password: Password of user... | the_stack_v2_python_sparse | temelio_monitoring/resource/webserver/nginx/stub_status_page.py | Temelio/monitoring-lib-python | train | 0 |
d23ea8bab831b937e29148470ddacfc9db8c6fd7 | [
"args = parser.parse(datasets_args, request)\nds = get_datasets(**args)\ndatasets = [str(d.id) for d in ds]\nreturn datasets",
"json_data = request.get_json(force=True)\nproduct = json_data['product']\nurls = json_data['dataset_definition_urls']\nstatuses = list(add_datasets([urls], product))\nreturn statuses"
] | <|body_start_0|>
args = parser.parse(datasets_args, request)
ds = get_datasets(**args)
datasets = [str(d.id) for d in ds]
return datasets
<|end_body_0|>
<|body_start_1|>
json_data = request.get_json(force=True)
product = json_data['product']
urls = json_data['dat... | The Datasets resource refers to groups of datasets which can be queried for by GET. Datasets can also be added to the datacube using a POST | Datasets | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Datasets:
"""The Datasets resource refers to groups of datasets which can be queried for by GET. Datasets can also be added to the datacube using a POST"""
def get(self):
"""Uses the args to construct a Datacube query to search for datasets. Returns an array of dataset ids."""
... | stack_v2_sparse_classes_75kplus_train_002682 | 2,766 | permissive | [
{
"docstring": "Uses the args to construct a Datacube query to search for datasets. Returns an array of dataset ids.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Attempts to add datasets to the datacube based on a product and dataset metadata urls",
"name": "post",
"s... | 2 | stack_v2_sparse_classes_30k_train_050554 | Implement the Python class `Datasets` described below.
Class description:
The Datasets resource refers to groups of datasets which can be queried for by GET. Datasets can also be added to the datacube using a POST
Method signatures and docstrings:
- def get(self): Uses the args to construct a Datacube query to search... | Implement the Python class `Datasets` described below.
Class description:
The Datasets resource refers to groups of datasets which can be queried for by GET. Datasets can also be added to the datacube using a POST
Method signatures and docstrings:
- def get(self): Uses the args to construct a Datacube query to search... | eaac847ca97335cc1cd718aae4eb1d10f84e38fd | <|skeleton|>
class Datasets:
"""The Datasets resource refers to groups of datasets which can be queried for by GET. Datasets can also be added to the datacube using a POST"""
def get(self):
"""Uses the args to construct a Datacube query to search for datasets. Returns an array of dataset ids."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Datasets:
"""The Datasets resource refers to groups of datasets which can be queried for by GET. Datasets can also be added to the datacube using a POST"""
def get(self):
"""Uses the args to construct a Datacube query to search for datasets. Returns an array of dataset ids."""
args = pars... | the_stack_v2_python_sparse | restcube/resources/datasets.py | opendatacube/restcube | train | 4 |
94b6996ca7ef0ba43cf6d29d954d385e685ecd56 | [
"self.ctx = None\nself.match = None\nself.cancel_btn = cancel_btn\nself.allowable_responses = allowable_responses\nself.canceled = False\nsuper().__init__(page_type='n/a', **kwrgs)",
"self.ctx = ctx\nchannel: discord.TextChannel = ctx.channel\nauthor: discord.Member = ctx.author\nmessage: discord.Message = ctx.me... | <|body_start_0|>
self.ctx = None
self.match = None
self.cancel_btn = cancel_btn
self.allowable_responses = allowable_responses
self.canceled = False
super().__init__(page_type='n/a', **kwrgs)
<|end_body_0|>
<|body_start_1|>
self.ctx = ctx
channel: discord... | StringPage | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StringPage:
def __init__(self, allowable_responses: List[str], cancel_btn=True, **kwrgs):
"""Callback signature: ctx: commands.Context, page: reactMenu.Page"""
<|body_0|>
async def run(self, ctx: commands.Context):
"""Callback signature: page: reactMenu.Page"""
... | stack_v2_sparse_classes_75kplus_train_002683 | 22,253 | permissive | [
{
"docstring": "Callback signature: ctx: commands.Context, page: reactMenu.Page",
"name": "__init__",
"signature": "def __init__(self, allowable_responses: List[str], cancel_btn=True, **kwrgs)"
},
{
"docstring": "Callback signature: page: reactMenu.Page",
"name": "run",
"signature": "asy... | 4 | null | Implement the Python class `StringPage` described below.
Class description:
Implement the StringPage class.
Method signatures and docstrings:
- def __init__(self, allowable_responses: List[str], cancel_btn=True, **kwrgs): Callback signature: ctx: commands.Context, page: reactMenu.Page
- async def run(self, ctx: comma... | Implement the Python class `StringPage` described below.
Class description:
Implement the StringPage class.
Method signatures and docstrings:
- def __init__(self, allowable_responses: List[str], cancel_btn=True, **kwrgs): Callback signature: ctx: commands.Context, page: reactMenu.Page
- async def run(self, ctx: comma... | b68ab01610ac399aa2b7daa97d5d71dd0d1b19d6 | <|skeleton|>
class StringPage:
def __init__(self, allowable_responses: List[str], cancel_btn=True, **kwrgs):
"""Callback signature: ctx: commands.Context, page: reactMenu.Page"""
<|body_0|>
async def run(self, ctx: commands.Context):
"""Callback signature: page: reactMenu.Page"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StringPage:
def __init__(self, allowable_responses: List[str], cancel_btn=True, **kwrgs):
"""Callback signature: ctx: commands.Context, page: reactMenu.Page"""
self.ctx = None
self.match = None
self.cancel_btn = cancel_btn
self.allowable_responses = allowable_responses
... | the_stack_v2_python_sparse | src/uiElements.py | amadea-system/GabbyGums | train | 3 | |
118b13c4003ef41be67e7cf52bdc626f68c07633 | [
"xy = numpy.insert(x, 0, values=y, axis=1)\ndf = pandas.DataFrame.from_records(xy)\ncolumns = ['y']\ncolumns_x = ['x' + str(i) for i in range(x.shape[1])]\ncolumns.extend(columns_x)\ndf.columns = columns\ndf.to_excel(path)",
"columns = ['x' + str(i) for i in range(x.shape[1])]\ndf = pandas.DataFrame.from_records(... | <|body_start_0|>
xy = numpy.insert(x, 0, values=y, axis=1)
df = pandas.DataFrame.from_records(xy)
columns = ['y']
columns_x = ['x' + str(i) for i in range(x.shape[1])]
columns.extend(columns_x)
df.columns = columns
df.to_excel(path)
<|end_body_0|>
<|body_start_1|... | ExcelTool | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExcelTool:
def saveXY2Excel(x, y, path='SALP_TRAIN_DATA.xlsx'):
""":param self: :param x: :param y: :param path: 输出excel路径 :return:"""
<|body_0|>
def saveX2Excel(x, path='SALP_PREDICT_DATA.xlsx'):
"""存储预测数据集 :param x: :param path: :return:"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_002684 | 1,144 | no_license | [
{
"docstring": ":param self: :param x: :param y: :param path: 输出excel路径 :return:",
"name": "saveXY2Excel",
"signature": "def saveXY2Excel(x, y, path='SALP_TRAIN_DATA.xlsx')"
},
{
"docstring": "存储预测数据集 :param x: :param path: :return:",
"name": "saveX2Excel",
"signature": "def saveX2Excel(... | 3 | stack_v2_sparse_classes_30k_train_030262 | Implement the Python class `ExcelTool` described below.
Class description:
Implement the ExcelTool class.
Method signatures and docstrings:
- def saveXY2Excel(x, y, path='SALP_TRAIN_DATA.xlsx'): :param self: :param x: :param y: :param path: 输出excel路径 :return:
- def saveX2Excel(x, path='SALP_PREDICT_DATA.xlsx'): 存储预测数... | Implement the Python class `ExcelTool` described below.
Class description:
Implement the ExcelTool class.
Method signatures and docstrings:
- def saveXY2Excel(x, y, path='SALP_TRAIN_DATA.xlsx'): :param self: :param x: :param y: :param path: 输出excel路径 :return:
- def saveX2Excel(x, path='SALP_PREDICT_DATA.xlsx'): 存储预测数... | 69b740332eaaecac553a4cc74c3e25f2af6889ac | <|skeleton|>
class ExcelTool:
def saveXY2Excel(x, y, path='SALP_TRAIN_DATA.xlsx'):
""":param self: :param x: :param y: :param path: 输出excel路径 :return:"""
<|body_0|>
def saveX2Excel(x, path='SALP_PREDICT_DATA.xlsx'):
"""存储预测数据集 :param x: :param path: :return:"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExcelTool:
def saveXY2Excel(x, y, path='SALP_TRAIN_DATA.xlsx'):
""":param self: :param x: :param y: :param path: 输出excel路径 :return:"""
xy = numpy.insert(x, 0, values=y, axis=1)
df = pandas.DataFrame.from_records(xy)
columns = ['y']
columns_x = ['x' + str(i) for i in ran... | the_stack_v2_python_sparse | data/excelTools.py | 9DemonFox/simpleLearning | train | 9 | |
4d3407e399f277451b0f08880eb9c75e5689f085 | [
"super(TrainableInitialState, self).__init__(name=name)\nwarnings.simplefilter('always', DeprecationWarning)\nwarnings.warn('Use the trainable flag in initial_state instead.', DeprecationWarning, stacklevel=2)\nif mask is not None:\n flat_mask = nest.flatten(mask)\n if not all([isinstance(m, bool) for m in fl... | <|body_start_0|>
super(TrainableInitialState, self).__init__(name=name)
warnings.simplefilter('always', DeprecationWarning)
warnings.warn('Use the trainable flag in initial_state instead.', DeprecationWarning, stacklevel=2)
if mask is not None:
flat_mask = nest.flatten(mask)
... | Helper Module that creates a learnable initial state for an RNNCore. This class receives an example (possibly nested) initial state of an RNNCore, and returns a state that has the same shape, structure, and values, but is trainable. Additionally, the user may specify a boolean mask that indicates which parts of the ini... | TrainableInitialState | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrainableInitialState:
"""Helper Module that creates a learnable initial state for an RNNCore. This class receives an example (possibly nested) initial state of an RNNCore, and returns a state that has the same shape, structure, and values, but is trainable. Additionally, the user may specify a b... | stack_v2_sparse_classes_75kplus_train_002685 | 14,770 | permissive | [
{
"docstring": "Constructs the Module that introduces a trainable state in the graph. It receives an initial state that will be used as the initial values for the trainable variables that the module contains, and optionally a mask that indicates the parts of the initial state that should be learnable. Args: ini... | 2 | stack_v2_sparse_classes_30k_train_037882 | Implement the Python class `TrainableInitialState` described below.
Class description:
Helper Module that creates a learnable initial state for an RNNCore. This class receives an example (possibly nested) initial state of an RNNCore, and returns a state that has the same shape, structure, and values, but is trainable.... | Implement the Python class `TrainableInitialState` described below.
Class description:
Helper Module that creates a learnable initial state for an RNNCore. This class receives an example (possibly nested) initial state of an RNNCore, and returns a state that has the same shape, structure, and values, but is trainable.... | 4e28fdf2ffd0eaefc0d23049106609421c9290b0 | <|skeleton|>
class TrainableInitialState:
"""Helper Module that creates a learnable initial state for an RNNCore. This class receives an example (possibly nested) initial state of an RNNCore, and returns a state that has the same shape, structure, and values, but is trainable. Additionally, the user may specify a b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TrainableInitialState:
"""Helper Module that creates a learnable initial state for an RNNCore. This class receives an example (possibly nested) initial state of an RNNCore, and returns a state that has the same shape, structure, and values, but is trainable. Additionally, the user may specify a boolean mask t... | the_stack_v2_python_sparse | sunset/sunset/python/modules/rnn_core.py | SynthAI/SynthAI | train | 3 |
b090ac2c51d41e6b815da6c38845a16289294893 | [
"msg = self.create_message(message)\ntry:\n msg.send(fail_silently=False)\nexcept smtplib.SMTPException as e:\n get_request_logger().exception(f'Failed sending plain text email:\\n{message}', exc_info=e)",
"msg = self.create_message(message)\nmsg.attach_alternative(message['html_render'], 'text/html')\ntry:... | <|body_start_0|>
msg = self.create_message(message)
try:
msg.send(fail_silently=False)
except smtplib.SMTPException as e:
get_request_logger().exception(f'Failed sending plain text email:\n{message}', exc_info=e)
<|end_body_0|>
<|body_start_1|>
msg = self.create_... | A consumer for sending async email messages. Contains two entry points - ``send_text`` and ``send_html`` - which create and send email messages given by the ``message`` dictionary, through Django Channels. The message object has several properties which are needed and some that are optional: * ``'type'`` [required]: Th... | EmailConsumer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailConsumer:
"""A consumer for sending async email messages. Contains two entry points - ``send_text`` and ``send_html`` - which create and send email messages given by the ``message`` dictionary, through Django Channels. The message object has several properties which are needed and some that ... | stack_v2_sparse_classes_75kplus_train_002686 | 5,324 | permissive | [
{
"docstring": "For sending a plaintext message. :param message: The message dictionary",
"name": "send_text",
"signature": "def send_text(self, message)"
},
{
"docstring": "For sending an HTML-rendered message. :param message: The message dictionary",
"name": "send_html",
"signature": "... | 3 | stack_v2_sparse_classes_30k_train_025686 | Implement the Python class `EmailConsumer` described below.
Class description:
A consumer for sending async email messages. Contains two entry points - ``send_text`` and ``send_html`` - which create and send email messages given by the ``message`` dictionary, through Django Channels. The message object has several pro... | Implement the Python class `EmailConsumer` described below.
Class description:
A consumer for sending async email messages. Contains two entry points - ``send_text`` and ``send_html`` - which create and send email messages given by the ``message`` dictionary, through Django Channels. The message object has several pro... | a90ac79f5756721c9a3864658a87fa62633dbc6c | <|skeleton|>
class EmailConsumer:
"""A consumer for sending async email messages. Contains two entry points - ``send_text`` and ``send_html`` - which create and send email messages given by the ``message`` dictionary, through Django Channels. The message object has several properties which are needed and some that ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EmailConsumer:
"""A consumer for sending async email messages. Contains two entry points - ``send_text`` and ``send_html`` - which create and send email messages given by the ``message`` dictionary, through Django Channels. The message object has several properties which are needed and some that are optional:... | the_stack_v2_python_sparse | src/mail/email.py | MAKENTNU/web | train | 12 |
0ffae585421dbf82dff641f549b86e9c8b75df7b | [
"self.filter_size = filter_size\nself.kernel_size = kernel_size\nself.strides = strides\nself.dilations = dilations\nself.pad_format = pad_format\nself.data_format = data_format\nself.kernel_init = kernel_init\nself.reuse = reuse\nself.dropout_rate = dropout_rate\nself.is_weight_norm = is_weight_norm\nself.is_batch... | <|body_start_0|>
self.filter_size = filter_size
self.kernel_size = kernel_size
self.strides = strides
self.dilations = dilations
self.pad_format = pad_format
self.data_format = data_format
self.kernel_init = kernel_init
self.reuse = reuse
self.drop... | CnnGLU | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CnnGLU:
def __init__(self, filter_size, kernel_size, strides=[1, 1, 1, 1], dilations=[1, 1, 1, 1], pad_format=constants.PAD_FORMAT_NORMAL, data_format='NHWC', kernel_init=tf.contrib.layers.xavier_initializer_conv2d(uniform=False), reuse=None, dropout_rate=0.1, is_weight_norm=False, is_batch_norm... | stack_v2_sparse_classes_75kplus_train_002687 | 6,782 | no_license | [
{
"docstring": "Args: filter_size: kernel_size: strides: dilations: padding: data_format: kernel_init: reuse: is_weight_norm: is_batch_norm: is_training: name:",
"name": "__init__",
"signature": "def __init__(self, filter_size, kernel_size, strides=[1, 1, 1, 1], dilations=[1, 1, 1, 1], pad_format=consta... | 2 | stack_v2_sparse_classes_30k_train_016826 | Implement the Python class `CnnGLU` described below.
Class description:
Implement the CnnGLU class.
Method signatures and docstrings:
- def __init__(self, filter_size, kernel_size, strides=[1, 1, 1, 1], dilations=[1, 1, 1, 1], pad_format=constants.PAD_FORMAT_NORMAL, data_format='NHWC', kernel_init=tf.contrib.layers.x... | Implement the Python class `CnnGLU` described below.
Class description:
Implement the CnnGLU class.
Method signatures and docstrings:
- def __init__(self, filter_size, kernel_size, strides=[1, 1, 1, 1], dilations=[1, 1, 1, 1], pad_format=constants.PAD_FORMAT_NORMAL, data_format='NHWC', kernel_init=tf.contrib.layers.x... | c8ed899b4941447b245efc2eda48831a668f7165 | <|skeleton|>
class CnnGLU:
def __init__(self, filter_size, kernel_size, strides=[1, 1, 1, 1], dilations=[1, 1, 1, 1], pad_format=constants.PAD_FORMAT_NORMAL, data_format='NHWC', kernel_init=tf.contrib.layers.xavier_initializer_conv2d(uniform=False), reuse=None, dropout_rate=0.1, is_weight_norm=False, is_batch_norm... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CnnGLU:
def __init__(self, filter_size, kernel_size, strides=[1, 1, 1, 1], dilations=[1, 1, 1, 1], pad_format=constants.PAD_FORMAT_NORMAL, data_format='NHWC', kernel_init=tf.contrib.layers.xavier_initializer_conv2d(uniform=False), reuse=None, dropout_rate=0.1, is_weight_norm=False, is_batch_norm=True, is_resi... | the_stack_v2_python_sparse | layers/common.py | rspanda1942/AiNLP | train | 1 | |
9c7759987f5b1a32aedf6cee1f23863d049d6cab | [
"with _Record.lock:\n with open(_Record.file, 'a+') as f:\n try:\n f.seek(0)\n r = json.load(f)\n except Exception as _:\n r = {}\n json.dump(r, f)\nreturn r",
"with _Record.lock:\n with open(_Record.file, 'r+') as f:\n r = json.load(f)\n ... | <|body_start_0|>
with _Record.lock:
with open(_Record.file, 'a+') as f:
try:
f.seek(0)
r = json.load(f)
except Exception as _:
r = {}
json.dump(r, f)
return r
<|end_body_0|>
<|bod... | Default tasks record handler Will read/write from/to ./tasks.json | _Record | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Record:
"""Default tasks record handler Will read/write from/to ./tasks.json"""
def read():
"""Reads persistence record to dict Returns dict"""
<|body_0|>
def write(name, le):
"""Writes record to record_handler name (str): name of task le (str): str() cast of da... | stack_v2_sparse_classes_75kplus_train_002688 | 13,873 | permissive | [
{
"docstring": "Reads persistence record to dict Returns dict",
"name": "read",
"signature": "def read()"
},
{
"docstring": "Writes record to record_handler name (str): name of task le (str): str() cast of datetime.datetime object for last execution Does not return",
"name": "write",
"si... | 2 | stack_v2_sparse_classes_30k_train_002904 | Implement the Python class `_Record` described below.
Class description:
Default tasks record handler Will read/write from/to ./tasks.json
Method signatures and docstrings:
- def read(): Reads persistence record to dict Returns dict
- def write(name, le): Writes record to record_handler name (str): name of task le (s... | Implement the Python class `_Record` described below.
Class description:
Default tasks record handler Will read/write from/to ./tasks.json
Method signatures and docstrings:
- def read(): Reads persistence record to dict Returns dict
- def write(name, le): Writes record to record_handler name (str): name of task le (s... | 6c42679cc129656e9216fc847e5839d6496dc452 | <|skeleton|>
class _Record:
"""Default tasks record handler Will read/write from/to ./tasks.json"""
def read():
"""Reads persistence record to dict Returns dict"""
<|body_0|>
def write(name, le):
"""Writes record to record_handler name (str): name of task le (str): str() cast of da... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _Record:
"""Default tasks record handler Will read/write from/to ./tasks.json"""
def read():
"""Reads persistence record to dict Returns dict"""
with _Record.lock:
with open(_Record.file, 'a+') as f:
try:
f.seek(0)
r = js... | the_stack_v2_python_sparse | lib/cherrypyscheduler.py | sinopsysHK/Watcher3 | train | 0 |
099cb67cd295cd3c425fc8aaac0ce577b8b72c80 | [
"downsample_raito = H // SparseHelper._cur_active.shape[-1]\nactive_ex = SparseHelper._cur_active.repeat_interleave(downsample_raito, 2).repeat_interleave(downsample_raito, 3)\nreturn active_ex if returning_active_map else active_ex.squeeze(1).nonzero(as_tuple=True)",
"x = super(type(self), self).forward(x)\nx *=... | <|body_start_0|>
downsample_raito = H // SparseHelper._cur_active.shape[-1]
active_ex = SparseHelper._cur_active.repeat_interleave(downsample_raito, 2).repeat_interleave(downsample_raito, 3)
return active_ex if returning_active_map else active_ex.squeeze(1).nonzero(as_tuple=True)
<|end_body_0|>
... | The helper to compute sparse operation with pytorch, such as sparse convlolution, sparse batch norm, etc. | SparseHelper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparseHelper:
"""The helper to compute sparse operation with pytorch, such as sparse convlolution, sparse batch norm, etc."""
def _get_active_map_or_index(H: int, returning_active_map: bool=True) -> torch.Tensor:
"""Get current active map with (B, 1, f, f) shape or index format."""
... | stack_v2_sparse_classes_75kplus_train_002689 | 5,428 | permissive | [
{
"docstring": "Get current active map with (B, 1, f, f) shape or index format.",
"name": "_get_active_map_or_index",
"signature": "def _get_active_map_or_index(H: int, returning_active_map: bool=True) -> torch.Tensor"
},
{
"docstring": "Sparse convolution forward function.",
"name": "sp_con... | 3 | stack_v2_sparse_classes_30k_train_004521 | Implement the Python class `SparseHelper` described below.
Class description:
The helper to compute sparse operation with pytorch, such as sparse convlolution, sparse batch norm, etc.
Method signatures and docstrings:
- def _get_active_map_or_index(H: int, returning_active_map: bool=True) -> torch.Tensor: Get current... | Implement the Python class `SparseHelper` described below.
Class description:
The helper to compute sparse operation with pytorch, such as sparse convlolution, sparse batch norm, etc.
Method signatures and docstrings:
- def _get_active_map_or_index(H: int, returning_active_map: bool=True) -> torch.Tensor: Get current... | d2ccc44a2c8e5d49bb26187aff42f2abc90aee28 | <|skeleton|>
class SparseHelper:
"""The helper to compute sparse operation with pytorch, such as sparse convlolution, sparse batch norm, etc."""
def _get_active_map_or_index(H: int, returning_active_map: bool=True) -> torch.Tensor:
"""Get current active map with (B, 1, f, f) shape or index format."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SparseHelper:
"""The helper to compute sparse operation with pytorch, such as sparse convlolution, sparse batch norm, etc."""
def _get_active_map_or_index(H: int, returning_active_map: bool=True) -> torch.Tensor:
"""Get current active map with (B, 1, f, f) shape or index format."""
downsa... | the_stack_v2_python_sparse | mmpretrain/models/utils/sparse_modules.py | open-mmlab/mmpretrain | train | 652 |
2e2afaa27e13649842730b6121168d0be50de07d | [
"if self.getInputType() in ['area', 'text']:\n return {}\naggregate_answers = {}\noptions = self.getAnswerOptions()\nfor option in options:\n aggregate_answers[option] = 0\nfor k, answer in self.answers.items():\n if answer['value']:\n if isinstance(answer['value'], str):\n try:\n ... | <|body_start_0|>
if self.getInputType() in ['area', 'text']:
return {}
aggregate_answers = {}
options = self.getAnswerOptions()
for option in options:
aggregate_answers[option] = 0
for k, answer in self.answers.items():
if answer['value']:
... | A question with select vocab within a survey | SurveySelectQuestion | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SurveySelectQuestion:
"""A question with select vocab within a survey"""
def getAggregateAnswers(self):
"""Return a mapping of aggregrate answer values, suitable for a histogram"""
<|body_0|>
def getPercentageAnswers(self):
"""Return a mapping of aggregrate answe... | stack_v2_sparse_classes_75kplus_train_002690 | 3,350 | no_license | [
{
"docstring": "Return a mapping of aggregrate answer values, suitable for a histogram",
"name": "getAggregateAnswers",
"signature": "def getAggregateAnswers(self)"
},
{
"docstring": "Return a mapping of aggregrate answer values, suitable for a barchart",
"name": "getPercentageAnswers",
... | 2 | stack_v2_sparse_classes_30k_train_029196 | Implement the Python class `SurveySelectQuestion` described below.
Class description:
A question with select vocab within a survey
Method signatures and docstrings:
- def getAggregateAnswers(self): Return a mapping of aggregrate answer values, suitable for a histogram
- def getPercentageAnswers(self): Return a mappin... | Implement the Python class `SurveySelectQuestion` described below.
Class description:
A question with select vocab within a survey
Method signatures and docstrings:
- def getAggregateAnswers(self): Return a mapping of aggregrate answer values, suitable for a histogram
- def getPercentageAnswers(self): Return a mappin... | b5c7e770e0616c0a5f1d5e13b5fca978a8721a9a | <|skeleton|>
class SurveySelectQuestion:
"""A question with select vocab within a survey"""
def getAggregateAnswers(self):
"""Return a mapping of aggregrate answer values, suitable for a histogram"""
<|body_0|>
def getPercentageAnswers(self):
"""Return a mapping of aggregrate answe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SurveySelectQuestion:
"""A question with select vocab within a survey"""
def getAggregateAnswers(self):
"""Return a mapping of aggregrate answer values, suitable for a histogram"""
if self.getInputType() in ['area', 'text']:
return {}
aggregate_answers = {}
opt... | the_stack_v2_python_sparse | products/PloneSurvey/content/.svn/text-base/SurveySelectQuestion.py.svn-base | cislgov/cisl.portal.plone25 | train | 0 |
2fdd641c3d0a9d739289256755c8d9aca2bb94a0 | [
"if self._listeners is None:\n self._listeners = weakref.WeakValueDictionary()\nself._listeners[id(listener)] = listener",
"if self._listeners is None:\n return\nwith ignored(KeyError):\n del self._listeners[id(listener)]",
"if self._listeners is None:\n return\nmethod_name = '_update_{0}'.format(no... | <|body_start_0|>
if self._listeners is None:
self._listeners = weakref.WeakValueDictionary()
self._listeners[id(listener)] = listener
<|end_body_0|>
<|body_start_1|>
if self._listeners is None:
return
with ignored(KeyError):
del self._listeners[id(lis... | Mixin class that provides services by which objects can register listeners to changes on that object. All methods provided by this class are underscored, since this is intended for internal use to communicate between classes in a generic way, and is not machinery that should be exposed to users of the classes involved.... | NotifierMixin | [
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NotifierMixin:
"""Mixin class that provides services by which objects can register listeners to changes on that object. All methods provided by this class are underscored, since this is intended for internal use to communicate between classes in a generic way, and is not machinery that should be ... | stack_v2_sparse_classes_75kplus_train_002691 | 31,014 | permissive | [
{
"docstring": "Add an object to the list of listeners to notify of changes to this object. This adds a weakref to the list of listeners that is removed from the listeners list when the listener has no other references to it.",
"name": "_add_listener",
"signature": "def _add_listener(self, listener)"
... | 4 | stack_v2_sparse_classes_30k_val_000701 | Implement the Python class `NotifierMixin` described below.
Class description:
Mixin class that provides services by which objects can register listeners to changes on that object. All methods provided by this class are underscored, since this is intended for internal use to communicate between classes in a generic wa... | Implement the Python class `NotifierMixin` described below.
Class description:
Mixin class that provides services by which objects can register listeners to changes on that object. All methods provided by this class are underscored, since this is intended for internal use to communicate between classes in a generic wa... | 2c9002f16bb5c265e0d14f4a2314c86eeaa35cb6 | <|skeleton|>
class NotifierMixin:
"""Mixin class that provides services by which objects can register listeners to changes on that object. All methods provided by this class are underscored, since this is intended for internal use to communicate between classes in a generic way, and is not machinery that should be ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NotifierMixin:
"""Mixin class that provides services by which objects can register listeners to changes on that object. All methods provided by this class are underscored, since this is intended for internal use to communicate between classes in a generic way, and is not machinery that should be exposed to us... | the_stack_v2_python_sparse | pkgs/astropy-1.1.2-np110py27_0/lib/python2.7/site-packages/astropy/io/fits/util.py | wangyum/Anaconda | train | 11 |
5c89dd72f82519ccefbcd48bf30935519ead0ae3 | [
"SlipTimeFn.__init__(self, name)\nModuleBruneSlipFn.__init__(self)\nself._loggingPrefix = 'BrSF '\nreturn",
"SlipTimeFn._configure(self)\nModuleBruneSlipFn.dbFinalSlip(self, self.inventory.dbSlip)\nModuleBruneSlipFn.dbSlipTime(self, self.inventory.dbSlipTime)\nModuleBruneSlipFn.dbRiseTime(self, self.inventory.dbR... | <|body_start_0|>
SlipTimeFn.__init__(self, name)
ModuleBruneSlipFn.__init__(self)
self._loggingPrefix = 'BrSF '
return
<|end_body_0|>
<|body_start_1|>
SlipTimeFn._configure(self)
ModuleBruneSlipFn.dbFinalSlip(self, self.inventory.dbSlip)
ModuleBruneSlipFn.dbSlipT... | Python object for slip time function that follows the integral of Brune's (1970) far-field time function. Inventory Properties @li None Facilities @li slip Spatial database of final slip @li slip_time Spatial database of slip initiation time @li rise_time Spatial database of rise time Factory: slip_time_fn | BruneSlipFn | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BruneSlipFn:
"""Python object for slip time function that follows the integral of Brune's (1970) far-field time function. Inventory Properties @li None Facilities @li slip Spatial database of final slip @li slip_time Spatial database of slip initiation time @li rise_time Spatial databas... | stack_v2_sparse_classes_75kplus_train_002692 | 2,807 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, name='bruneslipfn')"
},
{
"docstring": "Setup members using inventory.",
"name": "_configure",
"signature": "def _configure(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_033704 | Implement the Python class `BruneSlipFn` described below.
Class description:
Python object for slip time function that follows the integral of Brune's (1970) far-field time function. Inventory Properties @li None Facilities @li slip Spatial database of final slip @li slip_time Spatial database of slip initiati... | Implement the Python class `BruneSlipFn` described below.
Class description:
Python object for slip time function that follows the integral of Brune's (1970) far-field time function. Inventory Properties @li None Facilities @li slip Spatial database of final slip @li slip_time Spatial database of slip initiati... | 67bfe2e75e0a20bb55c93eb98bef7a9b3694523a | <|skeleton|>
class BruneSlipFn:
"""Python object for slip time function that follows the integral of Brune's (1970) far-field time function. Inventory Properties @li None Facilities @li slip Spatial database of final slip @li slip_time Spatial database of slip initiation time @li rise_time Spatial databas... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BruneSlipFn:
"""Python object for slip time function that follows the integral of Brune's (1970) far-field time function. Inventory Properties @li None Facilities @li slip Spatial database of final slip @li slip_time Spatial database of slip initiation time @li rise_time Spatial database of rise tim... | the_stack_v2_python_sparse | pylith/faults/obsolete/BruneSlipFn.py | fjiaqi/pylith | train | 0 |
c4c280497a3fbe85c495333b651fa757d0cf8658 | [
"def to_tree(i, j):\n if j < i:\n return None\n m = i + (j - i) // 2\n return TreeNode(nums[m], left=to_tree(i, m - 1), right=to_tree(m + 1, j))\nreturn to_tree(0, len(nums) - 1)",
"def build(i, j):\n if j < i:\n return None\n m = i + (j - i) // 2\n root = TreeNode(nums[m])\n ro... | <|body_start_0|>
def to_tree(i, j):
if j < i:
return None
m = i + (j - i) // 2
return TreeNode(nums[m], left=to_tree(i, m - 1), right=to_tree(m + 1, j))
return to_tree(0, len(nums) - 1)
<|end_body_0|>
<|body_start_1|>
def build(i, j):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
"""08/19/2021 12:17"""
<|body_0|>
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
"""08/21/2022 15:11"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def... | stack_v2_sparse_classes_75kplus_train_002693 | 2,331 | no_license | [
{
"docstring": "08/19/2021 12:17",
"name": "sortedArrayToBST",
"signature": "def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]"
},
{
"docstring": "08/21/2022 15:11",
"name": "sortedArrayToBST",
"signature": "def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode... | 2 | stack_v2_sparse_classes_30k_train_004671 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]: 08/19/2021 12:17
- def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]: 08/21/2022 15:11 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]: 08/19/2021 12:17
- def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]: 08/21/2022 15:11
<|skele... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
"""08/19/2021 12:17"""
<|body_0|>
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
"""08/21/2022 15:11"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
"""08/19/2021 12:17"""
def to_tree(i, j):
if j < i:
return None
m = i + (j - i) // 2
return TreeNode(nums[m], left=to_tree(i, m - 1), right=to_tree(m + 1, j))
... | the_stack_v2_python_sparse | leetcode/solved/108_Convert_Sorted_Array_to_Binary_Search_Tree/solution.py | sungminoh/algorithms | train | 0 | |
d72bc8e27e47c53a573a879914cdd3cc7fd3e4de | [
"progress_report.query_finished_count = 0\nprogress_report.query_total_count = len(resources)\nfor resource in resources:\n _LOG.info('Retrieving URL <%s>' % resource['url'])\n progress_report.current_query = resource['url']\n progress_report.update_progress()\n if in_memory:\n content = InMemory... | <|body_start_0|>
progress_report.query_finished_count = 0
progress_report.query_total_count = len(resources)
for resource in resources:
_LOG.info('Retrieving URL <%s>' % resource['url'])
progress_report.current_query = resource['url']
progress_report.update_pr... | Used when the source for deb packages is a remote source over HTTP. | HttpDownloader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HttpDownloader:
"""Used when the source for deb packages is a remote source over HTTP."""
def download_resources(self, resources, progress_report, in_memory=False):
"""Retrieves all metadata documents needed to fulfill the configuration set for the repository. The progress report wil... | stack_v2_sparse_classes_75kplus_train_002694 | 7,035 | no_license | [
{
"docstring": "Retrieves all metadata documents needed to fulfill the configuration set for the repository. The progress report will be updated as the downloads take place. :param progress_report: used to communicate the progress of this operation :type progress_report: pulp_deb.importer.sync_progress.Progress... | 3 | stack_v2_sparse_classes_30k_train_034091 | Implement the Python class `HttpDownloader` described below.
Class description:
Used when the source for deb packages is a remote source over HTTP.
Method signatures and docstrings:
- def download_resources(self, resources, progress_report, in_memory=False): Retrieves all metadata documents needed to fulfill the conf... | Implement the Python class `HttpDownloader` described below.
Class description:
Used when the source for deb packages is a remote source over HTTP.
Method signatures and docstrings:
- def download_resources(self, resources, progress_report, in_memory=False): Retrieves all metadata documents needed to fulfill the conf... | 8a713c3ca39b8317d6beb355156dc1d0cc6c2ec2 | <|skeleton|>
class HttpDownloader:
"""Used when the source for deb packages is a remote source over HTTP."""
def download_resources(self, resources, progress_report, in_memory=False):
"""Retrieves all metadata documents needed to fulfill the configuration set for the repository. The progress report wil... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HttpDownloader:
"""Used when the source for deb packages is a remote source over HTTP."""
def download_resources(self, resources, progress_report, in_memory=False):
"""Retrieves all metadata documents needed to fulfill the configuration set for the repository. The progress report will be updated ... | the_stack_v2_python_sparse | pulp_deb_plugins/pulp_deb/plugins/importers/downloaders/web.py | ekarlso/pulp_deb | train | 3 |
39adad70f87fcde5a6fa3503fa58835bcf195f43 | [
"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... | A set of methods for managing access keys. | AccessKeyServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccessKeyServiceServicer:
"""A set of methods for managing access keys."""
def List(self, request, context):
"""Retrieves the list of access keys for the specified service account."""
<|body_0|>
def Get(self, request, context):
"""Returns the specified access key... | stack_v2_sparse_classes_75kplus_train_002695 | 13,154 | permissive | [
{
"docstring": "Retrieves the list of access keys for the specified service account.",
"name": "List",
"signature": "def List(self, request, context)"
},
{
"docstring": "Returns the specified access key. To get the list of available access keys, make a [List] request.",
"name": "Get",
"s... | 6 | stack_v2_sparse_classes_30k_train_025076 | Implement the Python class `AccessKeyServiceServicer` described below.
Class description:
A set of methods for managing access keys.
Method signatures and docstrings:
- def List(self, request, context): Retrieves the list of access keys for the specified service account.
- def Get(self, request, context): Returns the... | Implement the Python class `AccessKeyServiceServicer` described below.
Class description:
A set of methods for managing access keys.
Method signatures and docstrings:
- def List(self, request, context): Retrieves the list of access keys for the specified service account.
- def Get(self, request, context): Returns the... | b906a014dd893e2697864e1e48e814a8d9fbc48c | <|skeleton|>
class AccessKeyServiceServicer:
"""A set of methods for managing access keys."""
def List(self, request, context):
"""Retrieves the list of access keys for the specified service account."""
<|body_0|>
def Get(self, request, context):
"""Returns the specified access key... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AccessKeyServiceServicer:
"""A set of methods for managing access keys."""
def List(self, request, context):
"""Retrieves the list of access keys for the specified service account."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
... | the_stack_v2_python_sparse | yandex/cloud/iam/v1/awscompatibility/access_key_service_pb2_grpc.py | yandex-cloud/python-sdk | train | 63 |
f5a615e72c74adf8d5893e8f0653619674a66740 | [
"Common = Configuration(self.driver)\nCommon.buttonConfiguration()\nCommon.buttonCommon()",
"FileName = self.rdmstr('测试添加', 4)\nself.enterCommon()\nDC = DataCatalog(self.driver)\nDC.buttonDataCatalog()\nDC.buttonAdd()\nDC.inputName(FileName)\nDC.buttonEnterAdd()\nDC.inputSearchName(FileName)\nDC.buttonEnterSearch... | <|body_start_0|>
Common = Configuration(self.driver)
Common.buttonConfiguration()
Common.buttonCommon()
<|end_body_0|>
<|body_start_1|>
FileName = self.rdmstr('测试添加', 4)
self.enterCommon()
DC = DataCatalog(self.driver)
DC.buttonDataCatalog()
DC.buttonAdd(... | TestConfiguration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestConfiguration:
def enterCommon(self):
"""点击应用配置,点击通用 :return:"""
<|body_0|>
def test_DataCatalog(self):
"""资料目录测试用例"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Common = Configuration(self.driver)
Common.buttonConfiguration()
... | stack_v2_sparse_classes_75kplus_train_002696 | 2,084 | no_license | [
{
"docstring": "点击应用配置,点击通用 :return:",
"name": "enterCommon",
"signature": "def enterCommon(self)"
},
{
"docstring": "资料目录测试用例",
"name": "test_DataCatalog",
"signature": "def test_DataCatalog(self)"
}
] | 2 | null | Implement the Python class `TestConfiguration` described below.
Class description:
Implement the TestConfiguration class.
Method signatures and docstrings:
- def enterCommon(self): 点击应用配置,点击通用 :return:
- def test_DataCatalog(self): 资料目录测试用例 | Implement the Python class `TestConfiguration` described below.
Class description:
Implement the TestConfiguration class.
Method signatures and docstrings:
- def enterCommon(self): 点击应用配置,点击通用 :return:
- def test_DataCatalog(self): 资料目录测试用例
<|skeleton|>
class TestConfiguration:
def enterCommon(self):
""... | b7d67334ba242fa7222f82ad95b2f7eb69400f9c | <|skeleton|>
class TestConfiguration:
def enterCommon(self):
"""点击应用配置,点击通用 :return:"""
<|body_0|>
def test_DataCatalog(self):
"""资料目录测试用例"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestConfiguration:
def enterCommon(self):
"""点击应用配置,点击通用 :return:"""
Common = Configuration(self.driver)
Common.buttonConfiguration()
Common.buttonCommon()
def test_DataCatalog(self):
"""资料目录测试用例"""
FileName = self.rdmstr('测试添加', 4)
self.enterCommon... | the_stack_v2_python_sparse | CenterTestUI/TestCase/test_Configuration_Page.py | Simonluepang/Script | train | 1 | |
542a60efe2a2bf740d3d5d7cf8bab60b81881e66 | [
"super(MuezzinCarousel, self).__init__(**kwargs)\nself.information_screen = InformationScreen(config_handler)\nself.main_screen = MainScreen(audio_player, config_handler)\nself.settings_screen = SettingsScreen(config_handler)\nself.add_widget(self.information_screen)\nself.add_widget(self.main_screen)\nself.add_wid... | <|body_start_0|>
super(MuezzinCarousel, self).__init__(**kwargs)
self.information_screen = InformationScreen(config_handler)
self.main_screen = MainScreen(audio_player, config_handler)
self.settings_screen = SettingsScreen(config_handler)
self.add_widget(self.information_screen)
... | Defines a Carousel that swipes left/right and holds an InformationScreen, MainScreen and SettingsScreen. | MuezzinCarousel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MuezzinCarousel:
"""Defines a Carousel that swipes left/right and holds an InformationScreen, MainScreen and SettingsScreen."""
def __init__(self, audio_player, config_handler, **kwargs):
"""Creates a MuezzinCarousel. :param kwargs: Kwargs for MDGridLayout"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_002697 | 1,325 | permissive | [
{
"docstring": "Creates a MuezzinCarousel. :param kwargs: Kwargs for MDGridLayout",
"name": "__init__",
"signature": "def __init__(self, audio_player, config_handler, **kwargs)"
},
{
"docstring": "Updates different widgets when the Carousel index changes to the corresponding respective widget :p... | 2 | null | Implement the Python class `MuezzinCarousel` described below.
Class description:
Defines a Carousel that swipes left/right and holds an InformationScreen, MainScreen and SettingsScreen.
Method signatures and docstrings:
- def __init__(self, audio_player, config_handler, **kwargs): Creates a MuezzinCarousel. :param kw... | Implement the Python class `MuezzinCarousel` described below.
Class description:
Defines a Carousel that swipes left/right and holds an InformationScreen, MainScreen and SettingsScreen.
Method signatures and docstrings:
- def __init__(self, audio_player, config_handler, **kwargs): Creates a MuezzinCarousel. :param kw... | 95f51ae4c3b64d2c49fe76d8bd599bec8471ac03 | <|skeleton|>
class MuezzinCarousel:
"""Defines a Carousel that swipes left/right and holds an InformationScreen, MainScreen and SettingsScreen."""
def __init__(self, audio_player, config_handler, **kwargs):
"""Creates a MuezzinCarousel. :param kwargs: Kwargs for MDGridLayout"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MuezzinCarousel:
"""Defines a Carousel that swipes left/right and holds an InformationScreen, MainScreen and SettingsScreen."""
def __init__(self, audio_player, config_handler, **kwargs):
"""Creates a MuezzinCarousel. :param kwargs: Kwargs for MDGridLayout"""
super(MuezzinCarousel, self).... | the_stack_v2_python_sparse | app/muezzin_carousel.py | mnadev/Muezzin | train | 2 |
744c7e645e0aef2810f5d4ae6839434df67af8e5 | [
"self['name'] = f'{firstNames[randint(0, len(firstNames) - 1)]}' + f' {lastNames[randint(0, len(lastNames) - 1)]}'\nself['strength']: int = 1\nself['crit_chance']: int = 5\nself['allies']: int = 0\nself['gold']: int = 0\nself['kill_count']: int = 0",
"if self['gold'] < cost:\n print_console('Insufficient gold'... | <|body_start_0|>
self['name'] = f'{firstNames[randint(0, len(firstNames) - 1)]}' + f' {lastNames[randint(0, len(lastNames) - 1)]}'
self['strength']: int = 1
self['crit_chance']: int = 5
self['allies']: int = 0
self['gold']: int = 0
self['kill_count']: int = 0
<|end_body_0... | This class tracks all values and methods realted to the PLAYER. | PlayerValues | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlayerValues:
"""This class tracks all values and methods realted to the PLAYER."""
def __init__(self):
"""Initialize the PLAYER with a random name and starting values."""
<|body_0|>
def upgrade(self, value, quantity, cost):
"""Use for easily creating upgrades.""... | stack_v2_sparse_classes_75kplus_train_002698 | 17,150 | no_license | [
{
"docstring": "Initialize the PLAYER with a random name and starting values.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Use for easily creating upgrades.",
"name": "upgrade",
"signature": "def upgrade(self, value, quantity, cost)"
}
] | 2 | stack_v2_sparse_classes_30k_train_030729 | Implement the Python class `PlayerValues` described below.
Class description:
This class tracks all values and methods realted to the PLAYER.
Method signatures and docstrings:
- def __init__(self): Initialize the PLAYER with a random name and starting values.
- def upgrade(self, value, quantity, cost): Use for easily... | Implement the Python class `PlayerValues` described below.
Class description:
This class tracks all values and methods realted to the PLAYER.
Method signatures and docstrings:
- def __init__(self): Initialize the PLAYER with a random name and starting values.
- def upgrade(self, value, quantity, cost): Use for easily... | e452817429195593e9c7cd89fe052bd8ed89943a | <|skeleton|>
class PlayerValues:
"""This class tracks all values and methods realted to the PLAYER."""
def __init__(self):
"""Initialize the PLAYER with a random name and starting values."""
<|body_0|>
def upgrade(self, value, quantity, cost):
"""Use for easily creating upgrades.""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PlayerValues:
"""This class tracks all values and methods realted to the PLAYER."""
def __init__(self):
"""Initialize the PLAYER with a random name and starting values."""
self['name'] = f'{firstNames[randint(0, len(firstNames) - 1)]}' + f' {lastNames[randint(0, len(lastNames) - 1)]}'
... | the_stack_v2_python_sparse | prosser_projects/tkinter/main.py | Keiyrti/python_projects | train | 0 |
b6c6d9c6c0350a8cf5e1027aa8c843127d9c157e | [
"logs.log_info('You are using the vgCa channel type: Ca_L2')\nself.time_unit = 1000.0\nself.vrev = 131.0\nTexpt = 36.0\nself.qt = 1.0\nself.m = 1.0 / (1 + np.exp((V - -30.0) / -6))\nself.h = 1.0 / (1 + np.exp((V - -80.0) / 6.4))\nself._mpower = 2\nself._hpower = 1",
"self._mInf = 1.0 / (1 + np.exp((V - -30.0) / -... | <|body_start_0|>
logs.log_info('You are using the vgCa channel type: Ca_L2')
self.time_unit = 1000.0
self.vrev = 131.0
Texpt = 36.0
self.qt = 1.0
self.m = 1.0 / (1 + np.exp((V - -30.0) / -6))
self.h = 1.0 / (1 + np.exp((V - -80.0) / 6.4))
self._mpower = 2
... | L-type calcium channel model Avery et al. L-type channels are higher-voltage activating and very persistent. They are commonly found in muscle or glands, where they induce activities such as hormone release or muscle contraction in response to neural stimulation. This channel has been modified to activate at more depol... | Ca_L2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ca_L2:
"""L-type calcium channel model Avery et al. L-type channels are higher-voltage activating and very persistent. They are commonly found in muscle or glands, where they induce activities such as hormone release or muscle contraction in response to neural stimulation. This channel has been m... | stack_v2_sparse_classes_75kplus_train_002699 | 22,487 | no_license | [
{
"docstring": "Run initialization calculation for m and h gates of the channel at starting Vmem value.",
"name": "_init_state",
"signature": "def _init_state(self, V)"
},
{
"docstring": "Update the state of m and h gates of the channel given their present value and present simulation Vmem.",
... | 2 | null | Implement the Python class `Ca_L2` described below.
Class description:
L-type calcium channel model Avery et al. L-type channels are higher-voltage activating and very persistent. They are commonly found in muscle or glands, where they induce activities such as hormone release or muscle contraction in response to neur... | Implement the Python class `Ca_L2` described below.
Class description:
L-type calcium channel model Avery et al. L-type channels are higher-voltage activating and very persistent. They are commonly found in muscle or glands, where they induce activities such as hormone release or muscle contraction in response to neur... | dd03ff5e3df3ef48d887a6566a6286fcd168880b | <|skeleton|>
class Ca_L2:
"""L-type calcium channel model Avery et al. L-type channels are higher-voltage activating and very persistent. They are commonly found in muscle or glands, where they induce activities such as hormone release or muscle contraction in response to neural stimulation. This channel has been m... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Ca_L2:
"""L-type calcium channel model Avery et al. L-type channels are higher-voltage activating and very persistent. They are commonly found in muscle or glands, where they induce activities such as hormone release or muscle contraction in response to neural stimulation. This channel has been modified to ac... | the_stack_v2_python_sparse | betse/science/channels/vg_ca.py | R-Stefano/betse-ml | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.