blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4ece046735739e3557e9a59bdccd0629bd8648e8 | [
"Canvas.__init__(self)\nself.configure(width=larg, height=haut)\nself.boss = boss\nself.larg = larg\nself.haut = haut\npas = (larg - 25) / 8\nfor t in range(0, 9):\n stx = 10 + t * pas\n self.create_line(stx, haut - 12, stx, 15, fill='grey')\npas = (haut - 25) / 10\nfor t in range(-5, 6):\n sty = haut / 2 ... | <|body_start_0|>
Canvas.__init__(self)
self.configure(width=larg, height=haut)
self.boss = boss
self.larg = larg
self.haut = haut
pas = (larg - 25) / 8
for t in range(0, 9):
stx = 10 + t * pas
self.create_line(stx, haut - 12, stx, 15, fill=... | Canevas pour le dessin de courbes élongation/temps | OscilloGraphe | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OscilloGraphe:
"""Canevas pour le dessin de courbes élongation/temps"""
def __init__(self, boss=None, larg=400, haut=350):
"""Constructeur du graphique : axes et échelle horizontale"""
<|body_0|>
def axes(self):
"""Création des axes de références"""
<|bod... | stack_v2_sparse_classes_36k_train_003000 | 3,176 | no_license | [
{
"docstring": "Constructeur du graphique : axes et échelle horizontale",
"name": "__init__",
"signature": "def __init__(self, boss=None, larg=400, haut=350)"
},
{
"docstring": "Création des axes de références",
"name": "axes",
"signature": "def axes(self)"
},
{
"docstring": "Tra... | 3 | stack_v2_sparse_classes_30k_train_014788 | Implement the Python class `OscilloGraphe` described below.
Class description:
Canevas pour le dessin de courbes élongation/temps
Method signatures and docstrings:
- def __init__(self, boss=None, larg=400, haut=350): Constructeur du graphique : axes et échelle horizontale
- def axes(self): Création des axes de référe... | Implement the Python class `OscilloGraphe` described below.
Class description:
Canevas pour le dessin de courbes élongation/temps
Method signatures and docstrings:
- def __init__(self, boss=None, larg=400, haut=350): Constructeur du graphique : axes et échelle horizontale
- def axes(self): Création des axes de référe... | 14b306447e227ddc5cb04b8819f388ca9f91a1d6 | <|skeleton|>
class OscilloGraphe:
"""Canevas pour le dessin de courbes élongation/temps"""
def __init__(self, boss=None, larg=400, haut=350):
"""Constructeur du graphique : axes et échelle horizontale"""
<|body_0|>
def axes(self):
"""Création des axes de références"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OscilloGraphe:
"""Canevas pour le dessin de courbes élongation/temps"""
def __init__(self, boss=None, larg=400, haut=350):
"""Constructeur du graphique : axes et échelle horizontale"""
Canvas.__init__(self)
self.configure(width=larg, height=haut)
self.boss = boss
s... | the_stack_v2_python_sparse | Course/Book/Programmer_avec_Python3/13-ClasseEtInterfacesGraphiques/oscillo.py | BjaouiAya/Cours-Python | train | 0 |
edc58cecc83ea494cd5301bda66b0d51b03f6718 | [
"solution_cells = []\nwith self.gradebook as gb:\n num_submissions = len(gb.notebook_submissions(notebook_id, assignment_id))\n notebook_id = gb.find_notebook(notebook_id, assignment_id).id\n for cell_name in gb.db.query(BaseCell.name).filter(BaseCell.type == 'SolutionCell').filter(BaseCell.notebook_id == ... | <|body_start_0|>
solution_cells = []
with self.gradebook as gb:
num_submissions = len(gb.notebook_submissions(notebook_id, assignment_id))
notebook_id = gb.find_notebook(notebook_id, assignment_id).id
for cell_name in gb.db.query(BaseCell.name).filter(BaseCell.type ==... | E2xAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class E2xAPI:
def get_solution_cell_ids(self, assignment_id, notebook_id):
"""Get information about the solution cells of a notebook given its name. Arguments --------- assignment_id: string The name of the assignment notebook_id: string The name of the notebook Returns ------- solution_cells:... | stack_v2_sparse_classes_36k_train_003001 | 6,177 | permissive | [
{
"docstring": "Get information about the solution cells of a notebook given its name. Arguments --------- assignment_id: string The name of the assignment notebook_id: string The name of the notebook Returns ------- solution_cells: dict A dictionary containing information about the solution cells",
"name":... | 2 | stack_v2_sparse_classes_30k_train_017271 | Implement the Python class `E2xAPI` described below.
Class description:
Implement the E2xAPI class.
Method signatures and docstrings:
- def get_solution_cell_ids(self, assignment_id, notebook_id): Get information about the solution cells of a notebook given its name. Arguments --------- assignment_id: string The name... | Implement the Python class `E2xAPI` described below.
Class description:
Implement the E2xAPI class.
Method signatures and docstrings:
- def get_solution_cell_ids(self, assignment_id, notebook_id): Get information about the solution cells of a notebook given its name. Arguments --------- assignment_id: string The name... | 19eb4662e4eee5ddef673097517e4bd4fb469e62 | <|skeleton|>
class E2xAPI:
def get_solution_cell_ids(self, assignment_id, notebook_id):
"""Get information about the solution cells of a notebook given its name. Arguments --------- assignment_id: string The name of the assignment notebook_id: string The name of the notebook Returns ------- solution_cells:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class E2xAPI:
def get_solution_cell_ids(self, assignment_id, notebook_id):
"""Get information about the solution cells of a notebook given its name. Arguments --------- assignment_id: string The name of the assignment notebook_id: string The name of the notebook Returns ------- solution_cells: dict A dictio... | the_stack_v2_python_sparse | e2xgrader/apps/api.py | divindevaiah/e2xgrader | train | 0 | |
58fbe93a10bcc00e2ad447d3b43ca662c1492758 | [
"count = 0\nresult = 0\n\ndef dfs(node):\n nonlocal count, result\n if node.left:\n dfs(node.left)\n if count >= k:\n return\n count += 1\n result = node.val\n if node.right:\n dfs(node.right)\ndfs(root)\nreturn result",
"def helper(node, stack):\n while node:\n st... | <|body_start_0|>
count = 0
result = 0
def dfs(node):
nonlocal count, result
if node.left:
dfs(node.left)
if count >= k:
return
count += 1
result = node.val
if node.right:
dfs(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
"""Recursive Inorder-Traversal, Time: O(H+k), Space: O(H)"""
<|body_0|>
def kthSmallest(self, root: TreeNode, k: int) -> int:
"""Iterative Inorder-Traversal, Time: O(H+k), Space: O(H)"""
<|body_1... | stack_v2_sparse_classes_36k_train_003002 | 1,262 | no_license | [
{
"docstring": "Recursive Inorder-Traversal, Time: O(H+k), Space: O(H)",
"name": "kthSmallest",
"signature": "def kthSmallest(self, root: TreeNode, k: int) -> int"
},
{
"docstring": "Iterative Inorder-Traversal, Time: O(H+k), Space: O(H)",
"name": "kthSmallest",
"signature": "def kthSmal... | 2 | stack_v2_sparse_classes_30k_train_018280 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest(self, root: TreeNode, k: int) -> int: Recursive Inorder-Traversal, Time: O(H+k), Space: O(H)
- def kthSmallest(self, root: TreeNode, k: int) -> int: Iterative Ino... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest(self, root: TreeNode, k: int) -> int: Recursive Inorder-Traversal, Time: O(H+k), Space: O(H)
- def kthSmallest(self, root: TreeNode, k: int) -> int: Iterative Ino... | 72136e3487d239f5b37e2d6393e034262a6bf599 | <|skeleton|>
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
"""Recursive Inorder-Traversal, Time: O(H+k), Space: O(H)"""
<|body_0|>
def kthSmallest(self, root: TreeNode, k: int) -> int:
"""Iterative Inorder-Traversal, Time: O(H+k), Space: O(H)"""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
"""Recursive Inorder-Traversal, Time: O(H+k), Space: O(H)"""
count = 0
result = 0
def dfs(node):
nonlocal count, result
if node.left:
dfs(node.left)
if count >= ... | the_stack_v2_python_sparse | python/230-Kth Smallest Element in a BST.py | cwza/leetcode | train | 0 | |
69d66ed6f7d9e8e5228640a545a247ffa900f14d | [
"shopify_partner = self.search([('shopify_customer_id', '=', customer.get('id')), ('shopify_instance_id', '=', instance.id)]) if customer.get('id') else False\nif not shopify_partner:\n odoo_partner = self.env['res.partner'].search([('email', '=', customer.get('email')), ('parent_id', '=', False)], limit=1)\nels... | <|body_start_0|>
shopify_partner = self.search([('shopify_customer_id', '=', customer.get('id')), ('shopify_instance_id', '=', instance.id)]) if customer.get('id') else False
if not shopify_partner:
odoo_partner = self.env['res.partner'].search([('email', '=', customer.get('email')), ('paren... | ShopifyResPartnerEpt | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShopifyResPartnerEpt:
def find_customer(self, instance, customer):
"""check_partner_contact_address :param instance: Object of instance :param customer: Response of the customer :return: It will return the odoo and Shopify customer object"""
<|body_0|>
def process_customers(... | stack_v2_sparse_classes_36k_train_003003 | 2,247 | no_license | [
{
"docstring": "check_partner_contact_address :param instance: Object of instance :param customer: Response of the customer :return: It will return the odoo and Shopify customer object",
"name": "find_customer",
"signature": "def find_customer(self, instance, customer)"
},
{
"docstring": ":param... | 2 | stack_v2_sparse_classes_30k_train_006641 | Implement the Python class `ShopifyResPartnerEpt` described below.
Class description:
Implement the ShopifyResPartnerEpt class.
Method signatures and docstrings:
- def find_customer(self, instance, customer): check_partner_contact_address :param instance: Object of instance :param customer: Response of the customer :... | Implement the Python class `ShopifyResPartnerEpt` described below.
Class description:
Implement the ShopifyResPartnerEpt class.
Method signatures and docstrings:
- def find_customer(self, instance, customer): check_partner_contact_address :param instance: Object of instance :param customer: Response of the customer :... | dd439232589631b3c59387ef22f21b5d8e724163 | <|skeleton|>
class ShopifyResPartnerEpt:
def find_customer(self, instance, customer):
"""check_partner_contact_address :param instance: Object of instance :param customer: Response of the customer :return: It will return the odoo and Shopify customer object"""
<|body_0|>
def process_customers(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShopifyResPartnerEpt:
def find_customer(self, instance, customer):
"""check_partner_contact_address :param instance: Object of instance :param customer: Response of the customer :return: It will return the odoo and Shopify customer object"""
shopify_partner = self.search([('shopify_customer_id... | the_stack_v2_python_sparse | shopify_ept/models/shopify_res_partner_ept.py | Darkmanzoro/nectarbeautyhub | train | 0 | |
d609e01f6e915ca8e050b5c402d04d3fa94858cc | [
"super().__init__(**kwargs)\nself.base_url = 'https://www.filmweb.pl'\nquery_part = '/search?q={title}'\nself.output = output\nself.start_urls.append(self.base_url + query_part.format(title=title))",
"href = response.xpath(\"//div[@id='searchResult']/descendant::a[@class='poster__link'][1]/@href\").get()\nif href... | <|body_start_0|>
super().__init__(**kwargs)
self.base_url = 'https://www.filmweb.pl'
query_part = '/search?q={title}'
self.output = output
self.start_urls.append(self.base_url + query_part.format(title=title))
<|end_body_0|>
<|body_start_1|>
href = response.xpath("//div[... | Movie spider for parsing basic information about movies. Attributes ---------- name : str name of the spider custom_settings : dict custom settings for the spider base_url : str base url of the site from which data will be parsed output : list list for holding parse result start_urls : list list for holding site urls t... | MovieSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovieSpider:
"""Movie spider for parsing basic information about movies. Attributes ---------- name : str name of the spider custom_settings : dict custom settings for the spider base_url : str base url of the site from which data will be parsed output : list list for holding parse result start_u... | stack_v2_sparse_classes_36k_train_003004 | 4,494 | no_license | [
{
"docstring": "Constructs all the necessary attributes for the spider. Parameters ---------- title : str title of the movie to be parsed output : list used for storing parse result",
"name": "__init__",
"signature": "def __init__(self, title, output, **kwargs)"
},
{
"docstring": "Parses informa... | 4 | stack_v2_sparse_classes_30k_train_021199 | Implement the Python class `MovieSpider` described below.
Class description:
Movie spider for parsing basic information about movies. Attributes ---------- name : str name of the spider custom_settings : dict custom settings for the spider base_url : str base url of the site from which data will be parsed output : lis... | Implement the Python class `MovieSpider` described below.
Class description:
Movie spider for parsing basic information about movies. Attributes ---------- name : str name of the spider custom_settings : dict custom settings for the spider base_url : str base url of the site from which data will be parsed output : lis... | 16e327e0e4d23f43410ead5426cf5a6caea7a12f | <|skeleton|>
class MovieSpider:
"""Movie spider for parsing basic information about movies. Attributes ---------- name : str name of the spider custom_settings : dict custom settings for the spider base_url : str base url of the site from which data will be parsed output : list list for holding parse result start_u... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MovieSpider:
"""Movie spider for parsing basic information about movies. Attributes ---------- name : str name of the spider custom_settings : dict custom settings for the spider base_url : str base url of the site from which data will be parsed output : list list for holding parse result start_urls : list li... | the_stack_v2_python_sparse | lab-4/util/scraper/movie_spider.py | WuTolas/pjwstk-nai | train | 0 |
daf0da5e037c656bf3e80c1fe035662a77b40a93 | [
"screen = self.kwargs.get('screen', 'dashboard')\nsection = self.kwargs.get('section', screen)\nunit = self.kwargs.get('unit', section)\nreturn [f'{BASE}/pages/{screen}/{unit}.html', f'{BASE}/pages/{screen}/{section}/{unit}.html', f'{BASE}/pages/{screen}/{section}.html', f'{BASE}/pages/{screen}/{screen}-{section}.h... | <|body_start_0|>
screen = self.kwargs.get('screen', 'dashboard')
section = self.kwargs.get('section', screen)
unit = self.kwargs.get('unit', section)
return [f'{BASE}/pages/{screen}/{unit}.html', f'{BASE}/pages/{screen}/{section}/{unit}.html', f'{BASE}/pages/{screen}/{section}.html', f'{... | Main view used for most console pages. | ConsoleView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConsoleView:
"""Main view used for most console pages."""
def get_template_names(self):
"""Get the screen's template based on the URL path, where the URL is segmented as: 'https://{base}/{screen}/{section}/{unit}/{part}/{piece}. A number of page template paths are tried, trying to ma... | stack_v2_sparse_classes_36k_train_003005 | 3,738 | permissive | [
{
"docstring": "Get the screen's template based on the URL path, where the URL is segmented as: 'https://{base}/{screen}/{section}/{unit}/{part}/{piece}. A number of page template paths are tried, trying to match a unit first, then section, then a screen-section, finally a screen. Screen-sections and sections a... | 2 | stack_v2_sparse_classes_30k_train_019859 | Implement the Python class `ConsoleView` described below.
Class description:
Main view used for most console pages.
Method signatures and docstrings:
- def get_template_names(self): Get the screen's template based on the URL path, where the URL is segmented as: 'https://{base}/{screen}/{section}/{unit}/{part}/{piece}... | Implement the Python class `ConsoleView` described below.
Class description:
Main view used for most console pages.
Method signatures and docstrings:
- def get_template_names(self): Get the screen's template based on the URL path, where the URL is segmented as: 'https://{base}/{screen}/{section}/{unit}/{part}/{piece}... | c266bc1169bef75214985901cd3165f415ad9ba7 | <|skeleton|>
class ConsoleView:
"""Main view used for most console pages."""
def get_template_names(self):
"""Get the screen's template based on the URL path, where the URL is segmented as: 'https://{base}/{screen}/{section}/{unit}/{part}/{piece}. A number of page template paths are tried, trying to ma... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConsoleView:
"""Main view used for most console pages."""
def get_template_names(self):
"""Get the screen's template based on the URL path, where the URL is segmented as: 'https://{base}/{screen}/{section}/{unit}/{part}/{piece}. A number of page template paths are tried, trying to match a unit fi... | the_stack_v2_python_sparse | console/views/main.py | mindthegrow/cannlytics | train | 0 |
813e9780eb35605bc7d37bea18a9d9762d5301f6 | [
"self.filename = filename\nself.nbr_words = 0\nself.nbr_chars = 0\nself.nbr_lines = 0\nself.zliczanie()",
"file = open(self.filename)\nfor line in file:\n line = line.strip('\\n')\n words = line.split()\n self.nbr_lines += 1\n self.nbr_words += len(words)\n self.nbr_chars += len(line)\nfile.close()... | <|body_start_0|>
self.filename = filename
self.nbr_words = 0
self.nbr_chars = 0
self.nbr_lines = 0
self.zliczanie()
<|end_body_0|>
<|body_start_1|>
file = open(self.filename)
for line in file:
line = line.strip('\n')
words = line.split()
... | Klasa obslugujaca zlicanie linijek, slow i znakow z pliku | Zlicz | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Zlicz:
"""Klasa obslugujaca zlicanie linijek, slow i znakow z pliku"""
def __init__(self, filename):
"""Inicjalizacja winna zawierac nazwe pliku do obslugi"""
<|body_0|>
def zliczanie(self):
"""Funkcja zliczajaca linijki, slowa i znaki z zainicjalizowanego pliku"... | stack_v2_sparse_classes_36k_train_003006 | 1,724 | no_license | [
{
"docstring": "Inicjalizacja winna zawierac nazwe pliku do obslugi",
"name": "__init__",
"signature": "def __init__(self, filename)"
},
{
"docstring": "Funkcja zliczajaca linijki, slowa i znaki z zainicjalizowanego pliku",
"name": "zliczanie",
"signature": "def zliczanie(self)"
},
{... | 3 | stack_v2_sparse_classes_30k_train_015895 | Implement the Python class `Zlicz` described below.
Class description:
Klasa obslugujaca zlicanie linijek, slow i znakow z pliku
Method signatures and docstrings:
- def __init__(self, filename): Inicjalizacja winna zawierac nazwe pliku do obslugi
- def zliczanie(self): Funkcja zliczajaca linijki, slowa i znaki z zain... | Implement the Python class `Zlicz` described below.
Class description:
Klasa obslugujaca zlicanie linijek, slow i znakow z pliku
Method signatures and docstrings:
- def __init__(self, filename): Inicjalizacja winna zawierac nazwe pliku do obslugi
- def zliczanie(self): Funkcja zliczajaca linijki, slowa i znaki z zain... | f79e4674ec7fe2f2272f000d7f1574bc95918912 | <|skeleton|>
class Zlicz:
"""Klasa obslugujaca zlicanie linijek, slow i znakow z pliku"""
def __init__(self, filename):
"""Inicjalizacja winna zawierac nazwe pliku do obslugi"""
<|body_0|>
def zliczanie(self):
"""Funkcja zliczajaca linijki, slowa i znaki z zainicjalizowanego pliku"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Zlicz:
"""Klasa obslugujaca zlicanie linijek, slow i znakow z pliku"""
def __init__(self, filename):
"""Inicjalizacja winna zawierac nazwe pliku do obslugi"""
self.filename = filename
self.nbr_words = 0
self.nbr_chars = 0
self.nbr_lines = 0
self.zliczanie()... | the_stack_v2_python_sparse | lab11/zad3.py | Kannute/Python | train | 0 |
4931febcdd902851eca7b9ac2810955bfea2edd7 | [
"if general_md is None:\n general_md = metadata_info.GeneralMd(name=_MODEL_NAME, description=_MODEL_DESCRIPTION)\nif input_md is None:\n input_md = metadata_info.BertInputTensorsMd(model_buffer, _DEFAULT_ID_NAME, _DEFAULT_MASK_NAME, _DEFAULT_SEGMENT_ID_NAME)\nif output_md is None:\n output_md = metadata_in... | <|body_start_0|>
if general_md is None:
general_md = metadata_info.GeneralMd(name=_MODEL_NAME, description=_MODEL_DESCRIPTION)
if input_md is None:
input_md = metadata_info.BertInputTensorsMd(model_buffer, _DEFAULT_ID_NAME, _DEFAULT_MASK_NAME, _DEFAULT_SEGMENT_ID_NAME)
if... | Writes metadata into the Bert NL classifier. | MetadataWriter | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later",
"MIT",
"LGPL-2.0-or-later",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetadataWriter:
"""Writes metadata into the Bert NL classifier."""
def create_from_metadata_info(cls, model_buffer: bytearray, general_md: Optional[metadata_info.GeneralMd]=None, input_md: Optional[metadata_info.BertInputTensorsMd]=None, output_md: Optional[metadata_info.ClassificationTensor... | stack_v2_sparse_classes_36k_train_003007 | 6,756 | permissive | [
{
"docstring": "Creates MetadataWriter based on general/input/output information. Args: model_buffer: valid buffer of the model file. general_md: general information about the model. If not specified, default general metadata will be generated. input_md: input tensor information. If not specified, default input... | 2 | stack_v2_sparse_classes_30k_train_012825 | Implement the Python class `MetadataWriter` described below.
Class description:
Writes metadata into the Bert NL classifier.
Method signatures and docstrings:
- def create_from_metadata_info(cls, model_buffer: bytearray, general_md: Optional[metadata_info.GeneralMd]=None, input_md: Optional[metadata_info.BertInputTen... | Implement the Python class `MetadataWriter` described below.
Class description:
Writes metadata into the Bert NL classifier.
Method signatures and docstrings:
- def create_from_metadata_info(cls, model_buffer: bytearray, general_md: Optional[metadata_info.GeneralMd]=None, input_md: Optional[metadata_info.BertInputTen... | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | <|skeleton|>
class MetadataWriter:
"""Writes metadata into the Bert NL classifier."""
def create_from_metadata_info(cls, model_buffer: bytearray, general_md: Optional[metadata_info.GeneralMd]=None, input_md: Optional[metadata_info.BertInputTensorsMd]=None, output_md: Optional[metadata_info.ClassificationTensor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MetadataWriter:
"""Writes metadata into the Bert NL classifier."""
def create_from_metadata_info(cls, model_buffer: bytearray, general_md: Optional[metadata_info.GeneralMd]=None, input_md: Optional[metadata_info.BertInputTensorsMd]=None, output_md: Optional[metadata_info.ClassificationTensorMd]=None):
... | the_stack_v2_python_sparse | third_party/tflite_support/src/tensorflow_lite_support/metadata/python/metadata_writers/bert_nl_classifier.py | chromium/chromium | train | 17,408 |
c20d2ccf360e6cb1a94ca8ae25e1b272f6706ba0 | [
"pygame.sprite.Sprite.__init__(self)\nself.image = pygame.image.load('Image/Trafico.png')\nself.rect = self.image.get_rect()\nself.image_orig = self.image\nself.speed = 2\nself.direction = angle\nself.steering = 90\nself.x = x\nself.y = y",
"self.direction = self.direction + self.steering\nif self.direction > 360... | <|body_start_0|>
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('Image/Trafico.png')
self.rect = self.image.get_rect()
self.image_orig = self.image
self.speed = 2
self.direction = angle
self.steering = 90
self.x = x
self.y = y
<... | Esta es la clase para los drones | Dummy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dummy:
"""Esta es la clase para los drones"""
def __init__(self, angle, x, y):
"""Aqui se definen varios atributos como la velocidad, el angulo, la imagen y la magnitud de los giros"""
<|body_0|>
def steerleft(self):
"""Giros hacia la izquierda"""
<|body_... | stack_v2_sparse_classes_36k_train_003008 | 2,190 | no_license | [
{
"docstring": "Aqui se definen varios atributos como la velocidad, el angulo, la imagen y la magnitud de los giros",
"name": "__init__",
"signature": "def __init__(self, angle, x, y)"
},
{
"docstring": "Giros hacia la izquierda",
"name": "steerleft",
"signature": "def steerleft(self)"
... | 4 | stack_v2_sparse_classes_30k_train_002373 | Implement the Python class `Dummy` described below.
Class description:
Esta es la clase para los drones
Method signatures and docstrings:
- def __init__(self, angle, x, y): Aqui se definen varios atributos como la velocidad, el angulo, la imagen y la magnitud de los giros
- def steerleft(self): Giros hacia la izquier... | Implement the Python class `Dummy` described below.
Class description:
Esta es la clase para los drones
Method signatures and docstrings:
- def __init__(self, angle, x, y): Aqui se definen varios atributos como la velocidad, el angulo, la imagen y la magnitud de los giros
- def steerleft(self): Giros hacia la izquier... | b5c61e38224746fe4e9af65a7ef432aa4f431f29 | <|skeleton|>
class Dummy:
"""Esta es la clase para los drones"""
def __init__(self, angle, x, y):
"""Aqui se definen varios atributos como la velocidad, el angulo, la imagen y la magnitud de los giros"""
<|body_0|>
def steerleft(self):
"""Giros hacia la izquierda"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dummy:
"""Esta es la clase para los drones"""
def __init__(self, angle, x, y):
"""Aqui se definen varios atributos como la velocidad, el angulo, la imagen y la magnitud de los giros"""
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('Image/Trafico.png')
... | the_stack_v2_python_sparse | Intro y Taller Progra- TEC/Proyectos/achacon-proyecto2/trafico.py | AdrChacon/ChaCa-Progra | train | 2 |
8134be26b083bea97f14a1f9d00d6aa12556a004 | [
"super().__init__(n_head, n_feat, dropout_rate)\nself.linear_pos = nn.Linear(n_feat, n_feat, bias=False)\nself.pos_bias_u = nn.Parameter(torch.Tensor(self.h, self.d_k))\nself.pos_bias_v = nn.Parameter(torch.Tensor(self.h, self.d_k))\ntorch.nn.init.xavier_uniform_(self.pos_bias_u)\ntorch.nn.init.xavier_uniform_(self... | <|body_start_0|>
super().__init__(n_head, n_feat, dropout_rate)
self.linear_pos = nn.Linear(n_feat, n_feat, bias=False)
self.pos_bias_u = nn.Parameter(torch.Tensor(self.h, self.d_k))
self.pos_bias_v = nn.Parameter(torch.Tensor(self.h, self.d_k))
torch.nn.init.xavier_uniform_(self... | Multi-Head Attention layer with relative position encoding. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): The number of heads. n_feat (int): The number of features. dropout_rate (float): Dropout rate. | RelPositionMultiHeadedAttention | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelPositionMultiHeadedAttention:
"""Multi-Head Attention layer with relative position encoding. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): The number of heads. n_feat (int): The number of features. dropout_rate (float): Dropout rate."""
def __init__(self, n_head, n_feat, dro... | stack_v2_sparse_classes_36k_train_003009 | 37,737 | permissive | [
{
"docstring": "Construct an RelPositionMultiHeadedAttention object.",
"name": "__init__",
"signature": "def __init__(self, n_head, n_feat, dropout_rate)"
},
{
"docstring": "Compute relative positinal encoding. Args: x (torch.Tensor): Input tensor (batch, time, size). zero_triu (bool): If true, ... | 3 | null | Implement the Python class `RelPositionMultiHeadedAttention` described below.
Class description:
Multi-Head Attention layer with relative position encoding. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): The number of heads. n_feat (int): The number of features. dropout_rate (float): Dropout rate.
Method... | Implement the Python class `RelPositionMultiHeadedAttention` described below.
Class description:
Multi-Head Attention layer with relative position encoding. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): The number of heads. n_feat (int): The number of features. dropout_rate (float): Dropout rate.
Method... | 31d50b1ea1dea92f4182c5b2b6fe9fe4c981ae39 | <|skeleton|>
class RelPositionMultiHeadedAttention:
"""Multi-Head Attention layer with relative position encoding. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): The number of heads. n_feat (int): The number of features. dropout_rate (float): Dropout rate."""
def __init__(self, n_head, n_feat, dro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RelPositionMultiHeadedAttention:
"""Multi-Head Attention layer with relative position encoding. Paper: https://arxiv.org/abs/1901.02860 Args: n_head (int): The number of heads. n_feat (int): The number of features. dropout_rate (float): Dropout rate."""
def __init__(self, n_head, n_feat, dropout_rate):
... | the_stack_v2_python_sparse | SVS/model/layers/conformer_related.py | SJTMusicTeam/SVS_system | train | 85 |
95cd12e8e35bc21dae0b08d8dcac3c00c5e00970 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn WindowsAppXAppAssignmentSettings()",
"from .mobile_app_assignment_settings import MobileAppAssignmentSettings\nfrom .mobile_app_assignment_settings import MobileAppAssignmentSettings\nfields: Dict[str, Callable[[Any], None]] = {'useDev... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return WindowsAppXAppAssignmentSettings()
<|end_body_0|>
<|body_start_1|>
from .mobile_app_assignment_settings import MobileAppAssignmentSettings
from .mobile_app_assignment_settings import Mob... | Contains properties used when assigning a Windows AppX mobile app to a group. | WindowsAppXAppAssignmentSettings | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WindowsAppXAppAssignmentSettings:
"""Contains properties used when assigning a Windows AppX mobile app to a group."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsAppXAppAssignmentSettings:
"""Creates a new instance of the appropriate class base... | stack_v2_sparse_classes_36k_train_003010 | 2,660 | 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: WindowsAppXAppAssignmentSettings",
"name": "create_from_discriminator_value",
"signature": "def create_from_... | 3 | stack_v2_sparse_classes_30k_train_018513 | Implement the Python class `WindowsAppXAppAssignmentSettings` described below.
Class description:
Contains properties used when assigning a Windows AppX mobile app to a group.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsAppXAppAssignmentSetti... | Implement the Python class `WindowsAppXAppAssignmentSettings` described below.
Class description:
Contains properties used when assigning a Windows AppX mobile app to a group.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsAppXAppAssignmentSetti... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class WindowsAppXAppAssignmentSettings:
"""Contains properties used when assigning a Windows AppX mobile app to a group."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsAppXAppAssignmentSettings:
"""Creates a new instance of the appropriate class base... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WindowsAppXAppAssignmentSettings:
"""Contains properties used when assigning a Windows AppX mobile app to a group."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WindowsAppXAppAssignmentSettings:
"""Creates a new instance of the appropriate class based on discrimi... | the_stack_v2_python_sparse | msgraph/generated/models/windows_app_x_app_assignment_settings.py | microsoftgraph/msgraph-sdk-python | train | 135 |
62bac999e14c362d9c79eb25ec950da3a56ce329 | [
"if not head or not head.next:\n return head\np1 = head\np2 = head.next\np1.next = None\nwhile p2:\n p2Next = p2.next\n p2.next = p1\n p1 = p2\n if p2Next:\n p2 = p2Next\n else:\n return p2",
"length = 0\nptr = head\nwhile ptr:\n length += 1\n ptr = ptr.next\nprint(length)\nh... | <|body_start_0|>
if not head or not head.next:
return head
p1 = head
p2 = head.next
p1.next = None
while p2:
p2Next = p2.next
p2.next = p1
p1 = p2
if p2Next:
p2 = p2Next
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def reorderList(self, head):
""":type head: ListNode :rtype: void Do not return anything, modify head in-place instead."""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_003011 | 1,532 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "reverseList",
"signature": "def reverseList(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: void Do not return anything, modify head in-place instead.",
"name": "reorderList",
"signature": "def reorderList(self... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def reorderList(self, head): :type head: ListNode :rtype: void Do not return anything, modify head in-place i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def reorderList(self, head): :type head: ListNode :rtype: void Do not return anything, modify head in-place i... | 5fed58c0cbbaf7dfa6b27282e4914b691f9e0759 | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def reorderList(self, head):
""":type head: ListNode :rtype: void Do not return anything, modify head in-place instead."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
if not head or not head.next:
return head
p1 = head
p2 = head.next
p1.next = None
while p2:
p2Next = p2.next
p2.next = p1
p1 = p2
... | the_stack_v2_python_sparse | LinkedList/reorderList.py | misa5555/py | train | 0 | |
d8d44c12638d214677f4998f425c56de896ebd21 | [
"if not nums:\n return []\nret = [[nums[0]]]\nfor i in range(1, len(nums)):\n new_ret = []\n for j in range(0, len(ret)):\n for k in range(0, len(ret[j]) + 1):\n new_ret.append(ret[j][:k] + [nums[i]] + ret[j][k:])\n ret = new_ret\nreturn ret",
"if not nums:\n return []\nret = [[nu... | <|body_start_0|>
if not nums:
return []
ret = [[nums[0]]]
for i in range(1, len(nums)):
new_ret = []
for j in range(0, len(ret)):
for k in range(0, len(ret[j]) + 1):
new_ret.append(ret[j][:k] + [nums[i]] + ret[j][k:])
... | Permutations | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Permutations:
def permute_distinct(nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def permute_dup(nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
... | stack_v2_sparse_classes_36k_train_003012 | 1,707 | permissive | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "permute_distinct",
"signature": "def permute_distinct(nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "permute_dup",
"signature": "def permute_dup(nums)"
}
] | 2 | null | Implement the Python class `Permutations` described below.
Class description:
Implement the Permutations class.
Method signatures and docstrings:
- def permute_distinct(nums): :type nums: List[int] :rtype: List[List[int]]
- def permute_dup(nums): :type nums: List[int] :rtype: List[List[int]] | Implement the Python class `Permutations` described below.
Class description:
Implement the Permutations class.
Method signatures and docstrings:
- def permute_distinct(nums): :type nums: List[int] :rtype: List[List[int]]
- def permute_dup(nums): :type nums: List[int] :rtype: List[List[int]]
<|skeleton|>
class Permu... | 77838c37e3fdae0f2ec628aa7ddc59f4a5949bbe | <|skeleton|>
class Permutations:
def permute_distinct(nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def permute_dup(nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Permutations:
def permute_distinct(nums):
""":type nums: List[int] :rtype: List[List[int]]"""
if not nums:
return []
ret = [[nums[0]]]
for i in range(1, len(nums)):
new_ret = []
for j in range(0, len(ret)):
for k in range(0, l... | the_stack_v2_python_sparse | Python/dev/arrays/permutations.py | faisaldialpad/hellouniverse | train | 0 | |
48bbd1bb640dcf045b7e89fd130dbf07ec173e7d | [
"self.cluster_gateway = cluster_gateway\nself.cluster_subnet_mask = cluster_subnet_mask\nself.dns_servers = dns_servers\nself.domain_names = domain_names\nself.ntp_servers = ntp_servers\nself.vip_hostname = vip_hostname\nself.vips = vips",
"if dictionary is None:\n return None\ncluster_gateway = dictionary.get... | <|body_start_0|>
self.cluster_gateway = cluster_gateway
self.cluster_subnet_mask = cluster_subnet_mask
self.dns_servers = dns_servers
self.domain_names = domain_names
self.ntp_servers = ntp_servers
self.vip_hostname = vip_hostname
self.vips = vips
<|end_body_0|>
... | Implementation of the 'NetworkConfiguration' model. Specifies all of the parameters needed for network configuration of the new Cluster. Attributes: cluster_gateway (string): Specifies the default gateway IP address (or addresses) for the Cluster network. cluster_subnet_mask (string): Specifies the subnet mask (or mask... | NetworkConfiguration | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetworkConfiguration:
"""Implementation of the 'NetworkConfiguration' model. Specifies all of the parameters needed for network configuration of the new Cluster. Attributes: cluster_gateway (string): Specifies the default gateway IP address (or addresses) for the Cluster network. cluster_subnet_m... | stack_v2_sparse_classes_36k_train_003013 | 3,285 | permissive | [
{
"docstring": "Constructor for the NetworkConfiguration class",
"name": "__init__",
"signature": "def __init__(self, cluster_gateway=None, cluster_subnet_mask=None, dns_servers=None, domain_names=None, ntp_servers=None, vip_hostname=None, vips=None)"
},
{
"docstring": "Creates an instance of th... | 2 | stack_v2_sparse_classes_30k_train_001760 | Implement the Python class `NetworkConfiguration` described below.
Class description:
Implementation of the 'NetworkConfiguration' model. Specifies all of the parameters needed for network configuration of the new Cluster. Attributes: cluster_gateway (string): Specifies the default gateway IP address (or addresses) fo... | Implement the Python class `NetworkConfiguration` described below.
Class description:
Implementation of the 'NetworkConfiguration' model. Specifies all of the parameters needed for network configuration of the new Cluster. Attributes: cluster_gateway (string): Specifies the default gateway IP address (or addresses) fo... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class NetworkConfiguration:
"""Implementation of the 'NetworkConfiguration' model. Specifies all of the parameters needed for network configuration of the new Cluster. Attributes: cluster_gateway (string): Specifies the default gateway IP address (or addresses) for the Cluster network. cluster_subnet_m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NetworkConfiguration:
"""Implementation of the 'NetworkConfiguration' model. Specifies all of the parameters needed for network configuration of the new Cluster. Attributes: cluster_gateway (string): Specifies the default gateway IP address (or addresses) for the Cluster network. cluster_subnet_mask (string):... | the_stack_v2_python_sparse | cohesity_management_sdk/models/network_configuration.py | cohesity/management-sdk-python | train | 24 |
f5b14ee8fec15bf9687e2b6cc6ffc23802f51ab5 | [
"col = mostcommonerror(beadqualitysummary(trackqc))\nframe = col.replace(list(set(col.unique()) - {'fixed', 'missing', np.NaN}), 'error').reset_index().fillna('ok')\nframe.sort_values('modification', inplace=True)\nif tracks is all or tracks is Ellipsis:\n return frame\nif tracks is None:\n tracks = (trackqc.... | <|body_start_0|>
col = mostcommonerror(beadqualitysummary(trackqc))
frame = col.replace(list(set(col.unique()) - {'fixed', 'missing', np.NaN}), 'error').reset_index().fillna('ok')
frame.sort_values('modification', inplace=True)
if tracks is all or tracks is Ellipsis:
return f... | outputs a flow diagram between two tracks showing the proportion of the beads classified by their status (their mostCommonError) | StatusFlow | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StatusFlow:
"""outputs a flow diagram between two tracks showing the proportion of the beads classified by their status (their mostCommonError)"""
def dataframe(trackqc: TrackQC, tracks=None) -> pd.DataFrame:
"""computes the dataframe used for finding edges and nodes"""
<|bod... | stack_v2_sparse_classes_36k_train_003014 | 3,473 | no_license | [
{
"docstring": "computes the dataframe used for finding edges and nodes",
"name": "dataframe",
"signature": "def dataframe(trackqc: TrackQC, tracks=None) -> pd.DataFrame"
},
{
"docstring": "computes nodes",
"name": "nodes",
"signature": "def nodes(frame: pd.DataFrame) -> pd.DataFrame"
... | 4 | stack_v2_sparse_classes_30k_train_017652 | Implement the Python class `StatusFlow` described below.
Class description:
outputs a flow diagram between two tracks showing the proportion of the beads classified by their status (their mostCommonError)
Method signatures and docstrings:
- def dataframe(trackqc: TrackQC, tracks=None) -> pd.DataFrame: computes the da... | Implement the Python class `StatusFlow` described below.
Class description:
outputs a flow diagram between two tracks showing the proportion of the beads classified by their status (their mostCommonError)
Method signatures and docstrings:
- def dataframe(trackqc: TrackQC, tracks=None) -> pd.DataFrame: computes the da... | f9534e4fff9775ff45d08d401de61015d4a69e76 | <|skeleton|>
class StatusFlow:
"""outputs a flow diagram between two tracks showing the proportion of the beads classified by their status (their mostCommonError)"""
def dataframe(trackqc: TrackQC, tracks=None) -> pd.DataFrame:
"""computes the dataframe used for finding edges and nodes"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StatusFlow:
"""outputs a flow diagram between two tracks showing the proportion of the beads classified by their status (their mostCommonError)"""
def dataframe(trackqc: TrackQC, tracks=None) -> pd.DataFrame:
"""computes the dataframe used for finding edges and nodes"""
col = mostcommoner... | the_stack_v2_python_sparse | src/scripting/beadquality/_statusflow.py | depixusgenome/trackanalysis | train | 0 |
1bcc744dc03056f586cf3454139a69a1f6127246 | [
"nodes = list()\nstack = list()\nstack.append(root)\nnodes.append(root)\nwhile stack:\n root = stack.pop(0)\n left, right = (root.left, root.right)\n nodes.append(left)\n nodes.append(right)\n if left:\n stack.append(left)\n if right:\n stack.append(right)\nwhile nodes and nodes[-1] ... | <|body_start_0|>
nodes = list()
stack = list()
stack.append(root)
nodes.append(root)
while stack:
root = stack.pop(0)
left, right = (root.left, root.right)
nodes.append(left)
nodes.append(right)
if left:
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_003015 | 4,016 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 6b24724da055a08510c83c645455eaa4ed201298 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
nodes = list()
stack = list()
stack.append(root)
nodes.append(root)
while stack:
root = stack.pop(0)
left, right = (root.left, roo... | the_stack_v2_python_sparse | Tree/python/leetcode/serialize_and_deserialize_binary_tree.py | sankeerth/Algorithms | train | 0 | |
47bce94e33187688a662bbcf97a6622c8523fc25 | [
"if not nums:\n return 0\ni = 0\nwhile i < len(nums):\n if val == nums[i]:\n nums.remove(val)\n i -= 1\n i += 1\nreturn len(nums)",
"cur = 0\nfor i in range(len(nums)):\n if nums[i] != val:\n nums[cur] = nums[i]\n cur += 1\nreturn cur"
] | <|body_start_0|>
if not nums:
return 0
i = 0
while i < len(nums):
if val == nums[i]:
nums.remove(val)
i -= 1
i += 1
return len(nums)
<|end_body_0|>
<|body_start_1|>
cur = 0
for i in range(len(nums)):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeElement(self, nums, val):
""":type nums: List[int] :type val: int :rtype: int"""
<|body_0|>
def removeElement2(self, nums, val):
""":type nums: List[int] :type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_003016 | 879 | no_license | [
{
"docstring": ":type nums: List[int] :type val: int :rtype: int",
"name": "removeElement",
"signature": "def removeElement(self, nums, val)"
},
{
"docstring": ":type nums: List[int] :type val: int :rtype: int",
"name": "removeElement2",
"signature": "def removeElement2(self, nums, val)"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElement(self, nums, val): :type nums: List[int] :type val: int :rtype: int
- def removeElement2(self, nums, val): :type nums: List[int] :type val: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElement(self, nums, val): :type nums: List[int] :type val: int :rtype: int
- def removeElement2(self, nums, val): :type nums: List[int] :type val: int :rtype: int
<|sk... | bd8df12c0d4afd048cf1b58b04c27fa1f3622769 | <|skeleton|>
class Solution:
def removeElement(self, nums, val):
""":type nums: List[int] :type val: int :rtype: int"""
<|body_0|>
def removeElement2(self, nums, val):
""":type nums: List[int] :type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def removeElement(self, nums, val):
""":type nums: List[int] :type val: int :rtype: int"""
if not nums:
return 0
i = 0
while i < len(nums):
if val == nums[i]:
nums.remove(val)
i -= 1
i += 1
re... | the_stack_v2_python_sparse | 27_remove_element.py | aojugg/leetcode | train | 0 | |
5a54309eb8de998ada09fea87dc822bd1846975e | [
"self.f = f\nself.gp = GP(X_init, Y_init, l, sigma_f)\nb_min, b_max = bounds\nself.X_s = np.linspace(b_min, b_max, ac_samples).reshape(-1, 1)\nself.xsi = xsi\nself.minimize = minimize",
"mu, sigma = self.gp.predict(self.X_s)\nmu = mu.reshape(-1, 1)\nsigma = sigma.reshape(-1, 1)\nif self.minimize:\n min_val = n... | <|body_start_0|>
self.f = f
self.gp = GP(X_init, Y_init, l, sigma_f)
b_min, b_max = bounds
self.X_s = np.linspace(b_min, b_max, ac_samples).reshape(-1, 1)
self.xsi = xsi
self.minimize = minimize
<|end_body_0|>
<|body_start_1|>
mu, sigma = self.gp.predict(self.X_s... | [summary] | BayesianOptimization | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BayesianOptimization:
"""[summary]"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""[summary] Args: f ([type]): [description] X_init ([type]): [description] Y_init ([type]): [description] bounds ([type]): [description] ac_sampl... | stack_v2_sparse_classes_36k_train_003017 | 1,783 | no_license | [
{
"docstring": "[summary] Args: f ([type]): [description] X_init ([type]): [description] Y_init ([type]): [description] bounds ([type]): [description] ac_samples ([type]): [description] l (int, optional): [description]. Defaults to 1. sigma_f (int, optional): [description]. Defaults to 1. xsi (float, optional):... | 2 | stack_v2_sparse_classes_30k_train_002731 | Implement the Python class `BayesianOptimization` described below.
Class description:
[summary]
Method signatures and docstrings:
- def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): [summary] Args: f ([type]): [description] X_init ([type]): [description] Y_init ([type... | Implement the Python class `BayesianOptimization` described below.
Class description:
[summary]
Method signatures and docstrings:
- def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): [summary] Args: f ([type]): [description] X_init ([type]): [description] Y_init ([type... | 5f86dee95f4d1c32014d0d74a368f342ff3ce6f7 | <|skeleton|>
class BayesianOptimization:
"""[summary]"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""[summary] Args: f ([type]): [description] X_init ([type]): [description] Y_init ([type]): [description] bounds ([type]): [description] ac_sampl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BayesianOptimization:
"""[summary]"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""[summary] Args: f ([type]): [description] X_init ([type]): [description] Y_init ([type]): [description] bounds ([type]): [description] ac_samples ([type]): ... | the_stack_v2_python_sparse | unsupervised_learning/0x03-hyperparameter_tuning/4-bayes_opt.py | d1sd41n/holbertonschool-machine_learning | train | 0 |
0f375f0f5bc5ff81b28b2302bee2d5b5a5954aac | [
"def preOrder(node):\n if not node:\n return ['None']\n return [str(node.val)] + preOrder(node.left) + preOrder(node.right)\nreturn ' '.join(preOrder(root))",
"def preOrder(it):\n v = next(it)\n if v == 'None':\n return None\n node = TreeNode(int(v))\n node.left = preOrder(it)\n ... | <|body_start_0|>
def preOrder(node):
if not node:
return ['None']
return [str(node.val)] + preOrder(node.left) + preOrder(node.right)
return ' '.join(preOrder(root))
<|end_body_0|>
<|body_start_1|>
def preOrder(it):
v = next(it)
if... | Codec3 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec3:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_003018 | 4,842 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_016764 | Implement the Python class `Codec3` described below.
Class description:
Implement the Codec3 class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtyp... | Implement the Python class `Codec3` described below.
Class description:
Implement the Codec3 class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtyp... | 63120dbaabd7c3c19633ebe952bcee4cf826b0e0 | <|skeleton|>
class Codec3:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec3:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def preOrder(node):
if not node:
return ['None']
return [str(node.val)] + preOrder(node.left) + preOrder(node.right)
return ' '.join(preO... | the_stack_v2_python_sparse | 297. Serialize and Deserialize Binary Tree _ tee.py | CaizhiXu/LeetCode-Python-Solutions | train | 0 | |
ba9682fd1f235b6d3dda9c475fc1eafee8886a9e | [
"dummy = ListNode(-1)\ndummy.next = head\nprev_node = dummy\nwhile head and head.next:\n first_node = head\n second_node = head.next\n prev_node.next = second_node\n first_node.next = second_node.next\n second_node.next = first_node\n prev_node = first_node\n head = first_node.next\nreturn dumm... | <|body_start_0|>
dummy = ListNode(-1)
dummy.next = head
prev_node = dummy
while head and head.next:
first_node = head
second_node = head.next
prev_node.next = second_node
first_node.next = second_node.next
second_node.next = fir... | LinkedList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkedList:
def swap_nodes(self, head: 'ListNode') -> 'ListNode':
"""Approach: Iterative Time Complexity: O(N) Space Complexity: O(1) :param head: :return:"""
<|body_0|>
def swap_nodes_(self, head: 'ListNode') -> 'ListNode':
"""Approach: Recursion Time Complexity: O(... | stack_v2_sparse_classes_36k_train_003019 | 1,339 | no_license | [
{
"docstring": "Approach: Iterative Time Complexity: O(N) Space Complexity: O(1) :param head: :return:",
"name": "swap_nodes",
"signature": "def swap_nodes(self, head: 'ListNode') -> 'ListNode'"
},
{
"docstring": "Approach: Recursion Time Complexity: O(N) Space Complexity: O(N) :param head: :ret... | 2 | null | Implement the Python class `LinkedList` described below.
Class description:
Implement the LinkedList class.
Method signatures and docstrings:
- def swap_nodes(self, head: 'ListNode') -> 'ListNode': Approach: Iterative Time Complexity: O(N) Space Complexity: O(1) :param head: :return:
- def swap_nodes_(self, head: 'Li... | Implement the Python class `LinkedList` described below.
Class description:
Implement the LinkedList class.
Method signatures and docstrings:
- def swap_nodes(self, head: 'ListNode') -> 'ListNode': Approach: Iterative Time Complexity: O(N) Space Complexity: O(1) :param head: :return:
- def swap_nodes_(self, head: 'Li... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class LinkedList:
def swap_nodes(self, head: 'ListNode') -> 'ListNode':
"""Approach: Iterative Time Complexity: O(N) Space Complexity: O(1) :param head: :return:"""
<|body_0|>
def swap_nodes_(self, head: 'ListNode') -> 'ListNode':
"""Approach: Recursion Time Complexity: O(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinkedList:
def swap_nodes(self, head: 'ListNode') -> 'ListNode':
"""Approach: Iterative Time Complexity: O(N) Space Complexity: O(1) :param head: :return:"""
dummy = ListNode(-1)
dummy.next = head
prev_node = dummy
while head and head.next:
first_node = hea... | the_stack_v2_python_sparse | revisited_2021/linked_list/swap_nodes.py | Shiv2157k/leet_code | train | 1 | |
1d7c46ce8d64b35ea3bb0f442f08dcd3f6fed32d | [
"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 HTTP routers. | HttpRouterServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HttpRouterServiceServicer:
"""A set of methods for managing HTTP routers."""
def Get(self, request, context):
"""Returns the specified HTTP router. To get the list of all available HTTP routers, make a [List] request."""
<|body_0|>
def List(self, request, context):
... | stack_v2_sparse_classes_36k_train_003020 | 12,714 | permissive | [
{
"docstring": "Returns the specified HTTP router. To get the list of all available HTTP routers, make a [List] request.",
"name": "Get",
"signature": "def Get(self, request, context)"
},
{
"docstring": "Lists HTTP routers in the specified folder.",
"name": "List",
"signature": "def List... | 6 | stack_v2_sparse_classes_30k_train_010194 | Implement the Python class `HttpRouterServiceServicer` described below.
Class description:
A set of methods for managing HTTP routers.
Method signatures and docstrings:
- def Get(self, request, context): Returns the specified HTTP router. To get the list of all available HTTP routers, make a [List] request.
- def Lis... | Implement the Python class `HttpRouterServiceServicer` described below.
Class description:
A set of methods for managing HTTP routers.
Method signatures and docstrings:
- def Get(self, request, context): Returns the specified HTTP router. To get the list of all available HTTP routers, make a [List] request.
- def Lis... | b906a014dd893e2697864e1e48e814a8d9fbc48c | <|skeleton|>
class HttpRouterServiceServicer:
"""A set of methods for managing HTTP routers."""
def Get(self, request, context):
"""Returns the specified HTTP router. To get the list of all available HTTP routers, make a [List] request."""
<|body_0|>
def List(self, request, context):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HttpRouterServiceServicer:
"""A set of methods for managing HTTP routers."""
def Get(self, request, context):
"""Returns the specified HTTP router. To get the list of all available HTTP routers, make a [List] request."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_... | the_stack_v2_python_sparse | yandex/cloud/apploadbalancer/v1/http_router_service_pb2_grpc.py | yandex-cloud/python-sdk | train | 63 |
fce2acde174d06ee3dd4886fd72a3d7152b13e55 | [
"max_area = 0\nn = len(height)\nh_prev = 0\nfor i in range(0, n - 1):\n hi = height[i]\n if hi <= h_prev:\n continue\n for j in range(i + 1, n):\n hj = height[j]\n h = min(hi, hj)\n area = (j - i) * h\n if area > max_area:\n max_area = area\n h_prev ... | <|body_start_0|>
max_area = 0
n = len(height)
h_prev = 0
for i in range(0, n - 1):
hi = height[i]
if hi <= h_prev:
continue
for j in range(i + 1, n):
hj = height[j]
h = min(hi, hj)
area = ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxArea_v1(self, height: List[int]) -> int:
"""A simple solution."""
<|body_0|>
def maxArea_v2(self, height: List[int]) -> int:
"""Use two pointers. Move the one with shorter height."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
max_... | stack_v2_sparse_classes_36k_train_003021 | 2,035 | no_license | [
{
"docstring": "A simple solution.",
"name": "maxArea_v1",
"signature": "def maxArea_v1(self, height: List[int]) -> int"
},
{
"docstring": "Use two pointers. Move the one with shorter height.",
"name": "maxArea_v2",
"signature": "def maxArea_v2(self, height: List[int]) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_val_000775 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea_v1(self, height: List[int]) -> int: A simple solution.
- def maxArea_v2(self, height: List[int]) -> int: Use two pointers. Move the one with shorter height. | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea_v1(self, height: List[int]) -> int: A simple solution.
- def maxArea_v2(self, height: List[int]) -> int: Use two pointers. Move the one with shorter height.
<|skelet... | 97a2386f5e3adbd7138fd123810c3232bdf7f622 | <|skeleton|>
class Solution:
def maxArea_v1(self, height: List[int]) -> int:
"""A simple solution."""
<|body_0|>
def maxArea_v2(self, height: List[int]) -> int:
"""Use two pointers. Move the one with shorter height."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxArea_v1(self, height: List[int]) -> int:
"""A simple solution."""
max_area = 0
n = len(height)
h_prev = 0
for i in range(0, n - 1):
hi = height[i]
if hi <= h_prev:
continue
for j in range(i + 1, n):
... | the_stack_v2_python_sparse | python3/string_array/container_with_most_water.py | victorchu/algorithms | train | 0 | |
044ce8d45c67200746832597ea0fffa812af07bd | [
"if not has_h5py:\n raise ImportError('Cannot launch logger, install h5py')\nself.hash = ('%.5f' % (time.time() % 1))[2:]\nself.simulation = simulation\nself.params = None\nself.filename = None\nself.file = None\nself.results_folder = 'results'\nif not os.path.exists(self.results_folder):\n os.makedirs(self.r... | <|body_start_0|>
if not has_h5py:
raise ImportError('Cannot launch logger, install h5py')
self.hash = ('%.5f' % (time.time() % 1))[2:]
self.simulation = simulation
self.params = None
self.filename = None
self.file = None
self.results_folder = 'results'... | Class that stores all relevant data of the simulation on disk. Uses the HD5F format for structuring data. | PositionLogger | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PositionLogger:
"""Class that stores all relevant data of the simulation on disk. Uses the HD5F format for structuring data."""
def __init__(self, simulation):
"""Create a new logger for the simulation. Stores data on each time step. :param simulation: Simulation that will be logged"... | stack_v2_sparse_classes_36k_train_003022 | 4,460 | no_license | [
{
"docstring": "Create a new logger for the simulation. Stores data on each time step. :param simulation: Simulation that will be logged",
"name": "__init__",
"signature": "def __init__(self, simulation)"
},
{
"docstring": "Called before the simulation starts. Fix all parameters and bootstrap fu... | 4 | null | Implement the Python class `PositionLogger` described below.
Class description:
Class that stores all relevant data of the simulation on disk. Uses the HD5F format for structuring data.
Method signatures and docstrings:
- def __init__(self, simulation): Create a new logger for the simulation. Stores data on each time... | Implement the Python class `PositionLogger` described below.
Class description:
Class that stores all relevant data of the simulation on disk. Uses the HD5F format for structuring data.
Method signatures and docstrings:
- def __init__(self, simulation): Create a new logger for the simulation. Stores data on each time... | b1d1d1316c2b89dfd7497b89dc823725b6ada8d6 | <|skeleton|>
class PositionLogger:
"""Class that stores all relevant data of the simulation on disk. Uses the HD5F format for structuring data."""
def __init__(self, simulation):
"""Create a new logger for the simulation. Stores data on each time step. :param simulation: Simulation that will be logged"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PositionLogger:
"""Class that stores all relevant data of the simulation on disk. Uses the HD5F format for structuring data."""
def __init__(self, simulation):
"""Create a new logger for the simulation. Stores data on each time step. :param simulation: Simulation that will be logged"""
if... | the_stack_v2_python_sparse | src/processing/log_results.py | QiangChen-CG/mercurial | train | 0 |
3accda0b5b82073651a328298b202670814179ec | [
"self.robot = robot\nself.relative_phase = relative_phase\nself.v = v\nself.a = a\nself.R = R\nself.amp_offset = amp_offset\nself.phase_offset = phase_offset\nself.phase_biases = self.generate_biases(relative_phase)",
"phase_biases = np.zeros((self.robot.n_oscillators, self.robot.n_oscillators))\nfor i in range(s... | <|body_start_0|>
self.robot = robot
self.relative_phase = relative_phase
self.v = v
self.a = a
self.R = R
self.amp_offset = amp_offset
self.phase_offset = phase_offset
self.phase_biases = self.generate_biases(relative_phase)
<|end_body_0|>
<|body_start_1|... | Gait | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Gait:
def __init__(self, robot, relative_phase, v, a, R, amp_offset, phase_offset):
"""Class containing default components of a gait. Formulation similar to Crespi2008 :param robot: Robot object :param relative_phase: phase difference between base joints :param v: frequency of each CPG -... | stack_v2_sparse_classes_36k_train_003023 | 9,855 | no_license | [
{
"docstring": "Class containing default components of a gait. Formulation similar to Crespi2008 :param robot: Robot object :param relative_phase: phase difference between base joints :param v: frequency of each CPG - fixed and same right now :param R: amplitude of CPG - fixed and same right now :param a: posit... | 2 | stack_v2_sparse_classes_30k_train_010934 | Implement the Python class `Gait` described below.
Class description:
Implement the Gait class.
Method signatures and docstrings:
- def __init__(self, robot, relative_phase, v, a, R, amp_offset, phase_offset): Class containing default components of a gait. Formulation similar to Crespi2008 :param robot: Robot object ... | Implement the Python class `Gait` described below.
Class description:
Implement the Gait class.
Method signatures and docstrings:
- def __init__(self, robot, relative_phase, v, a, R, amp_offset, phase_offset): Class containing default components of a gait. Formulation similar to Crespi2008 :param robot: Robot object ... | 463c5555a1b3c28c0d73bd05521e9758eef15e0e | <|skeleton|>
class Gait:
def __init__(self, robot, relative_phase, v, a, R, amp_offset, phase_offset):
"""Class containing default components of a gait. Formulation similar to Crespi2008 :param robot: Robot object :param relative_phase: phase difference between base joints :param v: frequency of each CPG -... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Gait:
def __init__(self, robot, relative_phase, v, a, R, amp_offset, phase_offset):
"""Class containing default components of a gait. Formulation similar to Crespi2008 :param robot: Robot object :param relative_phase: phase difference between base joints :param v: frequency of each CPG - fixed and sam... | the_stack_v2_python_sparse | gym-daisy-custom/gym_daisy_custom/control/gaits.py | contactrika/bo-svae-dc | train | 6 | |
9657ad66cc2346c3209b516edf30743f24a4e513 | [
"today_str = pendulum.today('UTC').format('YYYY-MM-DD')\ninfo = self.inner_compute_last_repair_info(today_str)\nlast_repair_info = info['last_repair_info']\ninfo_cache = info['info_cache']\nfor record in self:\n if record.id in last_repair_info:\n record.last_mile_repair_date = last_repair_info[record.id]... | <|body_start_0|>
today_str = pendulum.today('UTC').format('YYYY-MM-DD')
info = self.inner_compute_last_repair_info(today_str)
last_repair_info = info['last_repair_info']
info_cache = info['info_cache']
for record in self:
if record.id in last_repair_info:
... | 车辆设备, 说明,由于初期设计原因,多了一堆的废弃字段 | TrainDev | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrainDev:
"""车辆设备, 说明,由于初期设计原因,多了一堆的废弃字段"""
def _compute_last_repair_info(self):
"""计算上次里程修信息 :return:"""
<|body_0|>
def inner_compute_last_repair_info(self, date_str):
"""计算最终的修程信息 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
today_... | stack_v2_sparse_classes_36k_train_003024 | 2,455 | no_license | [
{
"docstring": "计算上次里程修信息 :return:",
"name": "_compute_last_repair_info",
"signature": "def _compute_last_repair_info(self)"
},
{
"docstring": "计算最终的修程信息 :return:",
"name": "inner_compute_last_repair_info",
"signature": "def inner_compute_last_repair_info(self, date_str)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021008 | Implement the Python class `TrainDev` described below.
Class description:
车辆设备, 说明,由于初期设计原因,多了一堆的废弃字段
Method signatures and docstrings:
- def _compute_last_repair_info(self): 计算上次里程修信息 :return:
- def inner_compute_last_repair_info(self, date_str): 计算最终的修程信息 :return: | Implement the Python class `TrainDev` described below.
Class description:
车辆设备, 说明,由于初期设计原因,多了一堆的废弃字段
Method signatures and docstrings:
- def _compute_last_repair_info(self): 计算上次里程修信息 :return:
- def inner_compute_last_repair_info(self, date_str): 计算最终的修程信息 :return:
<|skeleton|>
class TrainDev:
"""车辆设备, 说明,由于初期设... | 13b428a5c4ade6278e3e5e996ef10d9fb0fea4b9 | <|skeleton|>
class TrainDev:
"""车辆设备, 说明,由于初期设计原因,多了一堆的废弃字段"""
def _compute_last_repair_info(self):
"""计算上次里程修信息 :return:"""
<|body_0|>
def inner_compute_last_repair_info(self, date_str):
"""计算最终的修程信息 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TrainDev:
"""车辆设备, 说明,由于初期设计原因,多了一堆的废弃字段"""
def _compute_last_repair_info(self):
"""计算上次里程修信息 :return:"""
today_str = pendulum.today('UTC').format('YYYY-MM-DD')
info = self.inner_compute_last_repair_info(today_str)
last_repair_info = info['last_repair_info']
info_c... | the_stack_v2_python_sparse | mdias_addons/metro_park_base_data_10/models/train_dev.py | rezaghanimi/main_mdias | train | 0 |
db5981bcb87979b8820c2aa6db9e410cf59f8cd3 | [
"rating_value = 7\nrating_meaning = 'Indecisive'\nfestival = create_festival('IDFA', '2022-07-17', '2022-07-27')\nfilm = Film(festival_id=festival.id, film_id=-1, seq_nr=-1, title='A Test Movie', duration=timedelta(minutes=666))\nfilm.save()\nfan = me()\nrating = FilmFanFilmRating(film=film, film_fan=fan, rating=ra... | <|body_start_0|>
rating_value = 7
rating_meaning = 'Indecisive'
festival = create_festival('IDFA', '2022-07-17', '2022-07-27')
film = Film(festival_id=festival.id, film_id=-1, seq_nr=-1, title='A Test Movie', duration=timedelta(minutes=666))
film.save()
fan = me()
... | RatingModelTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RatingModelTests:
def test_rating_has_correct_meaning(self):
"""Rating 7 has meaning INDECISIVE."""
<|body_0|>
def test_ratings_can_have_same_film_id_but_not_same_festival_id(self):
"""Two ratings can only have films with identical film_id if festivals are different.... | stack_v2_sparse_classes_36k_train_003025 | 17,658 | no_license | [
{
"docstring": "Rating 7 has meaning INDECISIVE.",
"name": "test_rating_has_correct_meaning",
"signature": "def test_rating_has_correct_meaning(self)"
},
{
"docstring": "Two ratings can only have films with identical film_id if festivals are different.",
"name": "test_ratings_can_have_same_f... | 2 | stack_v2_sparse_classes_30k_train_001865 | Implement the Python class `RatingModelTests` described below.
Class description:
Implement the RatingModelTests class.
Method signatures and docstrings:
- def test_rating_has_correct_meaning(self): Rating 7 has meaning INDECISIVE.
- def test_ratings_can_have_same_film_id_but_not_same_festival_id(self): Two ratings c... | Implement the Python class `RatingModelTests` described below.
Class description:
Implement the RatingModelTests class.
Method signatures and docstrings:
- def test_rating_has_correct_meaning(self): Rating 7 has meaning INDECISIVE.
- def test_ratings_can_have_same_film_id_but_not_same_festival_id(self): Two ratings c... | 4ebc9b43a07bbc627b5e21cae368ae31828d3d2e | <|skeleton|>
class RatingModelTests:
def test_rating_has_correct_meaning(self):
"""Rating 7 has meaning INDECISIVE."""
<|body_0|>
def test_ratings_can_have_same_film_id_but_not_same_festival_id(self):
"""Two ratings can only have films with identical film_id if festivals are different.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RatingModelTests:
def test_rating_has_correct_meaning(self):
"""Rating 7 has meaning INDECISIVE."""
rating_value = 7
rating_meaning = 'Indecisive'
festival = create_festival('IDFA', '2022-07-17', '2022-07-27')
film = Film(festival_id=festival.id, film_id=-1, seq_nr=-1, ... | the_stack_v2_python_sparse | FilmRatings/film_list/tests.py | maar35/film-festival-planner | train | 0 | |
6b602057d47abe1ec7d08376f97f1f711961d937 | [
"decoded_group_id = trans.security.decode_id(group_id)\ntry:\n group = trans.sa_session.query(trans.app.model.Group).get(decoded_group_id)\nexcept Exception:\n group = None\nif not group:\n trans.response.status = 400\n return 'Invalid group id ( %s ) specified.' % str(group_id)\nrval = []\ntry:\n fo... | <|body_start_0|>
decoded_group_id = trans.security.decode_id(group_id)
try:
group = trans.sa_session.query(trans.app.model.Group).get(decoded_group_id)
except Exception:
group = None
if not group:
trans.response.status = 400
return 'Invalid... | GroupUsersAPIController | [
"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 GroupUsersAPIController:
def index(self, trans, group_id, **kwd):
"""GET /api/groups/{encoded_group_id}/users Displays a collection (list) of groups."""
<|body_0|>
def show(self, trans, id, group_id, **kwd):
"""GET /api/groups/{encoded_group_id}/users/{encoded_user_i... | stack_v2_sparse_classes_36k_train_003026 | 5,190 | permissive | [
{
"docstring": "GET /api/groups/{encoded_group_id}/users Displays a collection (list) of groups.",
"name": "index",
"signature": "def index(self, trans, group_id, **kwd)"
},
{
"docstring": "GET /api/groups/{encoded_group_id}/users/{encoded_user_id} Displays information about a group user.",
... | 4 | null | Implement the Python class `GroupUsersAPIController` described below.
Class description:
Implement the GroupUsersAPIController class.
Method signatures and docstrings:
- def index(self, trans, group_id, **kwd): GET /api/groups/{encoded_group_id}/users Displays a collection (list) of groups.
- def show(self, trans, id... | Implement the Python class `GroupUsersAPIController` described below.
Class description:
Implement the GroupUsersAPIController class.
Method signatures and docstrings:
- def index(self, trans, group_id, **kwd): GET /api/groups/{encoded_group_id}/users Displays a collection (list) of groups.
- def show(self, trans, id... | d194520fdfe08e48c0b3d0d2299cd2adcb8f5952 | <|skeleton|>
class GroupUsersAPIController:
def index(self, trans, group_id, **kwd):
"""GET /api/groups/{encoded_group_id}/users Displays a collection (list) of groups."""
<|body_0|>
def show(self, trans, id, group_id, **kwd):
"""GET /api/groups/{encoded_group_id}/users/{encoded_user_i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupUsersAPIController:
def index(self, trans, group_id, **kwd):
"""GET /api/groups/{encoded_group_id}/users Displays a collection (list) of groups."""
decoded_group_id = trans.security.decode_id(group_id)
try:
group = trans.sa_session.query(trans.app.model.Group).get(deco... | the_stack_v2_python_sparse | lib/galaxy/webapps/galaxy/api/group_users.py | bwlang/galaxy | train | 0 | |
143f3d145b520c94c6caf7075ced005ba410afd5 | [
"if not self._check_project():\n return None\nasset = artellapipe.AssetsMgr().find_asset(asset_name)\nif not asset:\n LOGGER.warning('Impossible to return occurrences because asset \"{}\" does not exists!'.format(asset_name))\n return None\nshot = shots.ShotsManager().find_shot(shot_name)\nif not shot:\n ... | <|body_start_0|>
if not self._check_project():
return None
asset = artellapipe.AssetsMgr().find_asset(asset_name)
if not asset:
LOGGER.warning('Impossible to return occurrences because asset "{}" does not exists!'.format(asset_name))
return None
shot =... | ArtellaCastingManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArtellaCastingManager:
def get_ocurrences_of_asset_in_shot(self, asset_name, shot_name, force_update=False):
"""Returns the number of ocurrences of given asset in given shot :param asset_name: str, name of the asset :param shot_name: str, name of the shot :return: int or None"""
... | stack_v2_sparse_classes_36k_train_003027 | 2,441 | permissive | [
{
"docstring": "Returns the number of ocurrences of given asset in given shot :param asset_name: str, name of the asset :param shot_name: str, name of the shot :return: int or None",
"name": "get_ocurrences_of_asset_in_shot",
"signature": "def get_ocurrences_of_asset_in_shot(self, asset_name, shot_name,... | 3 | stack_v2_sparse_classes_30k_train_008632 | Implement the Python class `ArtellaCastingManager` described below.
Class description:
Implement the ArtellaCastingManager class.
Method signatures and docstrings:
- def get_ocurrences_of_asset_in_shot(self, asset_name, shot_name, force_update=False): Returns the number of ocurrences of given asset in given shot :par... | Implement the Python class `ArtellaCastingManager` described below.
Class description:
Implement the ArtellaCastingManager class.
Method signatures and docstrings:
- def get_ocurrences_of_asset_in_shot(self, asset_name, shot_name, force_update=False): Returns the number of ocurrences of given asset in given shot :par... | 3400f6a55f124f639143fe01c559059eaba23b22 | <|skeleton|>
class ArtellaCastingManager:
def get_ocurrences_of_asset_in_shot(self, asset_name, shot_name, force_update=False):
"""Returns the number of ocurrences of given asset in given shot :param asset_name: str, name of the asset :param shot_name: str, name of the shot :return: int or None"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArtellaCastingManager:
def get_ocurrences_of_asset_in_shot(self, asset_name, shot_name, force_update=False):
"""Returns the number of ocurrences of given asset in given shot :param asset_name: str, name of the asset :param shot_name: str, name of the shot :return: int or None"""
if not self._c... | the_stack_v2_python_sparse | artellapipe/managers/casting.py | ArtellaPipe/artellapipe | train | 8 | |
f4ee422df99c4879973c53131592fb36c94be282 | [
"X = data[0]\ny = data[1]\nX_train, X_test, y_train, y_test = train_test_split(X, y, shuffle=True, random_state=RANDOM_SEED)\nprint()\nself.validate_linear_regression_model(X_train, X_test, y_train, y_test)\nprint('=' * 50)\nself.evaluate_linear_regression_with_cross_validation(X, y)\nprint('=' * 50)\nself.evaluate... | <|body_start_0|>
X = data[0]
y = data[1]
X_train, X_test, y_train, y_test = train_test_split(X, y, shuffle=True, random_state=RANDOM_SEED)
print()
self.validate_linear_regression_model(X_train, X_test, y_train, y_test)
print('=' * 50)
self.evaluate_linear_regressi... | In this module, we survey more common metrics for evaluating regression and classification models. Other metrics are explored in the other sample modules.Note: we don't include validation interpretations. Read the docs. | ValidateModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidateModel:
"""In this module, we survey more common metrics for evaluating regression and classification models. Other metrics are explored in the other sample modules.Note: we don't include validation interpretations. Read the docs."""
def validate_model(self, data):
"""Demonstr... | stack_v2_sparse_classes_36k_train_003028 | 6,315 | no_license | [
{
"docstring": "Demonstrate common metrics for regression and classification use cases and how to implement them using Scikit-learn. :param data: tuple - a tuple containing the data and the targets. :return:",
"name": "validate_model",
"signature": "def validate_model(self, data)"
},
{
"docstrin... | 4 | stack_v2_sparse_classes_30k_train_013708 | Implement the Python class `ValidateModel` described below.
Class description:
In this module, we survey more common metrics for evaluating regression and classification models. Other metrics are explored in the other sample modules.Note: we don't include validation interpretations. Read the docs.
Method signatures a... | Implement the Python class `ValidateModel` described below.
Class description:
In this module, we survey more common metrics for evaluating regression and classification models. Other metrics are explored in the other sample modules.Note: we don't include validation interpretations. Read the docs.
Method signatures a... | ee0b2a44fde77c44a3097459ecbec3b4d26b15d3 | <|skeleton|>
class ValidateModel:
"""In this module, we survey more common metrics for evaluating regression and classification models. Other metrics are explored in the other sample modules.Note: we don't include validation interpretations. Read the docs."""
def validate_model(self, data):
"""Demonstr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValidateModel:
"""In this module, we survey more common metrics for evaluating regression and classification models. Other metrics are explored in the other sample modules.Note: we don't include validation interpretations. Read the docs."""
def validate_model(self, data):
"""Demonstrate common me... | the_stack_v2_python_sparse | model_evaluation_metrics.py | GDBSD/ml_sprouts | train | 0 |
830346597676594a708e350f622b68ef6f1b525d | [
"self.exclusion_list = BoxHolder()\nif initial_exclusion_list is not None:\n for initial in initial_exclusion_list:\n self.exclusion_list.add_box(initial)",
"excluded = self.exclusion_list.is_in_box(mz, rt)\nif excluded:\n return (True, 0.0)\nelse:\n return (False, 1.0)",
"rt = current_scan.rt\n... | <|body_start_0|>
self.exclusion_list = BoxHolder()
if initial_exclusion_list is not None:
for initial in initial_exclusion_list:
self.exclusion_list.add_box(initial)
<|end_body_0|>
<|body_start_1|>
excluded = self.exclusion_list.is_in_box(mz, rt)
if excluded:... | A class that perform standard dynamic exclusion for Top-N. This is based on checked whether an m/z and RT value lies in certain exclusion boxes. | TopNExclusion | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopNExclusion:
"""A class that perform standard dynamic exclusion for Top-N. This is based on checked whether an m/z and RT value lies in certain exclusion boxes."""
def __init__(self, initial_exclusion_list=None):
"""Initialise a Top-N dynamic exclusion object Args: initial_exclusio... | stack_v2_sparse_classes_36k_train_003029 | 16,141 | permissive | [
{
"docstring": "Initialise a Top-N dynamic exclusion object Args: initial_exclusion_list: the initial list of boxes, if provided",
"name": "__init__",
"signature": "def __init__(self, initial_exclusion_list=None)"
},
{
"docstring": "Checks if a pair of (mz, rt) value is currently excluded by dyn... | 4 | stack_v2_sparse_classes_30k_train_010089 | Implement the Python class `TopNExclusion` described below.
Class description:
A class that perform standard dynamic exclusion for Top-N. This is based on checked whether an m/z and RT value lies in certain exclusion boxes.
Method signatures and docstrings:
- def __init__(self, initial_exclusion_list=None): Initialis... | Implement the Python class `TopNExclusion` described below.
Class description:
A class that perform standard dynamic exclusion for Top-N. This is based on checked whether an m/z and RT value lies in certain exclusion boxes.
Method signatures and docstrings:
- def __init__(self, initial_exclusion_list=None): Initialis... | e5d97ae4ff42d613fc55db51443e1e733999b908 | <|skeleton|>
class TopNExclusion:
"""A class that perform standard dynamic exclusion for Top-N. This is based on checked whether an m/z and RT value lies in certain exclusion boxes."""
def __init__(self, initial_exclusion_list=None):
"""Initialise a Top-N dynamic exclusion object Args: initial_exclusio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TopNExclusion:
"""A class that perform standard dynamic exclusion for Top-N. This is based on checked whether an m/z and RT value lies in certain exclusion boxes."""
def __init__(self, initial_exclusion_list=None):
"""Initialise a Top-N dynamic exclusion object Args: initial_exclusion_list: the i... | the_stack_v2_python_sparse | vimms/Exclusion.py | glasgowcompbio/vimms | train | 22 |
7ebf84e1e23dbb7e1b6c0d30e4f99882062f4017 | [
"super().__init__(menu, type, text, x, y)\nself.callback = callback\nself.last_pressed = True",
"hover = self.rect.collidepoint(pygame.mouse.get_pos())\nself.highlighted = hover and self.callback is not None\nsuper().update()",
"hover = self.rect.collidepoint(pygame.mouse.get_pos())\nif hover and self.callback ... | <|body_start_0|>
super().__init__(menu, type, text, x, y)
self.callback = callback
self.last_pressed = True
<|end_body_0|>
<|body_start_1|>
hover = self.rect.collidepoint(pygame.mouse.get_pos())
self.highlighted = hover and self.callback is not None
super().update()
<|en... | 响应被点击的菜单标签 | MenuButton | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MenuButton:
"""响应被点击的菜单标签"""
def __init__(self, menu, type, text, x, y, callback):
"""Args: menu (Menu): menu实例 type (str): prefab名称,用于字体和背景 text (str): 在按钮上显示的文字 x (int): x坐标 y (int): y坐标 callback (callable): 按下按钮时触发的回调函数"""
<|body_0|>
def update(self):
"""每帧调用,... | stack_v2_sparse_classes_36k_train_003030 | 8,937 | no_license | [
{
"docstring": "Args: menu (Menu): menu实例 type (str): prefab名称,用于字体和背景 text (str): 在按钮上显示的文字 x (int): x坐标 y (int): y坐标 callback (callable): 按下按钮时触发的回调函数",
"name": "__init__",
"signature": "def __init__(self, menu, type, text, x, y, callback)"
},
{
"docstring": "每帧调用,查找鼠标点击",
"name": "update"... | 3 | stack_v2_sparse_classes_30k_train_020451 | Implement the Python class `MenuButton` described below.
Class description:
响应被点击的菜单标签
Method signatures and docstrings:
- def __init__(self, menu, type, text, x, y, callback): Args: menu (Menu): menu实例 type (str): prefab名称,用于字体和背景 text (str): 在按钮上显示的文字 x (int): x坐标 y (int): y坐标 callback (callable): 按下按钮时触发的回调函数
- de... | Implement the Python class `MenuButton` described below.
Class description:
响应被点击的菜单标签
Method signatures and docstrings:
- def __init__(self, menu, type, text, x, y, callback): Args: menu (Menu): menu实例 type (str): prefab名称,用于字体和背景 text (str): 在按钮上显示的文字 x (int): x坐标 y (int): y坐标 callback (callable): 按下按钮时触发的回调函数
- de... | 4dfcab372fe3d0562e685b9f553f2af4a83f7f5f | <|skeleton|>
class MenuButton:
"""响应被点击的菜单标签"""
def __init__(self, menu, type, text, x, y, callback):
"""Args: menu (Menu): menu实例 type (str): prefab名称,用于字体和背景 text (str): 在按钮上显示的文字 x (int): x坐标 y (int): y坐标 callback (callable): 按下按钮时触发的回调函数"""
<|body_0|>
def update(self):
"""每帧调用,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MenuButton:
"""响应被点击的菜单标签"""
def __init__(self, menu, type, text, x, y, callback):
"""Args: menu (Menu): menu实例 type (str): prefab名称,用于字体和背景 text (str): 在按钮上显示的文字 x (int): x坐标 y (int): y坐标 callback (callable): 按下按钮时触发的回调函数"""
super().__init__(menu, type, text, x, y)
self.callback ... | the_stack_v2_python_sparse | 高级编程技术/python-game/tower-defence-master/core/menu.py | ZhuangXuward/Learning-data-backup | train | 0 |
5945c55c1e4223f6fbccbde9fc7b8c364968db77 | [
"selector = '#ae-appbar-version-id option[selected=\"selected\"]'\nversion_element, = self.doc.cssselect(selector)\nreturn version_element.text.strip()",
"selector = '#ae-instances-summary-table tbody tr'\nrow, = self.doc.cssselect(selector)\nchildren = list(row)\nassert len(children) == 4, [child.text for child ... | <|body_start_0|>
selector = '#ae-appbar-version-id option[selected="selected"]'
version_element, = self.doc.cssselect(selector)
return version_element.text.strip()
<|end_body_0|>
<|body_start_1|>
selector = '#ae-instances-summary-table tbody tr'
row, = self.doc.cssselect(selecto... | An API for the contents of /instances as structured data. | Instances | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Instances:
"""An API for the contents of /instances as structured data."""
def version(self):
"""The app version that owns these instances."""
<|body_0|>
def raw_summary_dict(self):
"""Performance statistics summarized across instances. Returns: A dict with field... | stack_v2_sparse_classes_36k_train_003031 | 12,694 | no_license | [
{
"docstring": "The app version that owns these instances.",
"name": "version",
"signature": "def version(self)"
},
{
"docstring": "Performance statistics summarized across instances. Returns: A dict with fields like this: {'total_instances': '100 total (10 Resident)', 'average_qps': '2.243', 'a... | 4 | stack_v2_sparse_classes_30k_train_009672 | Implement the Python class `Instances` described below.
Class description:
An API for the contents of /instances as structured data.
Method signatures and docstrings:
- def version(self): The app version that owns these instances.
- def raw_summary_dict(self): Performance statistics summarized across instances. Retur... | Implement the Python class `Instances` described below.
Class description:
An API for the contents of /instances as structured data.
Method signatures and docstrings:
- def version(self): The app version that owns these instances.
- def raw_summary_dict(self): Performance statistics summarized across instances. Retur... | d6546e4fa01902a6a3675c7b423d0ba75cf20b29 | <|skeleton|>
class Instances:
"""An API for the contents of /instances as structured data."""
def version(self):
"""The app version that owns these instances."""
<|body_0|>
def raw_summary_dict(self):
"""Performance statistics summarized across instances. Returns: A dict with field... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Instances:
"""An API for the contents of /instances as structured data."""
def version(self):
"""The app version that owns these instances."""
selector = '#ae-appbar-version-id option[selected="selected"]'
version_element, = self.doc.cssselect(selector)
return version_elem... | the_stack_v2_python_sparse | src/gae_dashboard/parsers.py | prantik/analytics | train | 1 |
cbee35a9c16a5f518592562b72d09e0e84fcafe6 | [
"if not Tk:\n return\nself.path = g.os_path_join(g.app.loadDir, '..', 'Icons')\nfor ivar, icon in (('lt_nav_disabled_image', 'lt_arrow_disabled.gif'), ('lt_nav_enabled_image', 'lt_arrow_enabled.gif'), ('rt_nav_disabled_image', 'rt_arrow_disabled.gif'), ('rt_nav_enabled_image', 'rt_arrow_enabled.gif')):\n imag... | <|body_start_0|>
if not Tk:
return
self.path = g.os_path_join(g.app.loadDir, '..', 'Icons')
for ivar, icon in (('lt_nav_disabled_image', 'lt_arrow_disabled.gif'), ('lt_nav_enabled_image', 'lt_arrow_enabled.gif'), ('rt_nav_disabled_image', 'rt_arrow_disabled.gif'), ('rt_nav_enabled_im... | An image manager class. | imageClass | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class imageClass:
"""An image manager class."""
def __init__(self):
"""Load the images needed for the module."""
<|body_0|>
def createImage(self, iconName):
"""Load a single image from a file."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not Tk:... | stack_v2_sparse_classes_36k_train_003032 | 25,137 | no_license | [
{
"docstring": "Load the images needed for the module.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Load a single image from a file.",
"name": "createImage",
"signature": "def createImage(self, iconName)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004760 | Implement the Python class `imageClass` described below.
Class description:
An image manager class.
Method signatures and docstrings:
- def __init__(self): Load the images needed for the module.
- def createImage(self, iconName): Load a single image from a file. | Implement the Python class `imageClass` described below.
Class description:
An image manager class.
Method signatures and docstrings:
- def __init__(self): Load the images needed for the module.
- def createImage(self, iconName): Load a single image from a file.
<|skeleton|>
class imageClass:
"""An image manager... | 28c22721e1bc313c120a8a6c288893bc566a5c67 | <|skeleton|>
class imageClass:
"""An image manager class."""
def __init__(self):
"""Load the images needed for the module."""
<|body_0|>
def createImage(self, iconName):
"""Load a single image from a file."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class imageClass:
"""An image manager class."""
def __init__(self):
"""Load the images needed for the module."""
if not Tk:
return
self.path = g.os_path_join(g.app.loadDir, '..', 'Icons')
for ivar, icon in (('lt_nav_disabled_image', 'lt_arrow_disabled.gif'), ('lt_nav... | the_stack_v2_python_sparse | Projects/Archived Tk code/nav_buttons.py | leo-editor/leo-editor-contrib | train | 6 |
c8e847637c17cda71821a261333b1324523f675e | [
"total_collect = defaultdict(list)\nfor word in wordList:\n for num in range(len(beginWord)):\n key = word[:num] + '_' + word[num + 1:]\n total_collect[key].append(word)\nprint(str(total_collect))",
"current_word = beginWord\nword_seen = set(wordList)\nif beginWord in word_seen:\n word_seen.re... | <|body_start_0|>
total_collect = defaultdict(list)
for word in wordList:
for num in range(len(beginWord)):
key = word[:num] + '_' + word[num + 1:]
total_collect[key].append(word)
print(str(total_collect))
<|end_body_0|>
<|body_start_1|>
curren... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def ladderLengthBFS(self, beginWord, endWord, wordList):
""":param beginWord: :param endWord: :param wordList: :return:"""
<|body_0|>
def ladderLength(self, beginWord, endWord, wordList):
""":type beginWord: str :type endWord: str :type wordList: List[str] ... | stack_v2_sparse_classes_36k_train_003033 | 2,543 | no_license | [
{
"docstring": ":param beginWord: :param endWord: :param wordList: :return:",
"name": "ladderLengthBFS",
"signature": "def ladderLengthBFS(self, beginWord, endWord, wordList)"
},
{
"docstring": ":type beginWord: str :type endWord: str :type wordList: List[str] :rtype: int",
"name": "ladderLe... | 2 | stack_v2_sparse_classes_30k_train_015535 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def ladderLengthBFS(self, beginWord, endWord, wordList): :param beginWord: :param endWord: :param wordList: :return:
- def ladderLength(self, beginWord, endWord, wordList): :type... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def ladderLengthBFS(self, beginWord, endWord, wordList): :param beginWord: :param endWord: :param wordList: :return:
- def ladderLength(self, beginWord, endWord, wordList): :type... | 8532260cda00453490b2fe554d521a54eaed219c | <|skeleton|>
class Solution:
def ladderLengthBFS(self, beginWord, endWord, wordList):
""":param beginWord: :param endWord: :param wordList: :return:"""
<|body_0|>
def ladderLength(self, beginWord, endWord, wordList):
""":type beginWord: str :type endWord: str :type wordList: List[str] ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def ladderLengthBFS(self, beginWord, endWord, wordList):
""":param beginWord: :param endWord: :param wordList: :return:"""
total_collect = defaultdict(list)
for word in wordList:
for num in range(len(beginWord)):
key = word[:num] + '_' + word[num +... | the_stack_v2_python_sparse | graph/wordLadder.py | Suriya0404/Algorithm | train | 0 | |
f1f2ab8a2dd361b8dd32ad5e25f9c3c0393a02d9 | [
"if not field:\n raise ValueError('Empty field name.')\nif not is_string(field):\n raise TypeError('The field name must be a string, not {0}'.format(type(field).__name__))\nif ' ' in field:\n raise ValueError(\"Field name can't contain spaces.\")\nself.__field = field\nspecifications = _get_specifications(... | <|body_start_0|>
if not field:
raise ValueError('Empty field name.')
if not is_string(field):
raise TypeError('The field name must be a string, not {0}'.format(type(field).__name__))
if ' ' in field:
raise ValueError("Field name can't contain spaces.")
... | @Requires decorator Defines a required service | Requires | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Requires:
"""@Requires decorator Defines a required service"""
def __init__(self, field, specification, aggregate=False, optional=False, spec_filter=None):
"""Sets up the requirement :param field: The injected field :param specification: The injected service specification :param aggr... | stack_v2_sparse_classes_36k_train_003034 | 41,418 | permissive | [
{
"docstring": "Sets up the requirement :param field: The injected field :param specification: The injected service specification :param aggregate: If true, injects a list :param optional: If true, this injection is optional :param spec_filter: An LDAP query to filter injected services upon their properties :ra... | 2 | stack_v2_sparse_classes_30k_train_006454 | Implement the Python class `Requires` described below.
Class description:
@Requires decorator Defines a required service
Method signatures and docstrings:
- def __init__(self, field, specification, aggregate=False, optional=False, spec_filter=None): Sets up the requirement :param field: The injected field :param spec... | Implement the Python class `Requires` described below.
Class description:
@Requires decorator Defines a required service
Method signatures and docstrings:
- def __init__(self, field, specification, aggregate=False, optional=False, spec_filter=None): Sets up the requirement :param field: The injected field :param spec... | 686556cdde20beba77ae202de9969be46feed5e2 | <|skeleton|>
class Requires:
"""@Requires decorator Defines a required service"""
def __init__(self, field, specification, aggregate=False, optional=False, spec_filter=None):
"""Sets up the requirement :param field: The injected field :param specification: The injected service specification :param aggr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Requires:
"""@Requires decorator Defines a required service"""
def __init__(self, field, specification, aggregate=False, optional=False, spec_filter=None):
"""Sets up the requirement :param field: The injected field :param specification: The injected service specification :param aggregate: If tru... | the_stack_v2_python_sparse | python/src/lib/python/pelix/ipopo/decorators.py | cohorte/cohorte-runtime | train | 3 |
b9de802fcd8dbde5c4402a3d4af3d7d349f59f3b | [
"try:\n help_args_set = {'-h', '--help'}\n if len(set(sys.argv).union(help_args_set)) < len(help_args_set) + 2:\n super().print_help()\n return\n args = [arg for arg in sys.argv if arg not in help_args_set]\n parsed_arguments = super().parse_args_into_dataclasses(args=args, return_remainin... | <|body_start_0|>
try:
help_args_set = {'-h', '--help'}
if len(set(sys.argv).union(help_args_set)) < len(help_args_set) + 2:
super().print_help()
return
args = [arg for arg in sys.argv if arg not in help_args_set]
parsed_arguments = ... | Argument parser using a custom help logic. | TrainerArgumentParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrainerArgumentParser:
"""Argument parser using a custom help logic."""
def print_help(self, file: Optional[IO[str]]=None) -> None:
"""Print help checking dynamically whether a specific pipeline is passed. Args: file: an optional I/O stream. Defaults to None, a.k.a., stdout and stder... | stack_v2_sparse_classes_36k_train_003035 | 6,950 | permissive | [
{
"docstring": "Print help checking dynamically whether a specific pipeline is passed. Args: file: an optional I/O stream. Defaults to None, a.k.a., stdout and stderr.",
"name": "print_help",
"signature": "def print_help(self, file: Optional[IO[str]]=None) -> None"
},
{
"docstring": "Overriding ... | 2 | null | Implement the Python class `TrainerArgumentParser` described below.
Class description:
Argument parser using a custom help logic.
Method signatures and docstrings:
- def print_help(self, file: Optional[IO[str]]=None) -> None: Print help checking dynamically whether a specific pipeline is passed. Args: file: an option... | Implement the Python class `TrainerArgumentParser` described below.
Class description:
Argument parser using a custom help logic.
Method signatures and docstrings:
- def print_help(self, file: Optional[IO[str]]=None) -> None: Print help checking dynamically whether a specific pipeline is passed. Args: file: an option... | 0b69b7d5b261f2f9af3984793c1295b9b80cd01a | <|skeleton|>
class TrainerArgumentParser:
"""Argument parser using a custom help logic."""
def print_help(self, file: Optional[IO[str]]=None) -> None:
"""Print help checking dynamically whether a specific pipeline is passed. Args: file: an optional I/O stream. Defaults to None, a.k.a., stdout and stder... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TrainerArgumentParser:
"""Argument parser using a custom help logic."""
def print_help(self, file: Optional[IO[str]]=None) -> None:
"""Print help checking dynamically whether a specific pipeline is passed. Args: file: an optional I/O stream. Defaults to None, a.k.a., stdout and stderr."""
... | the_stack_v2_python_sparse | src/gt4sd/cli/trainer.py | GT4SD/gt4sd-core | train | 239 |
ef8def231402a50d580ae3a5dbcf12c7a763370b | [
"field_data = validated_data.get('columns', [])\nif field_data:\n columns = ColumnNameSerializer(data=field_data, many=True, required=False)\n if columns.is_valid():\n column_names = [col_data['name'] for col_data in columns.data]\n bulk_list = [ActionColumnConditionTuple(action=action_obj, colu... | <|body_start_0|>
field_data = validated_data.get('columns', [])
if field_data:
columns = ColumnNameSerializer(data=field_data, many=True, required=False)
if columns.is_valid():
column_names = [col_data['name'] for col_data in columns.data]
bulk_lis... | Action serializer recursively traversing conditions but not columns. The serializer does not create any columns and relies on them being already created and receiving only the names | ActionSerializer | [
"MIT",
"LGPL-2.0-or-later",
"Python-2.0",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActionSerializer:
"""Action serializer recursively traversing conditions but not columns. The serializer does not create any columns and relies on them being already created and receiving only the names"""
def create_column_condition_pairs(self, validated_data, action_obj, wflow_columns):
... | stack_v2_sparse_classes_36k_train_003036 | 14,977 | permissive | [
{
"docstring": "Create the column_condition pairs. :param validated_data: Source data :param action_obj: action hosting the condition :param wflow_columns: All the columns available :return: Create the objects and store them in the DB",
"name": "create_column_condition_pairs",
"signature": "def create_c... | 2 | stack_v2_sparse_classes_30k_train_013017 | Implement the Python class `ActionSerializer` described below.
Class description:
Action serializer recursively traversing conditions but not columns. The serializer does not create any columns and relies on them being already created and receiving only the names
Method signatures and docstrings:
- def create_column_... | Implement the Python class `ActionSerializer` described below.
Class description:
Action serializer recursively traversing conditions but not columns. The serializer does not create any columns and relies on them being already created and receiving only the names
Method signatures and docstrings:
- def create_column_... | 5473e9faa24c71a2a1102d47ebc2cbf27608e42a | <|skeleton|>
class ActionSerializer:
"""Action serializer recursively traversing conditions but not columns. The serializer does not create any columns and relies on them being already created and receiving only the names"""
def create_column_condition_pairs(self, validated_data, action_obj, wflow_columns):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActionSerializer:
"""Action serializer recursively traversing conditions but not columns. The serializer does not create any columns and relies on them being already created and receiving only the names"""
def create_column_condition_pairs(self, validated_data, action_obj, wflow_columns):
"""Crea... | the_stack_v2_python_sparse | ontask/action/serializers.py | LucasFranciscoCorreia/ontask_b | train | 0 |
8937a59d4347230cda62d29c9273c4418577590a | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn LocalizedNotificationMessage()",
"from .entity import Entity\nfrom .entity import Entity\nfields: Dict[str, Callable[[Any], None]] = {'isDefault': lambda n: setattr(self, 'is_default', n.get_bool_value()), 'lastModifiedDateTime': lambd... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return LocalizedNotificationMessage()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .entity import Entity
fields: Dict[str, Callable[[Any], None]] = {'isDefault': lamb... | The text content of a Notification Message Template for the specified locale. | LocalizedNotificationMessage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocalizedNotificationMessage:
"""The text content of a Notification Message Template for the specified locale."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LocalizedNotificationMessage:
"""Creates a new instance of the appropriate class based on dis... | stack_v2_sparse_classes_36k_train_003037 | 3,272 | 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: LocalizedNotificationMessage",
"name": "create_from_discriminator_value",
"signature": "def create_from_disc... | 3 | stack_v2_sparse_classes_30k_train_003937 | Implement the Python class `LocalizedNotificationMessage` described below.
Class description:
The text content of a Notification Message Template for the specified locale.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LocalizedNotificationMessage: Cre... | Implement the Python class `LocalizedNotificationMessage` described below.
Class description:
The text content of a Notification Message Template for the specified locale.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LocalizedNotificationMessage: Cre... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class LocalizedNotificationMessage:
"""The text content of a Notification Message Template for the specified locale."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LocalizedNotificationMessage:
"""Creates a new instance of the appropriate class based on dis... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LocalizedNotificationMessage:
"""The text content of a Notification Message Template for the specified locale."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LocalizedNotificationMessage:
"""Creates a new instance of the appropriate class based on discriminator va... | the_stack_v2_python_sparse | msgraph/generated/models/localized_notification_message.py | microsoftgraph/msgraph-sdk-python | train | 135 |
d3f2ba6ece097e389f63d9be6e284cee59ab2bf6 | [
"super().__init__()\nself.queue = queue\nself.data_incoming = True",
"while self.data_incoming is True or len(self.queue) > 0:\n if len(self.queue) > 0:\n print(self.queue.data_queue.pop(0))\n time.sleep(0.5)\n else:\n time.sleep(0.75)"
] | <|body_start_0|>
super().__init__()
self.queue = queue
self.data_incoming = True
<|end_body_0|>
<|body_start_1|>
while self.data_incoming is True or len(self.queue) > 0:
if len(self.queue) > 0:
print(self.queue.data_queue.pop(0))
time.sleep(0.... | ConsumerThread class used to print the data out. | ConsumerThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConsumerThread:
"""ConsumerThread class used to print the data out."""
def __init__(self, queue: CityOverheadTimeQueue):
"""constructs the queue proxy and sets the data incoming status. :param queue: CityOverheadTimeQueue"""
<|body_0|>
def run(self) -> None:
"""i... | stack_v2_sparse_classes_36k_train_003038 | 4,615 | no_license | [
{
"docstring": "constructs the queue proxy and sets the data incoming status. :param queue: CityOverheadTimeQueue",
"name": "__init__",
"signature": "def __init__(self, queue: CityOverheadTimeQueue)"
},
{
"docstring": "if the queue list is not empty, remove the last item in the queue and if the ... | 2 | stack_v2_sparse_classes_30k_train_010683 | Implement the Python class `ConsumerThread` described below.
Class description:
ConsumerThread class used to print the data out.
Method signatures and docstrings:
- def __init__(self, queue: CityOverheadTimeQueue): constructs the queue proxy and sets the data incoming status. :param queue: CityOverheadTimeQueue
- def... | Implement the Python class `ConsumerThread` described below.
Class description:
ConsumerThread class used to print the data out.
Method signatures and docstrings:
- def __init__(self, queue: CityOverheadTimeQueue): constructs the queue proxy and sets the data incoming status. :param queue: CityOverheadTimeQueue
- def... | 7061af6821d25bf7df6fd6e419ad828f5c1e7d61 | <|skeleton|>
class ConsumerThread:
"""ConsumerThread class used to print the data out."""
def __init__(self, queue: CityOverheadTimeQueue):
"""constructs the queue proxy and sets the data incoming status. :param queue: CityOverheadTimeQueue"""
<|body_0|>
def run(self) -> None:
"""i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConsumerThread:
"""ConsumerThread class used to print the data out."""
def __init__(self, queue: CityOverheadTimeQueue):
"""constructs the queue proxy and sets the data incoming status. :param queue: CityOverheadTimeQueue"""
super().__init__()
self.queue = queue
self.data_... | the_stack_v2_python_sparse | Labs/Lab10/producer_consumer.py | jieunyu0623/3522_A00998343 | train | 1 |
f9cadcded151c9b6a9f402cd63432e1804b87ac7 | [
"idx = 0\nwhile idx < len(intervals):\n cur = intervals[idx]\n if newInterval[0] <= cur[0]:\n intervals.insert(idx, newInterval)\n break\n else:\n idx += 1\nelse:\n intervals.append(newInterval)\nreturn self.merge(intervals)",
"if len(intervals) < 2:\n return intervals\nidx = 0... | <|body_start_0|>
idx = 0
while idx < len(intervals):
cur = intervals[idx]
if newInterval[0] <= cur[0]:
intervals.insert(idx, newInterval)
break
else:
idx += 1
else:
intervals.append(newInterval)
... | Solution_B | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution_B:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
"""Insert the intervals only according to the first element, so that intervals is still sorted Then merge like LC056"""
<|body_0|>
def merge(self, intervals):
"""Help... | stack_v2_sparse_classes_36k_train_003039 | 4,614 | permissive | [
{
"docstring": "Insert the intervals only according to the first element, so that intervals is still sorted Then merge like LC056",
"name": "insert",
"signature": "def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]"
},
{
"docstring": "Helper B modified from l... | 2 | stack_v2_sparse_classes_30k_train_017565 | Implement the Python class `Solution_B` described below.
Class description:
Implement the Solution_B class.
Method signatures and docstrings:
- def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: Insert the intervals only according to the first element, so that intervals is still ... | Implement the Python class `Solution_B` described below.
Class description:
Implement the Solution_B class.
Method signatures and docstrings:
- def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: Insert the intervals only according to the first element, so that intervals is still ... | 143422321cbc3715ca08f6c3af8f960a55887ced | <|skeleton|>
class Solution_B:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
"""Insert the intervals only according to the first element, so that intervals is still sorted Then merge like LC056"""
<|body_0|>
def merge(self, intervals):
"""Help... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution_B:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
"""Insert the intervals only according to the first element, so that intervals is still sorted Then merge like LC056"""
idx = 0
while idx < len(intervals):
cur = intervals[i... | the_stack_v2_python_sparse | LeetCode/LC057_insert_interval.py | jxie0755/Learning_Python | train | 0 | |
373f7d1380b1773e5921521e75257f3befa159ac | [
"if source == 'auxiliary_file':\n logger.debug('Creating an auxiliary FileStoreItem')\n item = self.create(sharename=sharename, filetype=filetype)\n return item\nif not source:\n logger.error('Source is required but was not provided')\n return None\nitem = self.create(source=map_source(source), share... | <|body_start_0|>
if source == 'auxiliary_file':
logger.debug('Creating an auxiliary FileStoreItem')
item = self.create(sharename=sharename, filetype=filetype)
return item
if not source:
logger.error('Source is required but was not provided')
re... | Custom model manager to handle creation and retrieval of FileStoreItems | _FileStoreItemManager | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _FileStoreItemManager:
"""Custom model manager to handle creation and retrieval of FileStoreItems"""
def create_item(self, source, sharename='', filetype=''):
"""A "constructor" for FileStoreItem. :param source: URL or absolute file system path to a file. :type source: str. :returns:... | stack_v2_sparse_classes_36k_train_003040 | 23,458 | permissive | [
{
"docstring": "A \"constructor\" for FileStoreItem. :param source: URL or absolute file system path to a file. :type source: str. :returns: FileStoreItem -- if success, None if failure.",
"name": "create_item",
"signature": "def create_item(self, source, sharename='', filetype='')"
},
{
"docstr... | 2 | stack_v2_sparse_classes_30k_train_009802 | Implement the Python class `_FileStoreItemManager` described below.
Class description:
Custom model manager to handle creation and retrieval of FileStoreItems
Method signatures and docstrings:
- def create_item(self, source, sharename='', filetype=''): A "constructor" for FileStoreItem. :param source: URL or absolute... | Implement the Python class `_FileStoreItemManager` described below.
Class description:
Custom model manager to handle creation and retrieval of FileStoreItems
Method signatures and docstrings:
- def create_item(self, source, sharename='', filetype=''): A "constructor" for FileStoreItem. :param source: URL or absolute... | fca97c904be407c6619608e13437f25a9fc9e979 | <|skeleton|>
class _FileStoreItemManager:
"""Custom model manager to handle creation and retrieval of FileStoreItems"""
def create_item(self, source, sharename='', filetype=''):
"""A "constructor" for FileStoreItem. :param source: URL or absolute file system path to a file. :type source: str. :returns:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _FileStoreItemManager:
"""Custom model manager to handle creation and retrieval of FileStoreItems"""
def create_item(self, source, sharename='', filetype=''):
"""A "constructor" for FileStoreItem. :param source: URL or absolute file system path to a file. :type source: str. :returns: FileStoreIte... | the_stack_v2_python_sparse | refinery/file_store/models.py | ShuhratBek/refinery-platform | train | 1 |
9202d2e7929f8e5c3556ea256de476a3e1ab9cf5 | [
"self.category_slot = None\nif 'meta' not in kwargs:\n kwargs['meta'] = {}\nif 'category_slot' in kwargs:\n self.category_slot = kwargs['category_slot']\nif self.category_slot is not None and (not kwargs.get('keys')):\n slot = kwargs['category_slot']\n cat_values = [value[slot] for value in kwargs['valu... | <|body_start_0|>
self.category_slot = None
if 'meta' not in kwargs:
kwargs['meta'] = {}
if 'category_slot' in kwargs:
self.category_slot = kwargs['category_slot']
if self.category_slot is not None and (not kwargs.get('keys')):
slot = kwargs['category_s... | Class for Array field type. | Array | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Array:
"""Class for Array field type."""
def __init__(self, field_id, **kwargs):
"""Init Array class."""
<|body_0|>
def get_values_by_indices_for_slots(self, indices, slots):
"""Get values from specified array slots at matching indices."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_003041 | 11,877 | permissive | [
{
"docstring": "Init Array class.",
"name": "__init__",
"signature": "def __init__(self, field_id, **kwargs)"
},
{
"docstring": "Get values from specified array slots at matching indices.",
"name": "get_values_by_indices_for_slots",
"signature": "def get_values_by_indices_for_slots(self,... | 4 | stack_v2_sparse_classes_30k_train_019790 | Implement the Python class `Array` described below.
Class description:
Class for Array field type.
Method signatures and docstrings:
- def __init__(self, field_id, **kwargs): Init Array class.
- def get_values_by_indices_for_slots(self, indices, slots): Get values from specified array slots at matching indices.
- def... | Implement the Python class `Array` described below.
Class description:
Class for Array field type.
Method signatures and docstrings:
- def __init__(self, field_id, **kwargs): Init Array class.
- def get_values_by_indices_for_slots(self, indices, slots): Get values from specified array slots at matching indices.
- def... | 052a26316d19a48981417bf340d9f57e2cdc653a | <|skeleton|>
class Array:
"""Class for Array field type."""
def __init__(self, field_id, **kwargs):
"""Init Array class."""
<|body_0|>
def get_values_by_indices_for_slots(self, indices, slots):
"""Get values from specified array slots at matching indices."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Array:
"""Class for Array field type."""
def __init__(self, field_id, **kwargs):
"""Init Array class."""
self.category_slot = None
if 'meta' not in kwargs:
kwargs['meta'] = {}
if 'category_slot' in kwargs:
self.category_slot = kwargs['category_slot'... | the_stack_v2_python_sparse | src/blobtools/lib/field.py | blobtoolkit/blobtoolkit | train | 32 |
39f01ab1643286d0d10778342d7146f85a3ca685 | [
"self.d = collections.defaultdict(int)\nself.partial = ''\nself.matches = []\nfor s, t in zip(sentences, times):\n self.d[s] = t",
"if c == '#':\n self.d[self.partial] += 1\n self.partial = ''\n self.matches = []\n return []\nif self.partial == '':\n self.matches = [(-count, s) for s, count in s... | <|body_start_0|>
self.d = collections.defaultdict(int)
self.partial = ''
self.matches = []
for s, t in zip(sentences, times):
self.d[s] = t
<|end_body_0|>
<|body_start_1|>
if c == '#':
self.d[self.partial] += 1
self.partial = ''
se... | AutocompleteSystem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.d = collections.d... | stack_v2_sparse_classes_36k_train_003042 | 1,219 | no_license | [
{
"docstring": ":type sentences: List[str] :type times: List[int]",
"name": "__init__",
"signature": "def __init__(self, sentences, times)"
},
{
"docstring": ":type c: str :rtype: List[str]",
"name": "input",
"signature": "def input(self, c)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019238 | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str] | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str]
<|skeleton|>
cla... | fe5c6936627c2459731ddda6f67422c217b3cc91 | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
self.d = collections.defaultdict(int)
self.partial = ''
self.matches = []
for s, t in zip(sentences, times):
self.d[s] = t
def input(self, ... | the_stack_v2_python_sparse | 642. Design Search Autocomplete System/Python 2/solution.py | HarrrrryLi/LeetCode | train | 0 | |
21c72589692d38e67492f727c2f16663d001671f | [
"super().__init__('opendr_heart_anomaly_detection_node')\nself.publisher = self.create_publisher(Classification2D, output_heart_anomaly_topic, 1)\nself.subscriber = self.create_subscription(Float32MultiArray, input_ecg_topic, self.callback, 1)\nself.bridge = ROS2Bridge()\nself.channels = 1\nself.series_length = 900... | <|body_start_0|>
super().__init__('opendr_heart_anomaly_detection_node')
self.publisher = self.create_publisher(Classification2D, output_heart_anomaly_topic, 1)
self.subscriber = self.create_subscription(Float32MultiArray, input_ecg_topic, self.callback, 1)
self.bridge = ROS2Bridge()
... | HeartAnomalyNode | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HeartAnomalyNode:
def __init__(self, input_ecg_topic='/ecg/ecg', output_heart_anomaly_topic='/opendr/heart_anomaly', device='cuda', model='anbof'):
"""Creates a ROS2 Node for heart anomaly (atrial fibrillation) detection from ecg data :param input_ecg_topic: Topic from which we are readi... | stack_v2_sparse_classes_36k_train_003043 | 4,950 | permissive | [
{
"docstring": "Creates a ROS2 Node for heart anomaly (atrial fibrillation) detection from ecg data :param input_ecg_topic: Topic from which we are reading the input array data :type input_ecg_topic: str :param output_heart_anomaly_topic: Topic to which we are publishing the predicted class :type output_heart_a... | 2 | null | Implement the Python class `HeartAnomalyNode` described below.
Class description:
Implement the HeartAnomalyNode class.
Method signatures and docstrings:
- def __init__(self, input_ecg_topic='/ecg/ecg', output_heart_anomaly_topic='/opendr/heart_anomaly', device='cuda', model='anbof'): Creates a ROS2 Node for heart an... | Implement the Python class `HeartAnomalyNode` described below.
Class description:
Implement the HeartAnomalyNode class.
Method signatures and docstrings:
- def __init__(self, input_ecg_topic='/ecg/ecg', output_heart_anomaly_topic='/opendr/heart_anomaly', device='cuda', model='anbof'): Creates a ROS2 Node for heart an... | b3d6ce670cdf63469fc5766630eb295d67b3d788 | <|skeleton|>
class HeartAnomalyNode:
def __init__(self, input_ecg_topic='/ecg/ecg', output_heart_anomaly_topic='/opendr/heart_anomaly', device='cuda', model='anbof'):
"""Creates a ROS2 Node for heart anomaly (atrial fibrillation) detection from ecg data :param input_ecg_topic: Topic from which we are readi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HeartAnomalyNode:
def __init__(self, input_ecg_topic='/ecg/ecg', output_heart_anomaly_topic='/opendr/heart_anomaly', device='cuda', model='anbof'):
"""Creates a ROS2 Node for heart anomaly (atrial fibrillation) detection from ecg data :param input_ecg_topic: Topic from which we are reading the input a... | the_stack_v2_python_sparse | projects/opendr_ws_2/src/opendr_perception/opendr_perception/heart_anomaly_detection_node.py | opendr-eu/opendr | train | 535 | |
24906ed6aa5b0f57be95b64f1c61cde5804d26b9 | [
"super().__init__(**kwargs)\nfor td in ['pad', 'h_pad', 'w_pad', 'rect']:\n self._params[td] = None\nself.set(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)",
"info = self._params\nrenderer = fig._get_renderer()\nwith getattr(renderer, '_draw_disabled', nullcontext)():\n kwargs = get_tight_layout_figure(fig,... | <|body_start_0|>
super().__init__(**kwargs)
for td in ['pad', 'h_pad', 'w_pad', 'rect']:
self._params[td] = None
self.set(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
<|end_body_0|>
<|body_start_1|>
info = self._params
renderer = fig._get_renderer()
with get... | Implements the ``tight_layout`` geometry management. See :doc:`/tutorials/intermediate/tight_layout_guide` for details. | TightLayoutEngine | [
"CC0-1.0",
"BSD-3-Clause",
"MIT",
"Bitstream-Charter",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-bakoma-fonts-1995",
"LicenseRef-scancode-unknown-license-reference",
"OFL-1.1",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TightLayoutEngine:
"""Implements the ``tight_layout`` geometry management. See :doc:`/tutorials/intermediate/tight_layout_guide` for details."""
def __init__(self, *, pad=1.08, h_pad=None, w_pad=None, rect=(0, 0, 1, 1), **kwargs):
"""Initialize tight_layout engine. Parameters -------... | stack_v2_sparse_classes_36k_train_003044 | 11,335 | permissive | [
{
"docstring": "Initialize tight_layout engine. Parameters ---------- pad : float, default: 1.08 Padding between the figure edge and the edges of subplots, as a fraction of the font size. h_pad, w_pad : float Padding (height/width) between edges of adjacent subplots. Defaults to *pad*. rect : tuple (left, botto... | 3 | stack_v2_sparse_classes_30k_train_019346 | Implement the Python class `TightLayoutEngine` described below.
Class description:
Implements the ``tight_layout`` geometry management. See :doc:`/tutorials/intermediate/tight_layout_guide` for details.
Method signatures and docstrings:
- def __init__(self, *, pad=1.08, h_pad=None, w_pad=None, rect=(0, 0, 1, 1), **kw... | Implement the Python class `TightLayoutEngine` described below.
Class description:
Implements the ``tight_layout`` geometry management. See :doc:`/tutorials/intermediate/tight_layout_guide` for details.
Method signatures and docstrings:
- def __init__(self, *, pad=1.08, h_pad=None, w_pad=None, rect=(0, 0, 1, 1), **kw... | f5042e35b945aded77b23470ead62d7eacefde92 | <|skeleton|>
class TightLayoutEngine:
"""Implements the ``tight_layout`` geometry management. See :doc:`/tutorials/intermediate/tight_layout_guide` for details."""
def __init__(self, *, pad=1.08, h_pad=None, w_pad=None, rect=(0, 0, 1, 1), **kwargs):
"""Initialize tight_layout engine. Parameters -------... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TightLayoutEngine:
"""Implements the ``tight_layout`` geometry management. See :doc:`/tutorials/intermediate/tight_layout_guide` for details."""
def __init__(self, *, pad=1.08, h_pad=None, w_pad=None, rect=(0, 0, 1, 1), **kwargs):
"""Initialize tight_layout engine. Parameters ---------- pad : flo... | the_stack_v2_python_sparse | contrib/python/matplotlib/py3/matplotlib/layout_engine.py | catboost/catboost | train | 8,012 |
c0f3a1fe6aa66d6630df77ac7904c46779ee4d10 | [
"time = self.flowsheet().config.time.first()\nself.flow_in = pyunits.convert(self.flow_vol_in[time], to_units=pyunits.m ** 3 / pyunits.hr)\nself.number_of_units = 2\nself.base_fixed_cap_cost = 6699.1\nself.cap_scaling_exp = 0.4219\nchem_name = 'Ammonia'\nself.chemical_dosage = pyunits.convert(unit_params['dose'] * ... | <|body_start_0|>
time = self.flowsheet().config.time.first()
self.flow_in = pyunits.convert(self.flow_vol_in[time], to_units=pyunits.m ** 3 / pyunits.hr)
self.number_of_units = 2
self.base_fixed_cap_cost = 6699.1
self.cap_scaling_exp = 0.4219
chem_name = 'Ammonia'
... | UnitProcess | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnitProcess:
def fixed_cap(self, unit_params):
"""**"unit_params" are the unit parameters passed to the model from the input sheet as a Python dictionary.** **EXAMPLE: {'dose': 10}** Fixed capital for ammonia addition is a function of ammonia dose, ammonia solution flow, and the number o... | stack_v2_sparse_classes_36k_train_003045 | 3,897 | permissive | [
{
"docstring": "**\"unit_params\" are the unit parameters passed to the model from the input sheet as a Python dictionary.** **EXAMPLE: {'dose': 10}** Fixed capital for ammonia addition is a function of ammonia dose, ammonia solution flow, and the number of units. :param dose: Ammonia dose [mg/L] :type dose: fl... | 4 | null | Implement the Python class `UnitProcess` described below.
Class description:
Implement the UnitProcess class.
Method signatures and docstrings:
- def fixed_cap(self, unit_params): **"unit_params" are the unit parameters passed to the model from the input sheet as a Python dictionary.** **EXAMPLE: {'dose': 10}** Fixed... | Implement the Python class `UnitProcess` described below.
Class description:
Implement the UnitProcess class.
Method signatures and docstrings:
- def fixed_cap(self, unit_params): **"unit_params" are the unit parameters passed to the model from the input sheet as a Python dictionary.** **EXAMPLE: {'dose': 10}** Fixed... | 0e9713a195b50824c4d38ff6ea5db244a6f1ad57 | <|skeleton|>
class UnitProcess:
def fixed_cap(self, unit_params):
"""**"unit_params" are the unit parameters passed to the model from the input sheet as a Python dictionary.** **EXAMPLE: {'dose': 10}** Fixed capital for ammonia addition is a function of ammonia dose, ammonia solution flow, and the number o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnitProcess:
def fixed_cap(self, unit_params):
"""**"unit_params" are the unit parameters passed to the model from the input sheet as a Python dictionary.** **EXAMPLE: {'dose': 10}** Fixed capital for ammonia addition is a function of ammonia dose, ammonia solution flow, and the number of units. :para... | the_stack_v2_python_sparse | watertap3/watertap3/wt_units/ammonia_addition.py | JamariMurke/WaterTAP3 | train | 0 | |
5a6b39c2fdbd33224fe4b545785f92e114f5073d | [
"l = len(start)\nstack_R = []\nstack_L = []\ni = 0\nwhile i < l:\n if start[i] == 'R':\n if end[i] != 'R':\n stack_R.append('R')\n elif start[i] == 'L':\n if end[i] != 'L':\n if not stack_R and stack_L and (stack_L[-1] == 'L'):\n stack_L.pop()\n el... | <|body_start_0|>
l = len(start)
stack_R = []
stack_L = []
i = 0
while i < l:
if start[i] == 'R':
if end[i] != 'R':
stack_R.append('R')
elif start[i] == 'L':
if end[i] != 'L':
if not st... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canTransform(self, start, end):
""":type start: str :type end: str :rtype: bool 77MS"""
<|body_0|>
def canTransform_1(self, start, end):
""":type start: str :type end: str :rtype: bool 107MS"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_003046 | 2,705 | no_license | [
{
"docstring": ":type start: str :type end: str :rtype: bool 77MS",
"name": "canTransform",
"signature": "def canTransform(self, start, end)"
},
{
"docstring": ":type start: str :type end: str :rtype: bool 107MS",
"name": "canTransform_1",
"signature": "def canTransform_1(self, start, en... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canTransform(self, start, end): :type start: str :type end: str :rtype: bool 77MS
- def canTransform_1(self, start, end): :type start: str :type end: str :rtype: bool 107MS | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canTransform(self, start, end): :type start: str :type end: str :rtype: bool 77MS
- def canTransform_1(self, start, end): :type start: str :type end: str :rtype: bool 107MS
... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def canTransform(self, start, end):
""":type start: str :type end: str :rtype: bool 77MS"""
<|body_0|>
def canTransform_1(self, start, end):
""":type start: str :type end: str :rtype: bool 107MS"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canTransform(self, start, end):
""":type start: str :type end: str :rtype: bool 77MS"""
l = len(start)
stack_R = []
stack_L = []
i = 0
while i < l:
if start[i] == 'R':
if end[i] != 'R':
stack_R.append... | the_stack_v2_python_sparse | SwapAdjacentInLRString_MID_777.py | 953250587/leetcode-python | train | 2 | |
3329648e2501b7dca8b637fc70b95d04a9f3a69a | [
"def delete_forward_extremities_for_room_txn(txn: LoggingTransaction) -> int:\n sql = '\\n SELECT event_id FROM event_forward_extremities\\n INNER JOIN events USING (room_id, event_id)\\n WHERE room_id = ?\\n ORDER BY stream_ordering DESC\\n ... | <|body_start_0|>
def delete_forward_extremities_for_room_txn(txn: LoggingTransaction) -> int:
sql = '\n SELECT event_id FROM event_forward_extremities\n INNER JOIN events USING (room_id, event_id)\n WHERE room_id = ?\n ORDER BY stream_order... | EventForwardExtremitiesStore | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventForwardExtremitiesStore:
async def delete_forward_extremities_for_room(self, room_id: str) -> int:
"""Delete any extra forward extremities for a room. Invalidates the "get_latest_event_ids_in_room" cache if any forward extremities were deleted. Returns count deleted."""
<|bo... | stack_v2_sparse_classes_36k_train_003047 | 4,031 | permissive | [
{
"docstring": "Delete any extra forward extremities for a room. Invalidates the \"get_latest_event_ids_in_room\" cache if any forward extremities were deleted. Returns count deleted.",
"name": "delete_forward_extremities_for_room",
"signature": "async def delete_forward_extremities_for_room(self, room_... | 2 | null | Implement the Python class `EventForwardExtremitiesStore` described below.
Class description:
Implement the EventForwardExtremitiesStore class.
Method signatures and docstrings:
- async def delete_forward_extremities_for_room(self, room_id: str) -> int: Delete any extra forward extremities for a room. Invalidates the... | Implement the Python class `EventForwardExtremitiesStore` described below.
Class description:
Implement the EventForwardExtremitiesStore class.
Method signatures and docstrings:
- async def delete_forward_extremities_for_room(self, room_id: str) -> int: Delete any extra forward extremities for a room. Invalidates the... | d35bed8369514fe727b4fe1afb68f48cc8b2655a | <|skeleton|>
class EventForwardExtremitiesStore:
async def delete_forward_extremities_for_room(self, room_id: str) -> int:
"""Delete any extra forward extremities for a room. Invalidates the "get_latest_event_ids_in_room" cache if any forward extremities were deleted. Returns count deleted."""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventForwardExtremitiesStore:
async def delete_forward_extremities_for_room(self, room_id: str) -> int:
"""Delete any extra forward extremities for a room. Invalidates the "get_latest_event_ids_in_room" cache if any forward extremities were deleted. Returns count deleted."""
def delete_forward... | the_stack_v2_python_sparse | synapse/storage/databases/main/events_forward_extremities.py | matrix-org/synapse | train | 12,215 | |
fed05fdea0a20a7fe134eb328481b91fd4fa09a5 | [
"if connector is None:\n connector = CONNECTOR\nself._connector = connector",
"if '?' in uri:\n path, query = uri.split('?', 1)\n args = urllib.parse.parse_qs(query)\nelse:\n path = uri\n query = None\n args = {}\nresult = utils.FindMatch(self._connector, path)\nif result is None:\n raise htt... | <|body_start_0|>
if connector is None:
connector = CONNECTOR
self._connector = connector
<|end_body_0|>
<|body_start_1|>
if '?' in uri:
path, query = uri.split('?', 1)
args = urllib.parse.parse_qs(query)
else:
path = uri
query ... | Map resource to method. | Mapper | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mapper:
"""Map resource to method."""
def __init__(self, connector=None):
"""Resource mapper constructor. @param connector: a dictionary, mapping method name with URL path regexp"""
<|body_0|>
def getController(self, uri):
"""Find method for a given URI. @param u... | stack_v2_sparse_classes_36k_train_003048 | 10,260 | permissive | [
{
"docstring": "Resource mapper constructor. @param connector: a dictionary, mapping method name with URL path regexp",
"name": "__init__",
"signature": "def __init__(self, connector=None)"
},
{
"docstring": "Find method for a given URI. @param uri: string with URI @return: None if no method is ... | 2 | null | Implement the Python class `Mapper` described below.
Class description:
Map resource to method.
Method signatures and docstrings:
- def __init__(self, connector=None): Resource mapper constructor. @param connector: a dictionary, mapping method name with URL path regexp
- def getController(self, uri): Find method for ... | Implement the Python class `Mapper` described below.
Class description:
Map resource to method.
Method signatures and docstrings:
- def __init__(self, connector=None): Resource mapper constructor. @param connector: a dictionary, mapping method name with URL path regexp
- def getController(self, uri): Find method for ... | 456ea285a7583183c2c8e5bcffe9006ec8a9d658 | <|skeleton|>
class Mapper:
"""Map resource to method."""
def __init__(self, connector=None):
"""Resource mapper constructor. @param connector: a dictionary, mapping method name with URL path regexp"""
<|body_0|>
def getController(self, uri):
"""Find method for a given URI. @param u... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Mapper:
"""Map resource to method."""
def __init__(self, connector=None):
"""Resource mapper constructor. @param connector: a dictionary, mapping method name with URL path regexp"""
if connector is None:
connector = CONNECTOR
self._connector = connector
def getCon... | the_stack_v2_python_sparse | lib/rapi/connector.py | ganeti/ganeti | train | 465 |
022513e06de38bc45441ce79e5269fa1cb3ce05e | [
"await data.check(user)\nasync with aiosqlite.connect('data\\\\economy.db') as conn:\n async with conn.execute('SELECT * from ECONOMY') as cursor:\n async for row in cursor:\n if row[0] == user:\n return row[1]",
"await data.check(user)\nasync with aiosqlite.connect('data\\\\ec... | <|body_start_0|>
await data.check(user)
async with aiosqlite.connect('data\\economy.db') as conn:
async with conn.execute('SELECT * from ECONOMY') as cursor:
async for row in cursor:
if row[0] == user:
return row[1]
<|end_body_0|>
... | Wallet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Wallet:
async def get(self, user):
"""Gets the balance of somebody's wallet."""
<|body_0|>
async def add(self, user, add):
"""Adds money to somebody's wallet."""
<|body_1|>
async def remove(self, user, take):
"""Removes money from somebody's wall... | stack_v2_sparse_classes_36k_train_003049 | 5,807 | no_license | [
{
"docstring": "Gets the balance of somebody's wallet.",
"name": "get",
"signature": "async def get(self, user)"
},
{
"docstring": "Adds money to somebody's wallet.",
"name": "add",
"signature": "async def add(self, user, add)"
},
{
"docstring": "Removes money from somebody's wal... | 3 | stack_v2_sparse_classes_30k_train_012230 | Implement the Python class `Wallet` described below.
Class description:
Implement the Wallet class.
Method signatures and docstrings:
- async def get(self, user): Gets the balance of somebody's wallet.
- async def add(self, user, add): Adds money to somebody's wallet.
- async def remove(self, user, take): Removes mon... | Implement the Python class `Wallet` described below.
Class description:
Implement the Wallet class.
Method signatures and docstrings:
- async def get(self, user): Gets the balance of somebody's wallet.
- async def add(self, user, add): Adds money to somebody's wallet.
- async def remove(self, user, take): Removes mon... | 3d075c516124d3a25feebd584fdc351c3abc6613 | <|skeleton|>
class Wallet:
async def get(self, user):
"""Gets the balance of somebody's wallet."""
<|body_0|>
async def add(self, user, add):
"""Adds money to somebody's wallet."""
<|body_1|>
async def remove(self, user, take):
"""Removes money from somebody's wall... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Wallet:
async def get(self, user):
"""Gets the balance of somebody's wallet."""
await data.check(user)
async with aiosqlite.connect('data\\economy.db') as conn:
async with conn.execute('SELECT * from ECONOMY') as cursor:
async for row in cursor:
... | the_stack_v2_python_sparse | core/EcoCore.py | Smudge-Studios/smudge | train | 0 | |
72e365b959c1cd6aec2927d4b10361517de9c055 | [
"self.body = body\nplt.ion()\nplt.clf()\nplt.axes().set_aspect('equal')\nfor wall in body.env.walls:\n (x0, y0), (x1, y1) = wall\n plt.plot([x0, x1], [y0, y1], '-k', linewidth=3)\nfor loc in top.locations:\n x, y = top.locations[loc]\n plt.plot([x], [y], 'k<')\n plt.text(x + 1.0, y + 0.5, loc)\nplt.p... | <|body_start_0|>
self.body = body
plt.ion()
plt.clf()
plt.axes().set_aspect('equal')
for wall in body.env.walls:
(x0, y0), (x1, y1) = wall
plt.plot([x0, x1], [y0, y1], '-k', linewidth=3)
for loc in top.locations:
x, y = top.locations[lo... | Plot_env | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Plot_env:
def __init__(self, body, top):
"""sets up the plot"""
<|body_0|>
def plot_run(self):
"""plots the history after the agent has finished. This is typically only used if body.plotting==False"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sel... | stack_v2_sparse_classes_36k_train_003050 | 3,349 | no_license | [
{
"docstring": "sets up the plot",
"name": "__init__",
"signature": "def __init__(self, body, top)"
},
{
"docstring": "plots the history after the agent has finished. This is typically only used if body.plotting==False",
"name": "plot_run",
"signature": "def plot_run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006400 | Implement the Python class `Plot_env` described below.
Class description:
Implement the Plot_env class.
Method signatures and docstrings:
- def __init__(self, body, top): sets up the plot
- def plot_run(self): plots the history after the agent has finished. This is typically only used if body.plotting==False | Implement the Python class `Plot_env` described below.
Class description:
Implement the Plot_env class.
Method signatures and docstrings:
- def __init__(self, body, top): sets up the plot
- def plot_run(self): plots the history after the agent has finished. This is typically only used if body.plotting==False
<|skele... | 479d6120b75ac0ff602f032474cad440cadd9f31 | <|skeleton|>
class Plot_env:
def __init__(self, body, top):
"""sets up the plot"""
<|body_0|>
def plot_run(self):
"""plots the history after the agent has finished. This is typically only used if body.plotting==False"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Plot_env:
def __init__(self, body, top):
"""sets up the plot"""
self.body = body
plt.ion()
plt.clf()
plt.axes().set_aspect('equal')
for wall in body.env.walls:
(x0, y0), (x1, y1) = wall
plt.plot([x0, x1], [y0, y1], '-k', linewidth=3)
... | the_stack_v2_python_sparse | ass1/aipython/agentTop.py | fckphil/COMP9814 | train | 5 | |
6a13b0b95b8e511cc321bc05d656ae6907875917 | [
"Controller.__init__(self, InfectionView(city))\nself.city = city\nself.infected = False\nself.commands = {}\nself.addCommand(ENDL, self.stopRunning)",
"if not self.infected:\n self.city.infect(1)\n self.infected = True"
] | <|body_start_0|>
Controller.__init__(self, InfectionView(city))
self.city = city
self.infected = False
self.commands = {}
self.addCommand(ENDL, self.stopRunning)
<|end_body_0|>
<|body_start_1|>
if not self.infected:
self.city.infect(1)
self.infect... | Controller for an Infection | InfectionController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InfectionController:
"""Controller for an Infection"""
def __init__(self, city):
"""Initialize the Infection Controller"""
<|body_0|>
def performGameCycle(self):
"""Perform a Game Cycle Event"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Contr... | stack_v2_sparse_classes_36k_train_003051 | 702 | permissive | [
{
"docstring": "Initialize the Infection Controller",
"name": "__init__",
"signature": "def __init__(self, city)"
},
{
"docstring": "Perform a Game Cycle Event",
"name": "performGameCycle",
"signature": "def performGameCycle(self)"
}
] | 2 | null | Implement the Python class `InfectionController` described below.
Class description:
Controller for an Infection
Method signatures and docstrings:
- def __init__(self, city): Initialize the Infection Controller
- def performGameCycle(self): Perform a Game Cycle Event | Implement the Python class `InfectionController` described below.
Class description:
Controller for an Infection
Method signatures and docstrings:
- def __init__(self, city): Initialize the Infection Controller
- def performGameCycle(self): Perform a Game Cycle Event
<|skeleton|>
class InfectionController:
"""Co... | 2a54293181c1c2b1a2b840ddee4d4d80177efb33 | <|skeleton|>
class InfectionController:
"""Controller for an Infection"""
def __init__(self, city):
"""Initialize the Infection Controller"""
<|body_0|>
def performGameCycle(self):
"""Perform a Game Cycle Event"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InfectionController:
"""Controller for an Infection"""
def __init__(self, city):
"""Initialize the Infection Controller"""
Controller.__init__(self, InfectionView(city))
self.city = city
self.infected = False
self.commands = {}
self.addCommand(ENDL, self.st... | the_stack_v2_python_sparse | data/train/python/0e923bb94279b49aa0043dbbf37cfa73c58d0381infection_controller.py | harshp8l/deep-learning-lang-detection | train | 0 |
7dcac48ffa685cf54d1cba6c294fd826b40877fd | [
"if not root:\n return\nself.flatten(root.left)\nself.flatten(root.right)\nif root.left:\n r, l = (root.right, root.left)\n while l.right:\n l = l.right\n l.right = r\n root.right = root.left\n root.left = None",
"if not root:\n return\nself.prev = root\nself.flatten(root.left)\ntemp =... | <|body_start_0|>
if not root:
return
self.flatten(root.left)
self.flatten(root.right)
if root.left:
r, l = (root.right, root.left)
while l.right:
l = l.right
l.right = r
root.right = root.left
root.le... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def flatten(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
<|body_0|>
def flatten(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
... | stack_v2_sparse_classes_36k_train_003052 | 1,354 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.",
"name": "flatten",
"signature": "def flatten(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.",
"name": "flatten",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, root): :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.
- def flatten(self, root): :type root: TreeNode :rtype: void Do n... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, root): :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.
- def flatten(self, root): :type root: TreeNode :rtype: void Do n... | 0e99f9a5226507706b3ee66fd04bae813755ef40 | <|skeleton|>
class Solution:
def flatten(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
<|body_0|>
def flatten(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def flatten(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
if not root:
return
self.flatten(root.left)
self.flatten(root.right)
if root.left:
r, l = (root.right, root.left)
... | the_stack_v2_python_sparse | medium/tree/test_114_Flatten_Binary_Tree_to_Linked_List.py | wuxu1019/leetcode_sophia | train | 1 | |
578619eab8ff1bdb167108415c5f2e1e928e64e8 | [
"if pos_label is not _NoValue:\n raise ValueError('`pos_label` not supported')\nscore = score.atleast_2d()\np = CSoftmax().softmax(score)\nreturn -CArray(p[[list(range(score.shape[0])), y_true.tolist()]]).log()",
"score = score.atleast_2d()\ngrad = CSoftmax().softmax(score)\ngrad[[list(range(score.shape[0])), ... | <|body_start_0|>
if pos_label is not _NoValue:
raise ValueError('`pos_label` not supported')
score = score.atleast_2d()
p = CSoftmax().softmax(score)
return -CArray(p[[list(range(score.shape[0])), y_true.tolist()]]).log()
<|end_body_0|>
<|body_start_1|>
score = score... | Cross Entropy Loss Function (Log Loss). Cross entropy indicates the distance between what the model believes the output distribution should be, and what the original distribution really is. The cross entropy loss is defined as (for sample i): .. math:: L_\\text{cross-entropy} (y, s) = -\\log \\left( \\frac{e^{s_i}}{\\s... | CLossCrossEntropy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CLossCrossEntropy:
"""Cross Entropy Loss Function (Log Loss). Cross entropy indicates the distance between what the model believes the output distribution should be, and what the original distribution really is. The cross entropy loss is defined as (for sample i): .. math:: L_\\text{cross-entropy... | stack_v2_sparse_classes_36k_train_003053 | 3,428 | permissive | [
{
"docstring": "Computes the value of the Cross Entropy loss function. Parameters ---------- y_true : CArray Ground truth (correct), targets. Vector-like array. score : CArray Outputs (predicted), targets. 2-D array of shape (n_samples, n_classes). Returns ------- CArray Loss function. Vector-like array. Notes ... | 2 | stack_v2_sparse_classes_30k_train_010517 | Implement the Python class `CLossCrossEntropy` described below.
Class description:
Cross Entropy Loss Function (Log Loss). Cross entropy indicates the distance between what the model believes the output distribution should be, and what the original distribution really is. The cross entropy loss is defined as (for samp... | Implement the Python class `CLossCrossEntropy` described below.
Class description:
Cross Entropy Loss Function (Log Loss). Cross entropy indicates the distance between what the model believes the output distribution should be, and what the original distribution really is. The cross entropy loss is defined as (for samp... | 431373e65d8cfe2cb7cf042ce1a6c9519ea5a14a | <|skeleton|>
class CLossCrossEntropy:
"""Cross Entropy Loss Function (Log Loss). Cross entropy indicates the distance between what the model believes the output distribution should be, and what the original distribution really is. The cross entropy loss is defined as (for sample i): .. math:: L_\\text{cross-entropy... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CLossCrossEntropy:
"""Cross Entropy Loss Function (Log Loss). Cross entropy indicates the distance between what the model believes the output distribution should be, and what the original distribution really is. The cross entropy loss is defined as (for sample i): .. math:: L_\\text{cross-entropy} (y, s) = -\... | the_stack_v2_python_sparse | src/secml/ml/classifiers/loss/c_loss_cross_entropy.py | Cinofix/secml | train | 0 |
4ae0e4fc4ca383a82ef39e61639100ec27e27c9d | [
"self.entity_id = entity_id\nself.remediation_state = remediation_state\nself.root_inode_id = root_inode_id\nself.view_id = view_id",
"if dictionary is None:\n return None\nentity_id = dictionary.get('entityId')\nremediation_state = dictionary.get('remediationState')\nroot_inode_id = dictionary.get('rootInodeI... | <|body_start_0|>
self.entity_id = entity_id
self.remediation_state = remediation_state
self.root_inode_id = root_inode_id
self.view_id = view_id
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
entity_id = dictionary.get('entityId')
... | Implementation of the 'InfectedFileParam' model. TODO: type description here. Attributes: entity_id (long|int): Specifies the entity id of the infected file. remediation_state (RemediationStateEnum): Specifies the remediation state of the file. Remediation State. 'kQuarantine' indicates 'Quarantine' state of the file. ... | InfectedFileParam | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InfectedFileParam:
"""Implementation of the 'InfectedFileParam' model. TODO: type description here. Attributes: entity_id (long|int): Specifies the entity id of the infected file. remediation_state (RemediationStateEnum): Specifies the remediation state of the file. Remediation State. 'kQuarantin... | stack_v2_sparse_classes_36k_train_003054 | 2,750 | permissive | [
{
"docstring": "Constructor for the InfectedFileParam class",
"name": "__init__",
"signature": "def __init__(self, entity_id=None, remediation_state=None, root_inode_id=None, view_id=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A di... | 2 | null | Implement the Python class `InfectedFileParam` described below.
Class description:
Implementation of the 'InfectedFileParam' model. TODO: type description here. Attributes: entity_id (long|int): Specifies the entity id of the infected file. remediation_state (RemediationStateEnum): Specifies the remediation state of t... | Implement the Python class `InfectedFileParam` described below.
Class description:
Implementation of the 'InfectedFileParam' model. TODO: type description here. Attributes: entity_id (long|int): Specifies the entity id of the infected file. remediation_state (RemediationStateEnum): Specifies the remediation state of t... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class InfectedFileParam:
"""Implementation of the 'InfectedFileParam' model. TODO: type description here. Attributes: entity_id (long|int): Specifies the entity id of the infected file. remediation_state (RemediationStateEnum): Specifies the remediation state of the file. Remediation State. 'kQuarantin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InfectedFileParam:
"""Implementation of the 'InfectedFileParam' model. TODO: type description here. Attributes: entity_id (long|int): Specifies the entity id of the infected file. remediation_state (RemediationStateEnum): Specifies the remediation state of the file. Remediation State. 'kQuarantine' indicates ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/infected_file_param.py | cohesity/management-sdk-python | train | 24 |
a45746e7aad9986e913794ba933c4b344595fc6b | [
"handshake_protocols = data.get('handshake_protocols')\nrequests_attach = data.get('requests_attach')\nif not handshake_protocols and (not requests_attach):\n raise ValidationError('Model must include non-empty handshake_protocols or requests~attach or both')\ngoal = data.get('goal')\ngoal_code = data.get('goal_... | <|body_start_0|>
handshake_protocols = data.get('handshake_protocols')
requests_attach = data.get('requests_attach')
if not handshake_protocols and (not requests_attach):
raise ValidationError('Model must include non-empty handshake_protocols or requests~attach or both')
goal... | InvitationMessage schema. | InvitationMessageSchema | [
"LicenseRef-scancode-dco-1.1",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InvitationMessageSchema:
"""InvitationMessage schema."""
def validate_fields(self, data, **kwargs):
"""Validate schema fields. Args: data: The data to validate Raises: ValidationError: If any of the fields do not validate"""
<|body_0|>
def post_dump(self, data, **kwargs)... | stack_v2_sparse_classes_36k_train_003055 | 10,410 | permissive | [
{
"docstring": "Validate schema fields. Args: data: The data to validate Raises: ValidationError: If any of the fields do not validate",
"name": "validate_fields",
"signature": "def validate_fields(self, data, **kwargs)"
},
{
"docstring": "Post dump hook.",
"name": "post_dump",
"signatur... | 2 | null | Implement the Python class `InvitationMessageSchema` described below.
Class description:
InvitationMessage schema.
Method signatures and docstrings:
- def validate_fields(self, data, **kwargs): Validate schema fields. Args: data: The data to validate Raises: ValidationError: If any of the fields do not validate
- def... | Implement the Python class `InvitationMessageSchema` described below.
Class description:
InvitationMessage schema.
Method signatures and docstrings:
- def validate_fields(self, data, **kwargs): Validate schema fields. Args: data: The data to validate Raises: ValidationError: If any of the fields do not validate
- def... | 39cac36d8937ce84a9307ce100aaefb8bc05ec04 | <|skeleton|>
class InvitationMessageSchema:
"""InvitationMessage schema."""
def validate_fields(self, data, **kwargs):
"""Validate schema fields. Args: data: The data to validate Raises: ValidationError: If any of the fields do not validate"""
<|body_0|>
def post_dump(self, data, **kwargs)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InvitationMessageSchema:
"""InvitationMessage schema."""
def validate_fields(self, data, **kwargs):
"""Validate schema fields. Args: data: The data to validate Raises: ValidationError: If any of the fields do not validate"""
handshake_protocols = data.get('handshake_protocols')
re... | the_stack_v2_python_sparse | aries_cloudagent/protocols/out_of_band/v1_0/messages/invitation.py | hyperledger/aries-cloudagent-python | train | 370 |
b4d5db81e7499e35850d69122b3e50f7f8f8e582 | [
"super(FunctionComponent, self).__init__(opts)\nself.opts = opts\nself.options = opts.get(FunctionComponent.SECTION_HDR, {})\nself.init_function()",
"self.opts = opts\nself.options = opts.get(FunctionComponent.SECTION_HDR, {})\nself.init_function()",
"self.template_dir = self.options.get('template_dir')\nif sel... | <|body_start_0|>
super(FunctionComponent, self).__init__(opts)
self.opts = opts
self.options = opts.get(FunctionComponent.SECTION_HDR, {})
self.init_function()
<|end_body_0|>
<|body_start_1|>
self.opts = opts
self.options = opts.get(FunctionComponent.SECTION_HDR, {})
... | Component that implements Resilient function 'fn-netdevice | FunctionComponent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FunctionComponent:
"""Component that implements Resilient function 'fn-netdevice"""
def __init__(self, opts):
"""constructor provides access to the configuration options"""
<|body_0|>
def _reload(self, event, opts):
"""Configuration options have changed, save new... | stack_v2_sparse_classes_36k_train_003056 | 5,616 | permissive | [
{
"docstring": "constructor provides access to the configuration options",
"name": "__init__",
"signature": "def __init__(self, opts)"
},
{
"docstring": "Configuration options have changed, save new values",
"name": "_reload",
"signature": "def _reload(self, event, opts)"
},
{
"d... | 6 | stack_v2_sparse_classes_30k_train_018995 | Implement the Python class `FunctionComponent` described below.
Class description:
Component that implements Resilient function 'fn-netdevice
Method signatures and docstrings:
- def __init__(self, opts): constructor provides access to the configuration options
- def _reload(self, event, opts): Configuration options h... | Implement the Python class `FunctionComponent` described below.
Class description:
Component that implements Resilient function 'fn-netdevice
Method signatures and docstrings:
- def __init__(self, opts): constructor provides access to the configuration options
- def _reload(self, event, opts): Configuration options h... | 6878c78b94eeca407998a41ce8db2cc00f2b6758 | <|skeleton|>
class FunctionComponent:
"""Component that implements Resilient function 'fn-netdevice"""
def __init__(self, opts):
"""constructor provides access to the configuration options"""
<|body_0|>
def _reload(self, event, opts):
"""Configuration options have changed, save new... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FunctionComponent:
"""Component that implements Resilient function 'fn-netdevice"""
def __init__(self, opts):
"""constructor provides access to the configuration options"""
super(FunctionComponent, self).__init__(opts)
self.opts = opts
self.options = opts.get(FunctionCompo... | the_stack_v2_python_sparse | fn_netdevice/fn_netdevice/components/network_device.py | ibmresilient/resilient-community-apps | train | 81 |
2dab49d929719f3f3a35cc9a0529ca4f9b4b24c8 | [
"s = CustomerSubmitApplicationSerializer(data=request.data)\ns.is_valid(raise_exception=True)\npay_from = s.validated_data['pay_from']\nname = s.validated_data['name']\ntel = s.validated_data['tel']\nid_number = s.validated_data['id_number']\nid_card_back = s.validated_data.get('id_card_back')\nid_card_front = s.va... | <|body_start_0|>
s = CustomerSubmitApplicationSerializer(data=request.data)
s.is_valid(raise_exception=True)
pay_from = s.validated_data['pay_from']
name = s.validated_data['name']
tel = s.validated_data['tel']
id_number = s.validated_data['id_number']
id_card_bac... | CustomerSubjectermViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomerSubjectermViewSet:
def create_alipay_order(self, request, pk=None):
"""提交报名"""
<|body_0|>
def create_wechat_order(self, request, pk=None):
"""提交报名"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
s = CustomerSubmitApplicationSerializer(data=r... | stack_v2_sparse_classes_36k_train_003057 | 11,615 | no_license | [
{
"docstring": "提交报名",
"name": "create_alipay_order",
"signature": "def create_alipay_order(self, request, pk=None)"
},
{
"docstring": "提交报名",
"name": "create_wechat_order",
"signature": "def create_wechat_order(self, request, pk=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002586 | Implement the Python class `CustomerSubjectermViewSet` described below.
Class description:
Implement the CustomerSubjectermViewSet class.
Method signatures and docstrings:
- def create_alipay_order(self, request, pk=None): 提交报名
- def create_wechat_order(self, request, pk=None): 提交报名 | Implement the Python class `CustomerSubjectermViewSet` described below.
Class description:
Implement the CustomerSubjectermViewSet class.
Method signatures and docstrings:
- def create_alipay_order(self, request, pk=None): 提交报名
- def create_wechat_order(self, request, pk=None): 提交报名
<|skeleton|>
class CustomerSubjec... | 53cda7937ff628538ecfcee1edf8d9ef03edee81 | <|skeleton|>
class CustomerSubjectermViewSet:
def create_alipay_order(self, request, pk=None):
"""提交报名"""
<|body_0|>
def create_wechat_order(self, request, pk=None):
"""提交报名"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomerSubjectermViewSet:
def create_alipay_order(self, request, pk=None):
"""提交报名"""
s = CustomerSubmitApplicationSerializer(data=request.data)
s.is_valid(raise_exception=True)
pay_from = s.validated_data['pay_from']
name = s.validated_data['name']
tel = s.val... | the_stack_v2_python_sparse | apps/customer/subjects/viewsets.py | largerbigsuper/Building_Knowledge_Stack | train | 0 | |
b5cae01d58f20dfdd517a65108bfb0ebdcdbf196 | [
"super(_LocalState, self).__init__()\nif channels % heads != 0:\n raise ValueError('Channels must be divisible by heads.')\nself.heads = heads\nself.ndecay = ndecay\nself.content = nn.Conv1d(channels, channels, 1)\nself.query = nn.Conv1d(channels, channels, 1)\nself.key = nn.Conv1d(channels, channels, 1)\nself.q... | <|body_start_0|>
super(_LocalState, self).__init__()
if channels % heads != 0:
raise ValueError('Channels must be divisible by heads.')
self.heads = heads
self.ndecay = ndecay
self.content = nn.Conv1d(channels, channels, 1)
self.query = nn.Conv1d(channels, cha... | Local state allows to have attention based only on data (no positional embedding), but while setting a constraint on the time window (e.g. decaying penalty term). Also a failed experiments with trying to provide some frequency based attention. | _LocalState | [
"CC-BY-NC-4.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _LocalState:
"""Local state allows to have attention based only on data (no positional embedding), but while setting a constraint on the time window (e.g. decaying penalty term). Also a failed experiments with trying to provide some frequency based attention."""
def __init__(self, channels: ... | stack_v2_sparse_classes_36k_train_003058 | 38,242 | permissive | [
{
"docstring": "Args: channels (int): Size of Conv1d layers. heads (int, optional): (default: 4) ndecay (int, optional): (default: 4)",
"name": "__init__",
"signature": "def __init__(self, channels: int, heads: int=4, ndecay: int=4)"
},
{
"docstring": "LocalState forward call Args: x (torch.Tens... | 2 | stack_v2_sparse_classes_30k_train_013107 | Implement the Python class `_LocalState` described below.
Class description:
Local state allows to have attention based only on data (no positional embedding), but while setting a constraint on the time window (e.g. decaying penalty term). Also a failed experiments with trying to provide some frequency based attention... | Implement the Python class `_LocalState` described below.
Class description:
Local state allows to have attention based only on data (no positional embedding), but while setting a constraint on the time window (e.g. decaying penalty term). Also a failed experiments with trying to provide some frequency based attention... | e057d7d144e2716588b80255f0a143662fd5c10d | <|skeleton|>
class _LocalState:
"""Local state allows to have attention based only on data (no positional embedding), but while setting a constraint on the time window (e.g. decaying penalty term). Also a failed experiments with trying to provide some frequency based attention."""
def __init__(self, channels: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _LocalState:
"""Local state allows to have attention based only on data (no positional embedding), but while setting a constraint on the time window (e.g. decaying penalty term). Also a failed experiments with trying to provide some frequency based attention."""
def __init__(self, channels: int, heads: i... | the_stack_v2_python_sparse | torchaudio/models/_hdemucs.py | pytorch/audio | train | 2,319 |
a9085eaf7a446c54f2a7226b5c8e7ae9a6661930 | [
"super(PositionalEncoding, self).__init__()\nself.d_model = d_model\nself.reverse = reverse\nself.xscale = math.sqrt(self.d_model)\nself.dropout = torch.nn.Dropout(p=dropout_rate)\nself.pe = None\nself.extend_pe(torch.tensor(0.0).expand(1, max_len))\nself._register_load_state_dict_pre_hook(_pre_hook)",
"if self.p... | <|body_start_0|>
super(PositionalEncoding, self).__init__()
self.d_model = d_model
self.reverse = reverse
self.xscale = math.sqrt(self.d_model)
self.dropout = torch.nn.Dropout(p=dropout_rate)
self.pe = None
self.extend_pe(torch.tensor(0.0).expand(1, max_len))
... | Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. reverse (bool): Whether to reverse the input position. Only for the class LegacyRelPositionalEncoding. We remove it in the current class RelPositionalEncoding. | PositionalEncoding | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PositionalEncoding:
"""Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. reverse (bool): Whether to reverse the input position. Only for the class LegacyRelPositionalEncoding. We remove it in the current class R... | stack_v2_sparse_classes_36k_train_003059 | 12,758 | permissive | [
{
"docstring": "Construct an PositionalEncoding object.",
"name": "__init__",
"signature": "def __init__(self, d_model, dropout_rate, max_len=5000, reverse=False)"
},
{
"docstring": "Reset the positional encodings.",
"name": "extend_pe",
"signature": "def extend_pe(self, x)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_010615 | Implement the Python class `PositionalEncoding` described below.
Class description:
Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. reverse (bool): Whether to reverse the input position. Only for the class LegacyRelPositionalEncodi... | Implement the Python class `PositionalEncoding` described below.
Class description:
Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. reverse (bool): Whether to reverse the input position. Only for the class LegacyRelPositionalEncodi... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class PositionalEncoding:
"""Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. reverse (bool): Whether to reverse the input position. Only for the class LegacyRelPositionalEncoding. We remove it in the current class R... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PositionalEncoding:
"""Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. reverse (bool): Whether to reverse the input position. Only for the class LegacyRelPositionalEncoding. We remove it in the current class RelPositionalE... | the_stack_v2_python_sparse | espnet/nets/pytorch_backend/transformer/embedding.py | espnet/espnet | train | 7,242 |
2b30cece252111bb7609189bb915f13d8cac5477 | [
"from_match = helper.must_one(Session().query(Match).filter(Match.id == request.json.get('match_id')))\nhelper.must_mine(g.user_session.user, from_match, foreign_value=from_match.to_user_id)\nto_match = Session().query(Match).filter((Match.from_user_id == g.user_session.user.id) & (Match.to_user_id == request.json.... | <|body_start_0|>
from_match = helper.must_one(Session().query(Match).filter(Match.id == request.json.get('match_id')))
helper.must_mine(g.user_session.user, from_match, foreign_value=from_match.to_user_id)
to_match = Session().query(Match).filter((Match.from_user_id == g.user_session.user.id) & ... | HeartPrerequisites | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HeartPrerequisites:
def heart(self):
"""heart 를 보낼 만큼의 포인트를 갖고 있는지 확인합니다."""
<|body_0|>
def accept(self):
"""자기한테 온 하트가 맞는지 체크합니다. 더블 하트라면 지나갑니다. 만약 일반 하트라면 accept 하는 유저가 포인트를 갖고 있는지 체크합니다."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from_match ... | stack_v2_sparse_classes_36k_train_003060 | 2,042 | no_license | [
{
"docstring": "heart 를 보낼 만큼의 포인트를 갖고 있는지 확인합니다.",
"name": "heart",
"signature": "def heart(self)"
},
{
"docstring": "자기한테 온 하트가 맞는지 체크합니다. 더블 하트라면 지나갑니다. 만약 일반 하트라면 accept 하는 유저가 포인트를 갖고 있는지 체크합니다.",
"name": "accept",
"signature": "def accept(self)"
}
] | 2 | null | Implement the Python class `HeartPrerequisites` described below.
Class description:
Implement the HeartPrerequisites class.
Method signatures and docstrings:
- def heart(self): heart 를 보낼 만큼의 포인트를 갖고 있는지 확인합니다.
- def accept(self): 자기한테 온 하트가 맞는지 체크합니다. 더블 하트라면 지나갑니다. 만약 일반 하트라면 accept 하는 유저가 포인트를 갖고 있는지 체크합니다. | Implement the Python class `HeartPrerequisites` described below.
Class description:
Implement the HeartPrerequisites class.
Method signatures and docstrings:
- def heart(self): heart 를 보낼 만큼의 포인트를 갖고 있는지 확인합니다.
- def accept(self): 자기한테 온 하트가 맞는지 체크합니다. 더블 하트라면 지나갑니다. 만약 일반 하트라면 accept 하는 유저가 포인트를 갖고 있는지 체크합니다.
<|ske... | e143b525e6e495e5cfe9f0b40c154d0c28cea3c5 | <|skeleton|>
class HeartPrerequisites:
def heart(self):
"""heart 를 보낼 만큼의 포인트를 갖고 있는지 확인합니다."""
<|body_0|>
def accept(self):
"""자기한테 온 하트가 맞는지 체크합니다. 더블 하트라면 지나갑니다. 만약 일반 하트라면 accept 하는 유저가 포인트를 갖고 있는지 체크합니다."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HeartPrerequisites:
def heart(self):
"""heart 를 보낼 만큼의 포인트를 갖고 있는지 확인합니다."""
from_match = helper.must_one(Session().query(Match).filter(Match.id == request.json.get('match_id')))
helper.must_mine(g.user_session.user, from_match, foreign_value=from_match.to_user_id)
to_match = S... | the_stack_v2_python_sparse | api/models/prerequisites/heart_prerequisites.py | wow-woo/LabS | train | 0 | |
9fa382ea5c91e94bfce3b32a402049b790148741 | [
"size, header = FormatSMVADSCSN.get_smv_header(image_file)\nif int(header['DETECTOR_SN']) not in [926, 907]:\n return False\nreturn True",
"distance = float(self._header_dictionary['DISTANCE'])\nif 'DENZO_X_BEAM' in self._header_dictionary:\n beam_x = float(self._header_dictionary['DENZO_X_BEAM'])\n beam... | <|body_start_0|>
size, header = FormatSMVADSCSN.get_smv_header(image_file)
if int(header['DETECTOR_SN']) not in [926, 907]:
return False
return True
<|end_body_0|>
<|body_start_1|>
distance = float(self._header_dictionary['DISTANCE'])
if 'DENZO_X_BEAM' in self._heade... | A class for reading SMV format ADSC images, and correctly constructing a model for the experiment from this, for instrument number 926. | FormatSMVADSCSN926 | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FormatSMVADSCSN926:
"""A class for reading SMV format ADSC images, and correctly constructing a model for the experiment from this, for instrument number 926."""
def understand(image_file):
"""Check to see if this is ADSC SN 926."""
<|body_0|>
def _detector(self):
... | stack_v2_sparse_classes_36k_train_003061 | 2,464 | permissive | [
{
"docstring": "Check to see if this is ADSC SN 926.",
"name": "understand",
"signature": "def understand(image_file)"
},
{
"docstring": "Return a model for a simple detector, allowing for the installation on on a two-theta stage. Assert that the beam centre is provided in the Mosflm coordinate ... | 2 | stack_v2_sparse_classes_30k_train_004016 | Implement the Python class `FormatSMVADSCSN926` described below.
Class description:
A class for reading SMV format ADSC images, and correctly constructing a model for the experiment from this, for instrument number 926.
Method signatures and docstrings:
- def understand(image_file): Check to see if this is ADSC SN 92... | Implement the Python class `FormatSMVADSCSN926` described below.
Class description:
A class for reading SMV format ADSC images, and correctly constructing a model for the experiment from this, for instrument number 926.
Method signatures and docstrings:
- def understand(image_file): Check to see if this is ADSC SN 92... | 2fc8ffadbf67d0611e2d7affcf50d0f23abfc16f | <|skeleton|>
class FormatSMVADSCSN926:
"""A class for reading SMV format ADSC images, and correctly constructing a model for the experiment from this, for instrument number 926."""
def understand(image_file):
"""Check to see if this is ADSC SN 926."""
<|body_0|>
def _detector(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FormatSMVADSCSN926:
"""A class for reading SMV format ADSC images, and correctly constructing a model for the experiment from this, for instrument number 926."""
def understand(image_file):
"""Check to see if this is ADSC SN 926."""
size, header = FormatSMVADSCSN.get_smv_header(image_file... | the_stack_v2_python_sparse | src/dxtbx/format/FormatSMVADSCSN926.py | cctbx/dxtbx | train | 2 |
403a758b75638730e19b3da7d8e0eb82d5de0a6c | [
"super().__init__(name, X, metadata)\nself.name = name\nself.X = X\nself.metadata = metadata",
"conditions = []\nif not hasattr(processed_cycler_run, 'diagnostic_summary') & hasattr(processed_cycler_run, 'diagnostic_data'):\n return False\nif processed_cycler_run.diagnostic_summary is None:\n return False\n... | <|body_start_0|>
super().__init__(name, X, metadata)
self.name = name
self.X = X
self.metadata = metadata
<|end_body_0|>
<|body_start_1|>
conditions = []
if not hasattr(processed_cycler_run, 'diagnostic_summary') & hasattr(processed_cycler_run, 'diagnostic_data'):
... | Object corresponding to the fitted material parameters of the cell. Material parameters are determined by using high resolution half cell data to fit full cell dQdV curves. Rows of the output dataframe correspond to each of the diagnostics throughout the life of the cell. name (str): predictor object name. X (pandas.Da... | IntracellCycles | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IntracellCycles:
"""Object corresponding to the fitted material parameters of the cell. Material parameters are determined by using high resolution half cell data to fit full cell dQdV curves. Rows of the output dataframe correspond to each of the diagnostics throughout the life of the cell. name... | stack_v2_sparse_classes_36k_train_003062 | 10,932 | permissive | [
{
"docstring": "Args: name (str): predictor object name X (pandas.DataFrame): features in DataFrame format. metadata (dict): information about the data and code used to produce features",
"name": "__init__",
"signature": "def __init__(self, name, X, metadata)"
},
{
"docstring": "This function de... | 3 | stack_v2_sparse_classes_30k_train_014803 | Implement the Python class `IntracellCycles` described below.
Class description:
Object corresponding to the fitted material parameters of the cell. Material parameters are determined by using high resolution half cell data to fit full cell dQdV curves. Rows of the output dataframe correspond to each of the diagnostic... | Implement the Python class `IntracellCycles` described below.
Class description:
Object corresponding to the fitted material parameters of the cell. Material parameters are determined by using high resolution half cell data to fit full cell dQdV curves. Rows of the output dataframe correspond to each of the diagnostic... | 39c4cb952294d3e5ebcd2c85877d538f50d91979 | <|skeleton|>
class IntracellCycles:
"""Object corresponding to the fitted material parameters of the cell. Material parameters are determined by using high resolution half cell data to fit full cell dQdV curves. Rows of the output dataframe correspond to each of the diagnostics throughout the life of the cell. name... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IntracellCycles:
"""Object corresponding to the fitted material parameters of the cell. Material parameters are determined by using high resolution half cell data to fit full cell dQdV curves. Rows of the output dataframe correspond to each of the diagnostics throughout the life of the cell. name (str): predi... | the_stack_v2_python_sparse | beep/features/intracell_losses.py | lewis2222/beep | train | 1 |
81454b4a8dcaea6b30d6e1f646b26530d975409c | [
"if not isinstance(block_string, str):\n raise AssertionError\nops = block_string.split('_')\noptions = {}\nfor op in ops:\n splits = re.split('(\\\\d.*)', op)\n if len(splits) >= 2:\n key, value = splits[:2]\n options[key] = value\nif 's' not in options or len(options['s']) != 2:\n raise ... | <|body_start_0|>
if not isinstance(block_string, str):
raise AssertionError
ops = block_string.split('_')
options = {}
for op in ops:
splits = re.split('(\\d.*)', op)
if len(splits) >= 2:
key, value = splits[:2]
options[... | A class of Mixnet decoder to get model configuration. | MixnetDecoder | [
"MIT",
"Apache-2.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MixnetDecoder:
"""A class of Mixnet decoder to get model configuration."""
def _decode_block_string(block_string, depth_multiplier, depth_divisor, min_depth):
"""Gets a mixnet block through a string notation of arguments. E.g. r2_k3_a1_p1_s2_e1_i32_o16_se0.25_noskip: r - number of re... | stack_v2_sparse_classes_36k_train_003063 | 5,148 | permissive | [
{
"docstring": "Gets a mixnet block through a string notation of arguments. E.g. r2_k3_a1_p1_s2_e1_i32_o16_se0.25_noskip: r - number of repeat blocks, k - kernel size, s - strides (1-9), e - expansion ratio, i - input filters, o - output filters, se - squeeze/excitation ratio Args: block_string: a string, a str... | 4 | stack_v2_sparse_classes_30k_train_003893 | Implement the Python class `MixnetDecoder` described below.
Class description:
A class of Mixnet decoder to get model configuration.
Method signatures and docstrings:
- def _decode_block_string(block_string, depth_multiplier, depth_divisor, min_depth): Gets a mixnet block through a string notation of arguments. E.g. ... | Implement the Python class `MixnetDecoder` described below.
Class description:
A class of Mixnet decoder to get model configuration.
Method signatures and docstrings:
- def _decode_block_string(block_string, depth_multiplier, depth_divisor, min_depth): Gets a mixnet block through a string notation of arguments. E.g. ... | 9d663faf0c1660a9b8359a6472c164f658dfc8cb | <|skeleton|>
class MixnetDecoder:
"""A class of Mixnet decoder to get model configuration."""
def _decode_block_string(block_string, depth_multiplier, depth_divisor, min_depth):
"""Gets a mixnet block through a string notation of arguments. E.g. r2_k3_a1_p1_s2_e1_i32_o16_se0.25_noskip: r - number of re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MixnetDecoder:
"""A class of Mixnet decoder to get model configuration."""
def _decode_block_string(block_string, depth_multiplier, depth_divisor, min_depth):
"""Gets a mixnet block through a string notation of arguments. E.g. r2_k3_a1_p1_s2_e1_i32_o16_se0.25_noskip: r - number of repeat blocks, ... | the_stack_v2_python_sparse | pywick/models/segmentation/testnets/mixnet/utils.py | csetraynor/pywick | train | 0 |
59669381cf33dc4150379ce3d0f1ae965de6a94e | [
"self.max = int(max)\nself.granularity = timedelta(0, granularity)\nself.current = 0\nself.start = self.printed = datetime.utcnow()",
"percent = 100 * int(val) / self.max\nif percent > self.current:\n self.current = percent\n self.delta = datetime.utcnow() - self.start\n self.estimate = timedelta(0, 100 ... | <|body_start_0|>
self.max = int(max)
self.granularity = timedelta(0, granularity)
self.current = 0
self.start = self.printed = datetime.utcnow()
<|end_body_0|>
<|body_start_1|>
percent = 100 * int(val) / self.max
if percent > self.current:
self.current = perc... | When you are processing a long iterable and it takes minutes, you should let the user know that your application is still working. This class helps do that in the console, without creating too much output. | PercentageDone | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PercentageDone:
"""When you are processing a long iterable and it takes minutes, you should let the user know that your application is still working. This class helps do that in the console, without creating too much output."""
def __init__(self, max, granularity=6):
"""Parameters: *... | stack_v2_sparse_classes_36k_train_003064 | 5,416 | permissive | [
{
"docstring": "Parameters: *max*: The number of elements that shall be processed. *granularity*: how many seconds must elapse between printing the percentage done.",
"name": "__init__",
"signature": "def __init__(self, max, granularity=6)"
},
{
"docstring": "Takes *val* (the current position re... | 3 | stack_v2_sparse_classes_30k_train_017399 | Implement the Python class `PercentageDone` described below.
Class description:
When you are processing a long iterable and it takes minutes, you should let the user know that your application is still working. This class helps do that in the console, without creating too much output.
Method signatures and docstrings... | Implement the Python class `PercentageDone` described below.
Class description:
When you are processing a long iterable and it takes minutes, you should let the user know that your application is still working. This class helps do that in the console, without creating too much output.
Method signatures and docstrings... | 63f6fbd3e768bf55d79ac96964aa3bf7702f3f9a | <|skeleton|>
class PercentageDone:
"""When you are processing a long iterable and it takes minutes, you should let the user know that your application is still working. This class helps do that in the console, without creating too much output."""
def __init__(self, max, granularity=6):
"""Parameters: *... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PercentageDone:
"""When you are processing a long iterable and it takes minutes, you should let the user know that your application is still working. This class helps do that in the console, without creating too much output."""
def __init__(self, max, granularity=6):
"""Parameters: *max*: The num... | the_stack_v2_python_sparse | bag/show_progress.py | nandoflorestan/bag | train | 24 |
c3788eac779b7e955fed4daabb6a7292e4018e5c | [
"super().__init__(fibaro_device)\nself.entity_description = entity_description\nself.entity_id = ENTITY_ID_FORMAT.format(f'{self.ha_id}_{entity_description.key}')\nself._attr_name = f'{fibaro_device.friendly_name} {entity_description.name}'\nself._attr_unique_id = f'{fibaro_device.unique_id_str}_{entity_description... | <|body_start_0|>
super().__init__(fibaro_device)
self.entity_description = entity_description
self.entity_id = ENTITY_ID_FORMAT.format(f'{self.ha_id}_{entity_description.key}')
self._attr_name = f'{fibaro_device.friendly_name} {entity_description.name}'
self._attr_unique_id = f'{... | Representation of a Fibaro Additional Sensor. | FibaroAdditionalSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FibaroAdditionalSensor:
"""Representation of a Fibaro Additional Sensor."""
def __init__(self, fibaro_device: DeviceModel, entity_description: SensorEntityDescription) -> None:
"""Initialize the sensor."""
<|body_0|>
def update(self) -> None:
"""Update the state.... | stack_v2_sparse_classes_36k_train_003065 | 6,253 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, fibaro_device: DeviceModel, entity_description: SensorEntityDescription) -> None"
},
{
"docstring": "Update the state.",
"name": "update",
"signature": "def update(self) -> None"
}
] | 2 | null | Implement the Python class `FibaroAdditionalSensor` described below.
Class description:
Representation of a Fibaro Additional Sensor.
Method signatures and docstrings:
- def __init__(self, fibaro_device: DeviceModel, entity_description: SensorEntityDescription) -> None: Initialize the sensor.
- def update(self) -> No... | Implement the Python class `FibaroAdditionalSensor` described below.
Class description:
Representation of a Fibaro Additional Sensor.
Method signatures and docstrings:
- def __init__(self, fibaro_device: DeviceModel, entity_description: SensorEntityDescription) -> None: Initialize the sensor.
- def update(self) -> No... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class FibaroAdditionalSensor:
"""Representation of a Fibaro Additional Sensor."""
def __init__(self, fibaro_device: DeviceModel, entity_description: SensorEntityDescription) -> None:
"""Initialize the sensor."""
<|body_0|>
def update(self) -> None:
"""Update the state.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FibaroAdditionalSensor:
"""Representation of a Fibaro Additional Sensor."""
def __init__(self, fibaro_device: DeviceModel, entity_description: SensorEntityDescription) -> None:
"""Initialize the sensor."""
super().__init__(fibaro_device)
self.entity_description = entity_descriptio... | the_stack_v2_python_sparse | homeassistant/components/fibaro/sensor.py | home-assistant/core | train | 35,501 |
31f0a64d83123fb73705b02f5c6d8c2aa113a732 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn WorkingHours()",
"from .day_of_week import DayOfWeek\nfrom .time_zone_base import TimeZoneBase\nfrom .day_of_week import DayOfWeek\nfrom .time_zone_base import TimeZoneBase\nfields: Dict[str, Callable[[Any], None]] = {'daysOfWeek': lam... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return WorkingHours()
<|end_body_0|>
<|body_start_1|>
from .day_of_week import DayOfWeek
from .time_zone_base import TimeZoneBase
from .day_of_week import DayOfWeek
from .time_z... | WorkingHours | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkingHours:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WorkingHours:
"""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: ... | stack_v2_sparse_classes_36k_train_003066 | 3,572 | 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: WorkingHours",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(... | 3 | stack_v2_sparse_classes_30k_val_000398 | Implement the Python class `WorkingHours` described below.
Class description:
Implement the WorkingHours class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WorkingHours: Creates a new instance of the appropriate class based on discriminator value Ar... | Implement the Python class `WorkingHours` described below.
Class description:
Implement the WorkingHours class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WorkingHours: Creates a new instance of the appropriate class based on discriminator value Ar... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class WorkingHours:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WorkingHours:
"""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: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkingHours:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WorkingHours:
"""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: WorkingHours""... | the_stack_v2_python_sparse | msgraph/generated/models/working_hours.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
389b925eaf10f64c913a9b22c06b1bac77b01162 | [
"SimpleXMLRPCDispatcher.__init__(self, allow_none=True, encoding=encoding)\nself.register_introspection_functions()\nself._dispatch_method = dispatch_method",
"try:\n return self.funcs[name](*params)\nexcept KeyError:\n pass\nreturn self._dispatch_method(name, params)",
"data = to_str(request.read_data())... | <|body_start_0|>
SimpleXMLRPCDispatcher.__init__(self, allow_none=True, encoding=encoding)
self.register_introspection_functions()
self._dispatch_method = dispatch_method
<|end_body_0|>
<|body_start_1|>
try:
return self.funcs[name](*params)
except KeyError:
... | A XML-RPC servlet that can be registered in the Pelix HTTP service Calls the dispatch method given in the constructor | _XmlRpcServlet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _XmlRpcServlet:
"""A XML-RPC servlet that can be registered in the Pelix HTTP service Calls the dispatch method given in the constructor"""
def __init__(self, dispatch_method, encoding=None):
"""Sets up the servlet"""
<|body_0|>
def _simple_dispatch(self, name, params):
... | stack_v2_sparse_classes_36k_train_003067 | 8,341 | permissive | [
{
"docstring": "Sets up the servlet",
"name": "__init__",
"signature": "def __init__(self, dispatch_method, encoding=None)"
},
{
"docstring": "Dispatch method",
"name": "_simple_dispatch",
"signature": "def _simple_dispatch(self, name, params)"
},
{
"docstring": "Handles a HTTP P... | 3 | stack_v2_sparse_classes_30k_train_014166 | Implement the Python class `_XmlRpcServlet` described below.
Class description:
A XML-RPC servlet that can be registered in the Pelix HTTP service Calls the dispatch method given in the constructor
Method signatures and docstrings:
- def __init__(self, dispatch_method, encoding=None): Sets up the servlet
- def _simpl... | Implement the Python class `_XmlRpcServlet` described below.
Class description:
A XML-RPC servlet that can be registered in the Pelix HTTP service Calls the dispatch method given in the constructor
Method signatures and docstrings:
- def __init__(self, dispatch_method, encoding=None): Sets up the servlet
- def _simpl... | 1d0add361ca219da8fdf72bb9ba8cb0ade01ad2f | <|skeleton|>
class _XmlRpcServlet:
"""A XML-RPC servlet that can be registered in the Pelix HTTP service Calls the dispatch method given in the constructor"""
def __init__(self, dispatch_method, encoding=None):
"""Sets up the servlet"""
<|body_0|>
def _simple_dispatch(self, name, params):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _XmlRpcServlet:
"""A XML-RPC servlet that can be registered in the Pelix HTTP service Calls the dispatch method given in the constructor"""
def __init__(self, dispatch_method, encoding=None):
"""Sets up the servlet"""
SimpleXMLRPCDispatcher.__init__(self, allow_none=True, encoding=encodin... | the_stack_v2_python_sparse | pelix/remote/xml_rpc.py | tcalmant/ipopo | train | 67 |
b21c7ee555b17ae75be20315142879e3195f61b5 | [
"self.kode_field = kode_field\nself.beskrivelse_field = beskrivelse_field\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\nkode_field = dictionary.get('kodeField')\nbeskrivelse_field = dictionary.get('beskrivelseField')\nfor key in cls._names.values():\n if key in... | <|body_start_0|>
self.kode_field = kode_field
self.beskrivelse_field = beskrivelse_field
self.additional_properties = additional_properties
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
kode_field = dictionary.get('kodeField')
beskrivelse... | Implementation of the 'Person.DisponibelInntekt' model. TODO: type model description here. Attributes: kode_field (int): TODO: type description here. beskrivelse_field (string): TODO: type description here. | PersonDisponibelInntekt | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PersonDisponibelInntekt:
"""Implementation of the 'Person.DisponibelInntekt' model. TODO: type model description here. Attributes: kode_field (int): TODO: type description here. beskrivelse_field (string): TODO: type description here."""
def __init__(self, kode_field=None, beskrivelse_field=... | stack_v2_sparse_classes_36k_train_003068 | 2,179 | permissive | [
{
"docstring": "Constructor for the PersonDisponibelInntekt class",
"name": "__init__",
"signature": "def __init__(self, kode_field=None, beskrivelse_field=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dic... | 2 | stack_v2_sparse_classes_30k_train_017793 | Implement the Python class `PersonDisponibelInntekt` described below.
Class description:
Implementation of the 'Person.DisponibelInntekt' model. TODO: type model description here. Attributes: kode_field (int): TODO: type description here. beskrivelse_field (string): TODO: type description here.
Method signatures and ... | Implement the Python class `PersonDisponibelInntekt` described below.
Class description:
Implementation of the 'Person.DisponibelInntekt' model. TODO: type model description here. Attributes: kode_field (int): TODO: type description here. beskrivelse_field (string): TODO: type description here.
Method signatures and ... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class PersonDisponibelInntekt:
"""Implementation of the 'Person.DisponibelInntekt' model. TODO: type model description here. Attributes: kode_field (int): TODO: type description here. beskrivelse_field (string): TODO: type description here."""
def __init__(self, kode_field=None, beskrivelse_field=... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PersonDisponibelInntekt:
"""Implementation of the 'Person.DisponibelInntekt' model. TODO: type model description here. Attributes: kode_field (int): TODO: type description here. beskrivelse_field (string): TODO: type description here."""
def __init__(self, kode_field=None, beskrivelse_field=None, additio... | the_stack_v2_python_sparse | idfy_rest_client/models/person_disponibel_inntekt.py | dealflowteam/Idfy | train | 0 |
126d341993bc3f850329d2912ae2dc87a6a2e51e | [
"super(GetWordInfo, self).__init__()\nself.text = text\nself.freq = 0.0\nself.left = []\nself.right = []\nself.pmi = 0",
"self.freq += 1\nif left:\n self.left.append(left)\nif right:\n self.right.append(right)",
"self.freq /= length\nself.left = cal_infor_entropy(self.left)\nself.right = cal_infor_entropy... | <|body_start_0|>
super(GetWordInfo, self).__init__()
self.text = text
self.freq = 0.0
self.left = []
self.right = []
self.pmi = 0
<|end_body_0|>
<|body_start_1|>
self.freq += 1
if left:
self.left.append(left)
if right:
self... | Store information of each word, including it's frequency, left neighbors and right neighbors | GetWordInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetWordInfo:
"""Store information of each word, including it's frequency, left neighbors and right neighbors"""
def __init__(self, text):
"""init function,the text is the word. :param text:the string will be compute,include fre,PMI,information entropy."""
<|body_0|>
def ... | stack_v2_sparse_classes_36k_train_003069 | 6,102 | no_license | [
{
"docstring": "init function,the text is the word. :param text:the string will be compute,include fre,PMI,information entropy.",
"name": "__init__",
"signature": "def __init__(self, text)"
},
{
"docstring": "Increase frequency of this word, then append left/right neighbors. :param left: left ne... | 4 | stack_v2_sparse_classes_30k_train_011848 | Implement the Python class `GetWordInfo` described below.
Class description:
Store information of each word, including it's frequency, left neighbors and right neighbors
Method signatures and docstrings:
- def __init__(self, text): init function,the text is the word. :param text:the string will be compute,include fre... | Implement the Python class `GetWordInfo` described below.
Class description:
Store information of each word, including it's frequency, left neighbors and right neighbors
Method signatures and docstrings:
- def __init__(self, text): init function,the text is the word. :param text:the string will be compute,include fre... | a5ff7ad6c94c1fbb633d7321fd1a27f849ce6fb8 | <|skeleton|>
class GetWordInfo:
"""Store information of each word, including it's frequency, left neighbors and right neighbors"""
def __init__(self, text):
"""init function,the text is the word. :param text:the string will be compute,include fre,PMI,information entropy."""
<|body_0|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetWordInfo:
"""Store information of each word, including it's frequency, left neighbors and right neighbors"""
def __init__(self, text):
"""init function,the text is the word. :param text:the string will be compute,include fre,PMI,information entropy."""
super(GetWordInfo, self).__init__... | the_stack_v2_python_sparse | word_seg_md/newWordsFind.py | GenjiLuo/the-neologism | train | 0 |
06ceba3fe1c81f76686645e9be33c61721b997c7 | [
"self.credentials = credentials\nself.guid_vec = guid_vec\nself.option_flags = option_flags\nself.ou_path = ou_path\nself.src_sysvol_folder = src_sysvol_folder",
"if dictionary is None:\n return None\ncredentials = cohesity_management_sdk.models.credentials.Credentials.from_dictionary(dictionary.get('credentia... | <|body_start_0|>
self.credentials = credentials
self.guid_vec = guid_vec
self.option_flags = option_flags
self.ou_path = ou_path
self.src_sysvol_folder = src_sysvol_folder
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
credentials ... | Implementation of the 'ADObjectRestoreParam' model. TODO: type description here. Attributes: credentials (Credentials): For restoring user type objects (user, inetOrgPerson or organizationalPerson LDAP classes) that is returned in search result with 'kRestorePasswordRequired' flag, an initial password is required. The ... | ADObjectRestoreParam | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ADObjectRestoreParam:
"""Implementation of the 'ADObjectRestoreParam' model. TODO: type description here. Attributes: credentials (Credentials): For restoring user type objects (user, inetOrgPerson or organizationalPerson LDAP classes) that is returned in search result with 'kRestorePasswordRequi... | stack_v2_sparse_classes_36k_train_003070 | 3,811 | permissive | [
{
"docstring": "Constructor for the ADObjectRestoreParam class",
"name": "__init__",
"signature": "def __init__(self, credentials=None, guid_vec=None, option_flags=None, ou_path=None, src_sysvol_folder=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary... | 2 | null | Implement the Python class `ADObjectRestoreParam` described below.
Class description:
Implementation of the 'ADObjectRestoreParam' model. TODO: type description here. Attributes: credentials (Credentials): For restoring user type objects (user, inetOrgPerson or organizationalPerson LDAP classes) that is returned in se... | Implement the Python class `ADObjectRestoreParam` described below.
Class description:
Implementation of the 'ADObjectRestoreParam' model. TODO: type description here. Attributes: credentials (Credentials): For restoring user type objects (user, inetOrgPerson or organizationalPerson LDAP classes) that is returned in se... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ADObjectRestoreParam:
"""Implementation of the 'ADObjectRestoreParam' model. TODO: type description here. Attributes: credentials (Credentials): For restoring user type objects (user, inetOrgPerson or organizationalPerson LDAP classes) that is returned in search result with 'kRestorePasswordRequi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ADObjectRestoreParam:
"""Implementation of the 'ADObjectRestoreParam' model. TODO: type description here. Attributes: credentials (Credentials): For restoring user type objects (user, inetOrgPerson or organizationalPerson LDAP classes) that is returned in search result with 'kRestorePasswordRequired' flag, an... | the_stack_v2_python_sparse | cohesity_management_sdk/models/ad_object_restore_param.py | cohesity/management-sdk-python | train | 24 |
af795a7d6e32953a8d4e082d4f86a286df610894 | [
"self.options = options\nself.coerce = coerce\nself.doc = getattr(self.coerce, 'coerceDoc', '')",
"if value is None:\n raise UsageError(\"Parameter '{}' requires an argument.\".format(parameterName))\ntry:\n value = self.coerce(value)\nexcept ValueError as e:\n raise UsageError('Parameter type enforcemen... | <|body_start_0|>
self.options = options
self.coerce = coerce
self.doc = getattr(self.coerce, 'coerceDoc', '')
<|end_body_0|>
<|body_start_1|>
if value is None:
raise UsageError("Parameter '{}' requires an argument.".format(parameterName))
try:
value = sel... | Utility class that can corce a parameter before storing it. | CoerceParameter | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CoerceParameter:
"""Utility class that can corce a parameter before storing it."""
def __init__(self, options, coerce):
"""@param options: parent Options object @param coerce: callable used to coerce the value."""
<|body_0|>
def dispatch(self, parameterName, value):
... | stack_v2_sparse_classes_36k_train_003071 | 34,838 | permissive | [
{
"docstring": "@param options: parent Options object @param coerce: callable used to coerce the value.",
"name": "__init__",
"signature": "def __init__(self, options, coerce)"
},
{
"docstring": "When called in dispatch, do the coerce for C{value} and save the returned value.",
"name": "disp... | 2 | null | Implement the Python class `CoerceParameter` described below.
Class description:
Utility class that can corce a parameter before storing it.
Method signatures and docstrings:
- def __init__(self, options, coerce): @param options: parent Options object @param coerce: callable used to coerce the value.
- def dispatch(s... | Implement the Python class `CoerceParameter` described below.
Class description:
Utility class that can corce a parameter before storing it.
Method signatures and docstrings:
- def __init__(self, options, coerce): @param options: parent Options object @param coerce: callable used to coerce the value.
- def dispatch(s... | 5cee0a8c4180a3108538b4e4ce945a18726595a6 | <|skeleton|>
class CoerceParameter:
"""Utility class that can corce a parameter before storing it."""
def __init__(self, options, coerce):
"""@param options: parent Options object @param coerce: callable used to coerce the value."""
<|body_0|>
def dispatch(self, parameterName, value):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CoerceParameter:
"""Utility class that can corce a parameter before storing it."""
def __init__(self, options, coerce):
"""@param options: parent Options object @param coerce: callable used to coerce the value."""
self.options = options
self.coerce = coerce
self.doc = geta... | the_stack_v2_python_sparse | venv/Lib/site-packages/twisted/python/usage.py | zoelesv/Smathchat | train | 9 |
600bba583a2e5abeddbbe7e794de01e6180ec40d | [
"self._table = [[] for x in range(size)]\nif not func:\n func = naive\nself._hash = func",
"hash_val = self._hash(key) % len(self._table)\nfor item in self._table[hash_val]:\n if item[0] == key:\n return item[1]",
"hash_val = self._hash(key) % len(self._table)\nfor item in self._table[hash_val]:\n ... | <|body_start_0|>
self._table = [[] for x in range(size)]
if not func:
func = naive
self._hash = func
<|end_body_0|>
<|body_start_1|>
hash_val = self._hash(key) % len(self._table)
for item in self._table[hash_val]:
if item[0] == key:
return... | Hash class for data structure. | HashTable | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HashTable:
"""Hash class for data structure."""
def __init__(self, size=17, func=None):
"""Initialize the hash."""
<|body_0|>
def get(self, key):
"""Return the value stored at hash of given key."""
<|body_1|>
def set(self, key, val):
"""Store... | stack_v2_sparse_classes_36k_train_003072 | 1,185 | permissive | [
{
"docstring": "Initialize the hash.",
"name": "__init__",
"signature": "def __init__(self, size=17, func=None)"
},
{
"docstring": "Return the value stored at hash of given key.",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": "Store value based on given key."... | 3 | stack_v2_sparse_classes_30k_train_019740 | Implement the Python class `HashTable` described below.
Class description:
Hash class for data structure.
Method signatures and docstrings:
- def __init__(self, size=17, func=None): Initialize the hash.
- def get(self, key): Return the value stored at hash of given key.
- def set(self, key, val): Store value based on... | Implement the Python class `HashTable` described below.
Class description:
Hash class for data structure.
Method signatures and docstrings:
- def __init__(self, size=17, func=None): Initialize the hash.
- def get(self, key): Return the value stored at hash of given key.
- def set(self, key, val): Store value based on... | b9b07656a2ca6fa8cda7d44be9112bb7c2782fb0 | <|skeleton|>
class HashTable:
"""Hash class for data structure."""
def __init__(self, size=17, func=None):
"""Initialize the hash."""
<|body_0|>
def get(self, key):
"""Return the value stored at hash of given key."""
<|body_1|>
def set(self, key, val):
"""Store... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HashTable:
"""Hash class for data structure."""
def __init__(self, size=17, func=None):
"""Initialize the hash."""
self._table = [[] for x in range(size)]
if not func:
func = naive
self._hash = func
def get(self, key):
"""Return the value stored at... | the_stack_v2_python_sparse | src/hash_table.py | Casey0Kane/data-structures | train | 1 |
1c6315bf1ee497701ab03a0319aa9cf1024b13f0 | [
"url = '/dashboard/bookingperiod/'\nresponse = self.client.get(url, HTTP_HOST='website.domain')\nself.assertEqual(response.status_code, 302)",
"url = '/dashboard/bookingperiod/'\nself.client.login(username=self.adminUN, password='pass')\nresponse = self.client.get(url, HTTP_HOST='website.domain')\nself.assertEqua... | <|body_start_0|>
url = '/dashboard/bookingperiod/'
response = self.client.get(url, HTTP_HOST='website.domain')
self.assertEqual(response.status_code, 302)
<|end_body_0|>
<|body_start_1|>
url = '/dashboard/bookingperiod/'
self.client.login(username=self.adminUN, password='pass')
... | DashboardBookingPeriodsTestCase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DashboardBookingPeriodsTestCase:
def test_not_logged_in(self):
"""Test that the dashboard booking period view will redirect whilst not logged in."""
<|body_0|>
def test_logged_in_admin(self):
"""Test that the dashboard bookings period view will load whilst logged in ... | stack_v2_sparse_classes_36k_train_003073 | 26,818 | permissive | [
{
"docstring": "Test that the dashboard booking period view will redirect whilst not logged in.",
"name": "test_not_logged_in",
"signature": "def test_not_logged_in(self)"
},
{
"docstring": "Test that the dashboard bookings period view will load whilst logged in as admin.",
"name": "test_log... | 3 | null | Implement the Python class `DashboardBookingPeriodsTestCase` described below.
Class description:
Implement the DashboardBookingPeriodsTestCase class.
Method signatures and docstrings:
- def test_not_logged_in(self): Test that the dashboard booking period view will redirect whilst not logged in.
- def test_logged_in_a... | Implement the Python class `DashboardBookingPeriodsTestCase` described below.
Class description:
Implement the DashboardBookingPeriodsTestCase class.
Method signatures and docstrings:
- def test_not_logged_in(self): Test that the dashboard booking period view will redirect whilst not logged in.
- def test_logged_in_a... | 37d2942efcbdaad072f7a06ac876a40e0f69f702 | <|skeleton|>
class DashboardBookingPeriodsTestCase:
def test_not_logged_in(self):
"""Test that the dashboard booking period view will redirect whilst not logged in."""
<|body_0|>
def test_logged_in_admin(self):
"""Test that the dashboard bookings period view will load whilst logged in ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DashboardBookingPeriodsTestCase:
def test_not_logged_in(self):
"""Test that the dashboard booking period view will redirect whilst not logged in."""
url = '/dashboard/bookingperiod/'
response = self.client.get(url, HTTP_HOST='website.domain')
self.assertEqual(response.status_co... | the_stack_v2_python_sparse | mooring/test_views.py | dbca-wa/moorings | train | 0 | |
48639cc528d4f438e9f453ff791e82980140c443 | [
"super().__init__(cost_multiplier=cost_multiplier)\nself.control_count = control_count\nself.control_step_count = control_step_count\nself.max_control_norms = max_control_norms\nself.normalization_constant = control_count * control_step_count",
"normalized_controls = anp.divide(controls, self.max_control_norms)\n... | <|body_start_0|>
super().__init__(cost_multiplier=cost_multiplier)
self.control_count = control_count
self.control_step_count = control_step_count
self.max_control_norms = max_control_norms
self.normalization_constant = control_count * control_step_count
<|end_body_0|>
<|body_st... | a cost to penalize high control norms Fields: control_count :: int - the number of controls at each time step control_step_count :: int - the number of time steps cost_multiplier :: float - the weight factor for this cost max_control_norms :: ndarray (control_count) - the maximum norm for each control name :: str - a u... | ControlNorm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ControlNorm:
"""a cost to penalize high control norms Fields: control_count :: int - the number of controls at each time step control_step_count :: int - the number of time steps cost_multiplier :: float - the weight factor for this cost max_control_norms :: ndarray (control_count) - the maximum ... | stack_v2_sparse_classes_36k_train_003074 | 2,581 | permissive | [
{
"docstring": "See class fields for argument information.",
"name": "__init__",
"signature": "def __init__(self, control_count, control_step_count, max_control_norms, cost_multiplier=1.0)"
},
{
"docstring": "Args: controls :: ndarray (control_step_count, control_count) - the control parameters ... | 2 | stack_v2_sparse_classes_30k_train_013508 | Implement the Python class `ControlNorm` described below.
Class description:
a cost to penalize high control norms Fields: control_count :: int - the number of controls at each time step control_step_count :: int - the number of time steps cost_multiplier :: float - the weight factor for this cost max_control_norms ::... | Implement the Python class `ControlNorm` described below.
Class description:
a cost to penalize high control norms Fields: control_count :: int - the number of controls at each time step control_step_count :: int - the number of time steps cost_multiplier :: float - the weight factor for this cost max_control_norms ::... | 64c1eed34c9a4200a01a7152932482a29a1fd89e | <|skeleton|>
class ControlNorm:
"""a cost to penalize high control norms Fields: control_count :: int - the number of controls at each time step control_step_count :: int - the number of time steps cost_multiplier :: float - the weight factor for this cost max_control_norms :: ndarray (control_count) - the maximum ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ControlNorm:
"""a cost to penalize high control norms Fields: control_count :: int - the number of controls at each time step control_step_count :: int - the number of time steps cost_multiplier :: float - the weight factor for this cost max_control_norms :: ndarray (control_count) - the maximum norm for each... | the_stack_v2_python_sparse | qoc/standard/costs/controlnorm.py | jmbaker94/qoc | train | 0 |
cc7c8e7b2085a2ffdecf1ff5e5fadc209279dd23 | [
"detalle_compra = get_detalle_compra_id(id_detalle_compra)\nif not detalle_compra:\n api.abort(404)\nelse:\n return detalle_compra",
"data = request.json\ndetalle_compra = update_detalle_compra(id_detalle_compra, data)\nif not detalle_compra:\n api.abort(404)\nelse:\n return detalle_compra",
"detall... | <|body_start_0|>
detalle_compra = get_detalle_compra_id(id_detalle_compra)
if not detalle_compra:
api.abort(404)
else:
return detalle_compra
<|end_body_0|>
<|body_start_1|>
data = request.json
detalle_compra = update_detalle_compra(id_detalle_compra, data... | Compra | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Compra:
def get(self, id_detalle_compra):
"""get a detalle_compra given its identifier"""
<|body_0|>
def put(self, id_detalle_compra):
"""update a detalle_compra given its identifier"""
<|body_1|>
def delete(self, id_detalle_compra):
"""delete a ... | stack_v2_sparse_classes_36k_train_003075 | 2,198 | no_license | [
{
"docstring": "get a detalle_compra given its identifier",
"name": "get",
"signature": "def get(self, id_detalle_compra)"
},
{
"docstring": "update a detalle_compra given its identifier",
"name": "put",
"signature": "def put(self, id_detalle_compra)"
},
{
"docstring": "delete a ... | 3 | stack_v2_sparse_classes_30k_train_001407 | Implement the Python class `Compra` described below.
Class description:
Implement the Compra class.
Method signatures and docstrings:
- def get(self, id_detalle_compra): get a detalle_compra given its identifier
- def put(self, id_detalle_compra): update a detalle_compra given its identifier
- def delete(self, id_det... | Implement the Python class `Compra` described below.
Class description:
Implement the Compra class.
Method signatures and docstrings:
- def get(self, id_detalle_compra): get a detalle_compra given its identifier
- def put(self, id_detalle_compra): update a detalle_compra given its identifier
- def delete(self, id_det... | e3e6d716102280e73932e5eba65b2ff27eec45e0 | <|skeleton|>
class Compra:
def get(self, id_detalle_compra):
"""get a detalle_compra given its identifier"""
<|body_0|>
def put(self, id_detalle_compra):
"""update a detalle_compra given its identifier"""
<|body_1|>
def delete(self, id_detalle_compra):
"""delete a ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Compra:
def get(self, id_detalle_compra):
"""get a detalle_compra given its identifier"""
detalle_compra = get_detalle_compra_id(id_detalle_compra)
if not detalle_compra:
api.abort(404)
else:
return detalle_compra
def put(self, id_detalle_compra):
... | the_stack_v2_python_sparse | app/main/controller/detalle_compra_controller.py | Team-3-TCS/api-my-store | train | 1 | |
ea9741d0003975c6d8a0b075fd2247a8476b1936 | [
"self.rects = rects\ncurSize = 0\nself.preSize = []\nfor rect in rects:\n curSize += (rect[2] - rect[0]) * (rect[3] - rect[1])\n self.preSize.append(curSize)\nself.totalSize = curSize",
"randWeight = random.randint(1, self.totalSize)\nstart = 0\nend = len(self.preSize) - 1\nidx = None\nwhile start < end:\n ... | <|body_start_0|>
self.rects = rects
curSize = 0
self.preSize = []
for rect in rects:
curSize += (rect[2] - rect[0]) * (rect[3] - rect[1])
self.preSize.append(curSize)
self.totalSize = curSize
<|end_body_0|>
<|body_start_1|>
randWeight = random.ran... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
<|body_0|>
def pick(self):
""":rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.rects = rects
curSize = 0
self.preSize = []
for rect... | stack_v2_sparse_classes_36k_train_003076 | 2,383 | no_license | [
{
"docstring": ":type rects: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, rects)"
},
{
"docstring": ":rtype: List[int]",
"name": "pick",
"signature": "def pick(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014642 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, rects): :type rects: List[List[int]]
- def pick(self): :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, rects): :type rects: List[List[int]]
- def pick(self): :rtype: List[int]
<|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: ... | fd310ec0a989e003242f1840230aaac150f006f0 | <|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
<|body_0|>
def pick(self):
""":rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
self.rects = rects
curSize = 0
self.preSize = []
for rect in rects:
curSize += (rect[2] - rect[0]) * (rect[3] - rect[1])
self.preSize.append(curSize)
self.totalSize =... | the_stack_v2_python_sparse | 好咧,最后还是要搞google/medium/RandomPointinNonoverlappingRectangles497_WRONG.py | jing1988a/python_fb | train | 0 | |
12a28e1512f472e02f759f89186f17763f6ecca8 | [
"super(_IterationPhaseLearnOnly, self).__init__(nIters=nIters)\nself.__model = model\nreturn",
"super(_IterationPhaseLearnOnly, self).enterPhase()\nself.__model.enableLearning()\nself.__model.disableInference()\nreturn"
] | <|body_start_0|>
super(_IterationPhaseLearnOnly, self).__init__(nIters=nIters)
self.__model = model
return
<|end_body_0|>
<|body_start_1|>
super(_IterationPhaseLearnOnly, self).enterPhase()
self.__model.enableLearning()
self.__model.disableInference()
return
<|en... | This class implements the "learn-only" phase of the Iteration Cycle | _IterationPhaseLearnOnly | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _IterationPhaseLearnOnly:
"""This class implements the "learn-only" phase of the Iteration Cycle"""
def __init__(self, model, nIters):
"""model: Model instance nIters: Number of iterations; MUST be greater than 0"""
<|body_0|>
def enterPhase(self):
"""[_Iteration... | stack_v2_sparse_classes_36k_train_003077 | 16,958 | no_license | [
{
"docstring": "model: Model instance nIters: Number of iterations; MUST be greater than 0",
"name": "__init__",
"signature": "def __init__(self, model, nIters)"
},
{
"docstring": "[_IterationPhase method implementation] Performs initialization that is necessary upon entry to the phase. Must be ... | 2 | stack_v2_sparse_classes_30k_train_002271 | Implement the Python class `_IterationPhaseLearnOnly` described below.
Class description:
This class implements the "learn-only" phase of the Iteration Cycle
Method signatures and docstrings:
- def __init__(self, model, nIters): model: Model instance nIters: Number of iterations; MUST be greater than 0
- def enterPha... | Implement the Python class `_IterationPhaseLearnOnly` described below.
Class description:
This class implements the "learn-only" phase of the Iteration Cycle
Method signatures and docstrings:
- def __init__(self, model, nIters): model: Model instance nIters: Number of iterations; MUST be greater than 0
- def enterPha... | d494b3041069d377d6a7a9c296a14334f2fa5acc | <|skeleton|>
class _IterationPhaseLearnOnly:
"""This class implements the "learn-only" phase of the Iteration Cycle"""
def __init__(self, model, nIters):
"""model: Model instance nIters: Number of iterations; MUST be greater than 0"""
<|body_0|>
def enterPhase(self):
"""[_Iteration... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _IterationPhaseLearnOnly:
"""This class implements the "learn-only" phase of the Iteration Cycle"""
def __init__(self, model, nIters):
"""model: Model instance nIters: Number of iterations; MUST be greater than 0"""
super(_IterationPhaseLearnOnly, self).__init__(nIters=nIters)
sel... | the_stack_v2_python_sparse | python/numenta_nupic/nupic-master/src/nupic/frameworks/opf/opftaskdriver.py | LiuFang816/SALSTM_py_data | train | 10 |
49bea5216e02a8c891f34824e163cd961e813ca2 | [
"link = 'https://store.steampowered.com/'\ngns = '<div class=\"tab_item_name\">'\ngds = '<div class=\"discount_pct\">-'\ngops = 'class=\"discount_original_price\">'\ngps = 'class=\"discount_final_price\">'\nend = '</div>'\nself.games = []\nself.database = database\ninfo = requests.get(link).text\nself.gather_games(... | <|body_start_0|>
link = 'https://store.steampowered.com/'
gns = '<div class="tab_item_name">'
gds = '<div class="discount_pct">-'
gops = 'class="discount_original_price">'
gps = 'class="discount_final_price">'
end = '</div>'
self.games = []
self.database =... | scansteampage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class scansteampage:
def __init__(self, database='gameshelf'):
"""See game's explanation for the abbreviations"""
<|body_0|>
def gather_games(self, info, gns, gds, gps, gops, end):
"""This method adds game objects to the scansteampage object's list self.games"""
<|... | stack_v2_sparse_classes_36k_train_003078 | 4,903 | permissive | [
{
"docstring": "See game's explanation for the abbreviations",
"name": "__init__",
"signature": "def __init__(self, database='gameshelf')"
},
{
"docstring": "This method adds game objects to the scansteampage object's list self.games",
"name": "gather_games",
"signature": "def gather_gam... | 3 | null | Implement the Python class `scansteampage` described below.
Class description:
Implement the scansteampage class.
Method signatures and docstrings:
- def __init__(self, database='gameshelf'): See game's explanation for the abbreviations
- def gather_games(self, info, gns, gds, gps, gops, end): This method adds game o... | Implement the Python class `scansteampage` described below.
Class description:
Implement the scansteampage class.
Method signatures and docstrings:
- def __init__(self, database='gameshelf'): See game's explanation for the abbreviations
- def gather_games(self, info, gns, gds, gps, gops, end): This method adds game o... | 8648e42feb610228021b42646c1c4c8b929e745a | <|skeleton|>
class scansteampage:
def __init__(self, database='gameshelf'):
"""See game's explanation for the abbreviations"""
<|body_0|>
def gather_games(self, info, gns, gds, gps, gops, end):
"""This method adds game objects to the scansteampage object's list self.games"""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class scansteampage:
def __init__(self, database='gameshelf'):
"""See game's explanation for the abbreviations"""
link = 'https://store.steampowered.com/'
gns = '<div class="tab_item_name">'
gds = '<div class="discount_pct">-'
gops = 'class="discount_original_price">'
... | the_stack_v2_python_sparse | 3_advanced/chapter20/solutions/txt_write_practice.py | thestrawberryqueen/python | train | 0 | |
6451e530afed9ec0497f224372d19ab2d7416b5c | [
"if not issubclass(type(report), Path):\n report = Path(report.temporary_file_path())\nif zipfile.is_zipfile(str(report)):\n return self._process_zipfile(report)\nelse:\n raise ValueError(f'File {report} not a zip!')",
"components = dict()\nsource = dict()\ntry:\n with zipfile.ZipFile(str(report)) as ... | <|body_start_0|>
if not issubclass(type(report), Path):
report = Path(report.temporary_file_path())
if zipfile.is_zipfile(str(report)):
return self._process_zipfile(report)
else:
raise ValueError(f'File {report} not a zip!')
<|end_body_0|>
<|body_start_1|>
... | Importer for blackduck. V3 is different in that it creates a Finding in defect dojo for each vulnerable component version used in a project, for each license that is In Violation for the components, AND for each license that is marked with a 'License Risk' that is anything other than 'OK' as a For Review Finding in def... | BlackduckCRImporter | [
"MIT-open-group",
"GCC-exception-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LGPL-3.0-only",
"GPL-3.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-3.0-or-later",
"IJG",
"Zlib",
"LicenseRef-scancode-proprietary-license",
"PSF-2.0",
"LicenseRef-scancode-python-cwi... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlackduckCRImporter:
"""Importer for blackduck. V3 is different in that it creates a Finding in defect dojo for each vulnerable component version used in a project, for each license that is In Violation for the components, AND for each license that is marked with a 'License Risk' that is anything... | stack_v2_sparse_classes_36k_train_003079 | 5,989 | permissive | [
{
"docstring": "Given a path to a zip file, this function will find the relevant CSV files and return three dictionaries with the information needed. Dictionaries are components, source and security risks. :param report: Path to zip file :return: ( {component_id:details} , {component_id:[vulns]}, {component_id:... | 5 | null | Implement the Python class `BlackduckCRImporter` described below.
Class description:
Importer for blackduck. V3 is different in that it creates a Finding in defect dojo for each vulnerable component version used in a project, for each license that is In Violation for the components, AND for each license that is marked... | Implement the Python class `BlackduckCRImporter` described below.
Class description:
Importer for blackduck. V3 is different in that it creates a Finding in defect dojo for each vulnerable component version used in a project, for each license that is In Violation for the components, AND for each license that is marked... | b98093dcb966ffe972f8719337de2209bf3989ec | <|skeleton|>
class BlackduckCRImporter:
"""Importer for blackduck. V3 is different in that it creates a Finding in defect dojo for each vulnerable component version used in a project, for each license that is In Violation for the components, AND for each license that is marked with a 'License Risk' that is anything... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BlackduckCRImporter:
"""Importer for blackduck. V3 is different in that it creates a Finding in defect dojo for each vulnerable component version used in a project, for each license that is In Violation for the components, AND for each license that is marked with a 'License Risk' that is anything other than '... | the_stack_v2_python_sparse | dojo/tools/blackduck_component_risk/importer.py | DefectDojo/django-DefectDojo | train | 2,719 |
d4d1407c5e94cdaedf63ccc88e1092cafd364240 | [
"assert len(input_list) > 0\nsuper().__init__(self.PROBLEM_NAME)\nself.input_list = input_list",
"print('Solving {} problem ...'.format(self.PROBLEM_NAME))\ni = 0\nwhile i < len(self.input_list):\n j = i + 1\n while j < len(self.input_list) and (self.input_list[i] == self.input_list[j] or self.input_list[i]... | <|body_start_0|>
assert len(input_list) > 0
super().__init__(self.PROBLEM_NAME)
self.input_list = input_list
<|end_body_0|>
<|body_start_1|>
print('Solving {} problem ...'.format(self.PROBLEM_NAME))
i = 0
while i < len(self.input_list):
j = i + 1
... | RemoveDuplicatesInPlaceSortedArray | RemoveDuplicatesInPlaceSortedArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RemoveDuplicatesInPlaceSortedArray:
"""RemoveDuplicatesInPlaceSortedArray"""
def __init__(self, input_list):
"""RemoveDuplicatesInPlaceSortedArray Args: input_list: Contains a list of integers Returns: None Raises: None"""
<|body_0|>
def solve(self):
"""Solve the... | stack_v2_sparse_classes_36k_train_003080 | 1,888 | no_license | [
{
"docstring": "RemoveDuplicatesInPlaceSortedArray Args: input_list: Contains a list of integers Returns: None Raises: None",
"name": "__init__",
"signature": "def __init__(self, input_list)"
},
{
"docstring": "Solve the problem Note: The O(n) runtime and O(1) (space). Args: Returns: integer Rai... | 2 | null | Implement the Python class `RemoveDuplicatesInPlaceSortedArray` described below.
Class description:
RemoveDuplicatesInPlaceSortedArray
Method signatures and docstrings:
- def __init__(self, input_list): RemoveDuplicatesInPlaceSortedArray Args: input_list: Contains a list of integers Returns: None Raises: None
- def s... | Implement the Python class `RemoveDuplicatesInPlaceSortedArray` described below.
Class description:
RemoveDuplicatesInPlaceSortedArray
Method signatures and docstrings:
- def __init__(self, input_list): RemoveDuplicatesInPlaceSortedArray Args: input_list: Contains a list of integers Returns: None Raises: None
- def s... | 11f4d25cb211740514c119a60962d075a0817abd | <|skeleton|>
class RemoveDuplicatesInPlaceSortedArray:
"""RemoveDuplicatesInPlaceSortedArray"""
def __init__(self, input_list):
"""RemoveDuplicatesInPlaceSortedArray Args: input_list: Contains a list of integers Returns: None Raises: None"""
<|body_0|>
def solve(self):
"""Solve the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RemoveDuplicatesInPlaceSortedArray:
"""RemoveDuplicatesInPlaceSortedArray"""
def __init__(self, input_list):
"""RemoveDuplicatesInPlaceSortedArray Args: input_list: Contains a list of integers Returns: None Raises: None"""
assert len(input_list) > 0
super().__init__(self.PROBLEM_N... | the_stack_v2_python_sparse | python/problems/array/remove_duplicates_in_place_sorted_array.py | santhosh-kumar/AlgorithmsAndDataStructures | train | 2 |
8f01b3f9d0767b93ca3be3d65dca909c42d3ae0a | [
"EasyFrame.__init__(self, 'Investment Calculator')\nself.addLabel(text='Initial amount', row=0, column=0)\nself.addLabel(text='Number of years', row=1, column=0)\nself.addLabel(text='Interest rate in %', row=2, column=0)\nself.amount = self.addFloatField(value=0.0, row=0, column=1)\nself.period = self.addIntegerFie... | <|body_start_0|>
EasyFrame.__init__(self, 'Investment Calculator')
self.addLabel(text='Initial amount', row=0, column=0)
self.addLabel(text='Number of years', row=1, column=0)
self.addLabel(text='Interest rate in %', row=2, column=0)
self.amount = self.addFloatField(value=0.0, ro... | Demonstrates a multiline text area. | TextAreaDemo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextAreaDemo:
"""Demonstrates a multiline text area."""
def __init__(self):
"""Sets up the window and widgets."""
<|body_0|>
def compute(self):
"""Computes the investment schedule based on the inputs and outputs the schedule."""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k_train_003081 | 2,955 | no_license | [
{
"docstring": "Sets up the window and widgets.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Computes the investment schedule based on the inputs and outputs the schedule.",
"name": "compute",
"signature": "def compute(self)"
}
] | 2 | null | Implement the Python class `TextAreaDemo` described below.
Class description:
Demonstrates a multiline text area.
Method signatures and docstrings:
- def __init__(self): Sets up the window and widgets.
- def compute(self): Computes the investment schedule based on the inputs and outputs the schedule. | Implement the Python class `TextAreaDemo` described below.
Class description:
Demonstrates a multiline text area.
Method signatures and docstrings:
- def __init__(self): Sets up the window and widgets.
- def compute(self): Computes the investment schedule based on the inputs and outputs the schedule.
<|skeleton|>
cl... | eca69d000dc77681a30734b073b2383c97ccc02e | <|skeleton|>
class TextAreaDemo:
"""Demonstrates a multiline text area."""
def __init__(self):
"""Sets up the window and widgets."""
<|body_0|>
def compute(self):
"""Computes the investment schedule based on the inputs and outputs the schedule."""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TextAreaDemo:
"""Demonstrates a multiline text area."""
def __init__(self):
"""Sets up the window and widgets."""
EasyFrame.__init__(self, 'Investment Calculator')
self.addLabel(text='Initial amount', row=0, column=0)
self.addLabel(text='Number of years', row=1, column=0)
... | the_stack_v2_python_sparse | gui/breezy/textareademo.py | lforet/robomow | train | 11 |
fab93328f25055817288ca02e77a676246110ed1 | [
"list.__init__(self)\nentries = [] if entries is None else entries\nself._url_ = _url_\nurl = _url_\nfilter_syntax = '?filter='\nif url and filter_syntax in url:\n url = url.split(filter_syntax)[0]\nfor item in entries:\n item_url = None\n if 'objectID' in item:\n item_url = '%s/%s' % (url, item['ob... | <|body_start_0|>
list.__init__(self)
entries = [] if entries is None else entries
self._url_ = _url_
url = _url_
filter_syntax = '?filter='
if url and filter_syntax in url:
url = url.split(filter_syntax)[0]
for item in entries:
item_url = N... | Using this class a JSON list will be transformed in a list of WebObject instances. | WebList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WebList:
"""Using this class a JSON list will be transformed in a list of WebObject instances."""
def __init__(self, entries=None, _url_=None):
"""Create a WebList from a list of items that are processed by the _format_response function"""
<|body_0|>
def copy_data(self, ... | stack_v2_sparse_classes_36k_train_003082 | 11,000 | permissive | [
{
"docstring": "Create a WebList from a list of items that are processed by the _format_response function",
"name": "__init__",
"signature": "def __init__(self, entries=None, _url_=None)"
},
{
"docstring": "copy date and retrun json",
"name": "copy_data",
"signature": "def copy_data(self... | 2 | stack_v2_sparse_classes_30k_train_018683 | Implement the Python class `WebList` described below.
Class description:
Using this class a JSON list will be transformed in a list of WebObject instances.
Method signatures and docstrings:
- def __init__(self, entries=None, _url_=None): Create a WebList from a list of items that are processed by the _format_response... | Implement the Python class `WebList` described below.
Class description:
Using this class a JSON list will be transformed in a list of WebObject instances.
Method signatures and docstrings:
- def __init__(self, entries=None, _url_=None): Create a WebList from a list of items that are processed by the _format_response... | fd164a32008a200fc035381a22b2ef284c4d6cd7 | <|skeleton|>
class WebList:
"""Using this class a JSON list will be transformed in a list of WebObject instances."""
def __init__(self, entries=None, _url_=None):
"""Create a WebList from a list of items that are processed by the _format_response function"""
<|body_0|>
def copy_data(self, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WebList:
"""Using this class a JSON list will be transformed in a list of WebObject instances."""
def __init__(self, entries=None, _url_=None):
"""Create a WebList from a list of items that are processed by the _format_response function"""
list.__init__(self)
entries = [] if entri... | the_stack_v2_python_sparse | brisk-main/brisk_ixload/ixrestutils.py | waseembaig/IxBrisk | train | 0 |
0cf94da62afb45bd02680ddbdf5fa24498fd8175 | [
"if not root:\n return ''\ndq, q = (collections.deque(), [])\ndq.append(root)\nq.append(str(root.val))\nwhile dq:\n node = dq.popleft()\n if node:\n dq.append(node.left if node.left else None)\n q.append(str(node.left.val) if node.left else '')\n dq.append(node.right if node.right else... | <|body_start_0|>
if not root:
return ''
dq, q = (collections.deque(), [])
dq.append(root)
q.append(str(root.val))
while dq:
node = dq.popleft()
if node:
dq.append(node.left if node.left else None)
q.append(str(no... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_003083 | 2,095 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 3873502679a5def6af4be03028542f07d059d1a9 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
dq, q = (collections.deque(), [])
dq.append(root)
q.append(str(root.val))
while dq:
node = dq.popleft()
... | the_stack_v2_python_sparse | Python-Algorithms-DataStructure/src/leet/297_SerializeandDeserializeBinaryTree.py | coremedy/Python-Algorithms-DataStructure | train | 0 | |
b9b2568ac198e5c971268684c513f6eab9f01116 | [
"if not isinstance(local_addr, tuple):\n raise TypeError()\nif not isinstance(remote_addr, tuple):\n raise TypeError()\nself.local_addr = local_addr\nself.remote_addr = remote_addr\nself.multicast = multicast\nself.callbacks = []\nself.transport: asyncio.DatagramTransport | None = None",
"if raw:\n try:\... | <|body_start_0|>
if not isinstance(local_addr, tuple):
raise TypeError()
if not isinstance(remote_addr, tuple):
raise TypeError()
self.local_addr = local_addr
self.remote_addr = remote_addr
self.multicast = multicast
self.callbacks = []
sel... | Class for handling (sending and receiving) UDP packets. | UDPTransport | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UDPTransport:
"""Class for handling (sending and receiving) UDP packets."""
def __init__(self, local_addr: tuple[str, int], remote_addr: tuple[str, int], multicast: bool=False):
"""Initialize UDPTransport class."""
<|body_0|>
def data_received_callback(self, raw: bytes, ... | stack_v2_sparse_classes_36k_train_003084 | 6,535 | permissive | [
{
"docstring": "Initialize UDPTransport class.",
"name": "__init__",
"signature": "def __init__(self, local_addr: tuple[str, int], remote_addr: tuple[str, int], multicast: bool=False)"
},
{
"docstring": "Parse and process KNXIP frame. Callback for having received an UDP packet.",
"name": "da... | 5 | null | Implement the Python class `UDPTransport` described below.
Class description:
Class for handling (sending and receiving) UDP packets.
Method signatures and docstrings:
- def __init__(self, local_addr: tuple[str, int], remote_addr: tuple[str, int], multicast: bool=False): Initialize UDPTransport class.
- def data_rece... | Implement the Python class `UDPTransport` described below.
Class description:
Class for handling (sending and receiving) UDP packets.
Method signatures and docstrings:
- def __init__(self, local_addr: tuple[str, int], remote_addr: tuple[str, int], multicast: bool=False): Initialize UDPTransport class.
- def data_rece... | 48d4e31365c15e632b275f0d129cd9f2b2b5717d | <|skeleton|>
class UDPTransport:
"""Class for handling (sending and receiving) UDP packets."""
def __init__(self, local_addr: tuple[str, int], remote_addr: tuple[str, int], multicast: bool=False):
"""Initialize UDPTransport class."""
<|body_0|>
def data_received_callback(self, raw: bytes, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UDPTransport:
"""Class for handling (sending and receiving) UDP packets."""
def __init__(self, local_addr: tuple[str, int], remote_addr: tuple[str, int], multicast: bool=False):
"""Initialize UDPTransport class."""
if not isinstance(local_addr, tuple):
raise TypeError()
... | the_stack_v2_python_sparse | xknx/io/transport/udp_transport.py | XKNX/xknx | train | 248 |
30bb0fc51cb65232d6e68a25e1cf7f75f874c680 | [
"super().__init__()\nact_kwargs = act_kwargs if act_kwargs is not None else {}\nself.out_channels = in_channels if out_channels is None else out_channels\nhidden_channels = int(mlp_ratio * in_channels)\nact_kwargs['dim_in'] = hidden_channels\nact_kwargs['dim_out'] = hidden_channels\nself.fc1 = nn.Linear(in_channels... | <|body_start_0|>
super().__init__()
act_kwargs = act_kwargs if act_kwargs is not None else {}
self.out_channels = in_channels if out_channels is None else out_channels
hidden_channels = int(mlp_ratio * in_channels)
act_kwargs['dim_in'] = hidden_channels
act_kwargs['dim_ou... | Mlp | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mlp:
def __init__(self, in_channels: int, mlp_ratio: int=2, activation: str='star_relu', dropout: float=0.0, bias: bool=False, out_channels: int=None, act_kwargs: Dict[str, Any]=None, **kwargs) -> None:
"""MLP token mixer. - MetaFormer: https://arxiv.org/abs/2210.13452 - MLP-Mixer: https... | stack_v2_sparse_classes_36k_train_003085 | 6,969 | permissive | [
{
"docstring": "MLP token mixer. - MetaFormer: https://arxiv.org/abs/2210.13452 - MLP-Mixer: https://arxiv.org/abs/2105.01601 - Input shape: (B, N, embed_dim) - Output shape: (B, seq_len, embed_dim) Parameters ---------- in_channels : int Number of input features. mlp_ratio : int, default=2 Scaling factor to ge... | 2 | null | Implement the Python class `Mlp` described below.
Class description:
Implement the Mlp class.
Method signatures and docstrings:
- def __init__(self, in_channels: int, mlp_ratio: int=2, activation: str='star_relu', dropout: float=0.0, bias: bool=False, out_channels: int=None, act_kwargs: Dict[str, Any]=None, **kwargs)... | Implement the Python class `Mlp` described below.
Class description:
Implement the Mlp class.
Method signatures and docstrings:
- def __init__(self, in_channels: int, mlp_ratio: int=2, activation: str='star_relu', dropout: float=0.0, bias: bool=False, out_channels: int=None, act_kwargs: Dict[str, Any]=None, **kwargs)... | 7f79405012eb934b419bbdba8de23f35e840ca85 | <|skeleton|>
class Mlp:
def __init__(self, in_channels: int, mlp_ratio: int=2, activation: str='star_relu', dropout: float=0.0, bias: bool=False, out_channels: int=None, act_kwargs: Dict[str, Any]=None, **kwargs) -> None:
"""MLP token mixer. - MetaFormer: https://arxiv.org/abs/2210.13452 - MLP-Mixer: https... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Mlp:
def __init__(self, in_channels: int, mlp_ratio: int=2, activation: str='star_relu', dropout: float=0.0, bias: bool=False, out_channels: int=None, act_kwargs: Dict[str, Any]=None, **kwargs) -> None:
"""MLP token mixer. - MetaFormer: https://arxiv.org/abs/2210.13452 - MLP-Mixer: https://arxiv.org/a... | the_stack_v2_python_sparse | cellseg_models_pytorch/modules/mlp.py | okunator/cellseg_models.pytorch | train | 43 | |
23ab1bd3739ccf116c3415bb57fc5fcafaf2e3b9 | [
"self.directory: str = directory\nself.files_summary: Dict[str, Dict[str, int]] = dict()\nself.analyze_files()\nself.pretty_print()",
"num_lines: int = 0\nnum_class: int = 0\nnum_def: int = 0\nnum_char: int = 0\nfilename: str = ''\nfile_list = os.listdir(self.directory)\nfor i in range(len(file_list)):\n if fi... | <|body_start_0|>
self.directory: str = directory
self.files_summary: Dict[str, Dict[str, int]] = dict()
self.analyze_files()
self.pretty_print()
<|end_body_0|>
<|body_start_1|>
num_lines: int = 0
num_class: int = 0
num_def: int = 0
num_char: int = 0
... | This function searches that directory for Python files (i.e. files ending with .py). For each .py file in the directory, opens each file and calculates a summary of the file including: the file name the total number of lines in the file the total number of characters in the file the number of Python functions (lines th... | FileAnalyzer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileAnalyzer:
"""This function searches that directory for Python files (i.e. files ending with .py). For each .py file in the directory, opens each file and calculates a summary of the file including: the file name the total number of lines in the file the total number of characters in the file ... | stack_v2_sparse_classes_36k_train_003086 | 5,661 | no_license | [
{
"docstring": "Your docstring should go here for the description of the method.",
"name": "__init__",
"signature": "def __init__(self, directory: str) -> None"
},
{
"docstring": "A method that populate the summarized data into self.files_summary.",
"name": "analyze_files",
"signature": ... | 3 | stack_v2_sparse_classes_30k_train_008369 | Implement the Python class `FileAnalyzer` described below.
Class description:
This function searches that directory for Python files (i.e. files ending with .py). For each .py file in the directory, opens each file and calculates a summary of the file including: the file name the total number of lines in the file the ... | Implement the Python class `FileAnalyzer` described below.
Class description:
This function searches that directory for Python files (i.e. files ending with .py). For each .py file in the directory, opens each file and calculates a summary of the file including: the file name the total number of lines in the file the ... | 7fe7bb8518584cc98f00f16d6b1cd0a288254ee3 | <|skeleton|>
class FileAnalyzer:
"""This function searches that directory for Python files (i.e. files ending with .py). For each .py file in the directory, opens each file and calculates a summary of the file including: the file name the total number of lines in the file the total number of characters in the file ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileAnalyzer:
"""This function searches that directory for Python files (i.e. files ending with .py). For each .py file in the directory, opens each file and calculates a summary of the file including: the file name the total number of lines in the file the total number of characters in the file the number of... | the_stack_v2_python_sparse | HW_08_Rohan_Ratwani/HW08_Rohan_Ratwani.py | RohanRatwani/SSW-810 | train | 0 |
653f5f73837501e75f257abbed79603699e03a60 | [
"super().__init__()\nself.ignore = ignore\nif reduced:\n self.loss_fn = partial(metrics.reduced_focal_loss, gamma=gamma, threshold=threshold, reduction=reduction)\nelse:\n self.loss_fn = partial(metrics.sigmoid_focal_loss, gamma=gamma, alpha=alpha, reduction=reduction)",
"targets = targets.view(-1)\nlogits ... | <|body_start_0|>
super().__init__()
self.ignore = ignore
if reduced:
self.loss_fn = partial(metrics.reduced_focal_loss, gamma=gamma, threshold=threshold, reduction=reduction)
else:
self.loss_fn = partial(metrics.sigmoid_focal_loss, gamma=gamma, alpha=alpha, reduct... | Compute focal loss for binary classification problem. It has been proposed in `Focal Loss for Dense Object Detection`_ paper. .. _Focal Loss for Dense Object Detection: https://arxiv.org/abs/1708.02002 | FocalLossBinary | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FocalLossBinary:
"""Compute focal loss for binary classification problem. It has been proposed in `Focal Loss for Dense Object Detection`_ paper. .. _Focal Loss for Dense Object Detection: https://arxiv.org/abs/1708.02002"""
def __init__(self, ignore: int=None, reduced: bool=False, gamma: fl... | stack_v2_sparse_classes_36k_train_003087 | 3,869 | permissive | [
{
"docstring": "@TODO: Docs. Contribution is welcome.",
"name": "__init__",
"signature": "def __init__(self, ignore: int=None, reduced: bool=False, gamma: float=2.0, alpha: float=0.25, threshold: float=0.5, reduction: str='mean')"
},
{
"docstring": "Args: logits: [bs; ...] targets: [bs; ...] Ret... | 2 | null | Implement the Python class `FocalLossBinary` described below.
Class description:
Compute focal loss for binary classification problem. It has been proposed in `Focal Loss for Dense Object Detection`_ paper. .. _Focal Loss for Dense Object Detection: https://arxiv.org/abs/1708.02002
Method signatures and docstrings:
-... | Implement the Python class `FocalLossBinary` described below.
Class description:
Compute focal loss for binary classification problem. It has been proposed in `Focal Loss for Dense Object Detection`_ paper. .. _Focal Loss for Dense Object Detection: https://arxiv.org/abs/1708.02002
Method signatures and docstrings:
-... | e99f90655d0efcf22559a46e928f0f98c9807ebf | <|skeleton|>
class FocalLossBinary:
"""Compute focal loss for binary classification problem. It has been proposed in `Focal Loss for Dense Object Detection`_ paper. .. _Focal Loss for Dense Object Detection: https://arxiv.org/abs/1708.02002"""
def __init__(self, ignore: int=None, reduced: bool=False, gamma: fl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FocalLossBinary:
"""Compute focal loss for binary classification problem. It has been proposed in `Focal Loss for Dense Object Detection`_ paper. .. _Focal Loss for Dense Object Detection: https://arxiv.org/abs/1708.02002"""
def __init__(self, ignore: int=None, reduced: bool=False, gamma: float=2.0, alph... | the_stack_v2_python_sparse | catalyst/contrib/losses/focal.py | catalyst-team/catalyst | train | 3,038 |
4cd6c6d7f396db9826c905c4bfb2c3e448b6ea9e | [
"subsc = get_subscription(request, username)\nbuying_list = get_buying_list(request)\nfav_list = get_fav_list(request)\nrecipes = get_recipes(request, username, fav_list)\ntag_list = []\nif 'tag' in request.GET:\n tag_list, recipes = formation_tags(request, recipes)\nis_paginator, prev_url, next_url, parameters,... | <|body_start_0|>
subsc = get_subscription(request, username)
buying_list = get_buying_list(request)
fav_list = get_fav_list(request)
recipes = get_recipes(request, username, fav_list)
tag_list = []
if 'tag' in request.GET:
tag_list, recipes = formation_tags(re... | Класс миксин. Для того, чтобы не копипастить одни и теже методы в нескольких предтсавлениях. | IndexPageMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IndexPageMixin:
"""Класс миксин. Для того, чтобы не копипастить одни и теже методы в нескольких предтсавлениях."""
def get(self, request, username=None):
"""Представление для главной страницы, страницы автора, избранного. Помимо самих рецептов, возвращает переменные для проверки сост... | stack_v2_sparse_classes_36k_train_003088 | 7,761 | no_license | [
{
"docstring": "Представление для главной страницы, страницы автора, избранного. Помимо самих рецептов, возвращает переменные для проверки состояния переключателей. subsc - подписан на автора или нет. fav_list - список с id рецептов которые в избранном. buying_list - список с id рецептов, добавленных в покупки.... | 3 | stack_v2_sparse_classes_30k_train_007744 | Implement the Python class `IndexPageMixin` described below.
Class description:
Класс миксин. Для того, чтобы не копипастить одни и теже методы в нескольких предтсавлениях.
Method signatures and docstrings:
- def get(self, request, username=None): Представление для главной страницы, страницы автора, избранного. Помим... | Implement the Python class `IndexPageMixin` described below.
Class description:
Класс миксин. Для того, чтобы не копипастить одни и теже методы в нескольких предтсавлениях.
Method signatures and docstrings:
- def get(self, request, username=None): Представление для главной страницы, страницы автора, избранного. Помим... | dba6f5daf5b046a900f6e8c4b295b919aa03ed43 | <|skeleton|>
class IndexPageMixin:
"""Класс миксин. Для того, чтобы не копипастить одни и теже методы в нескольких предтсавлениях."""
def get(self, request, username=None):
"""Представление для главной страницы, страницы автора, избранного. Помимо самих рецептов, возвращает переменные для проверки сост... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IndexPageMixin:
"""Класс миксин. Для того, чтобы не копипастить одни и теже методы в нескольких предтсавлениях."""
def get(self, request, username=None):
"""Представление для главной страницы, страницы автора, избранного. Помимо самих рецептов, возвращает переменные для проверки состояния переклю... | the_stack_v2_python_sparse | recipes/mixins.py | zYoma/foodgram-project | train | 0 |
90c430c99d1bb2798fbe46dba714401a4be85254 | [
"dir_path = Path(dir_path)\ndestination = dir_path / usage_constant.USAGE_STATS_FILE\ntemp = dir_path / f'{usage_constant.USAGE_STATS_FILE}.tmp'\nwith temp.open(mode='w') as json_file:\n json_file.write(json.dumps(asdict(data)))\nif sys.platform == 'win32':\n destination.unlink(missing_ok=True)\ntemp.rename(d... | <|body_start_0|>
dir_path = Path(dir_path)
destination = dir_path / usage_constant.USAGE_STATS_FILE
temp = dir_path / f'{usage_constant.USAGE_STATS_FILE}.tmp'
with temp.open(mode='w') as json_file:
json_file.write(json.dumps(asdict(data)))
if sys.platform == 'win32':
... | The client implementation for usage report. It is in charge of writing usage stats to the directory and report usage stats. | UsageReportClient | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UsageReportClient:
"""The client implementation for usage report. It is in charge of writing usage stats to the directory and report usage stats."""
def write_usage_data(self, data: UsageStatsToWrite, dir_path: str) -> None:
"""Write the usage data to the directory. Params: data: Dat... | stack_v2_sparse_classes_36k_train_003089 | 29,968 | permissive | [
{
"docstring": "Write the usage data to the directory. Params: data: Data to report dir_path: The path to the directory to write usage data.",
"name": "write_usage_data",
"signature": "def write_usage_data(self, data: UsageStatsToWrite, dir_path: str) -> None"
},
{
"docstring": "Report the usage... | 2 | stack_v2_sparse_classes_30k_train_011775 | Implement the Python class `UsageReportClient` described below.
Class description:
The client implementation for usage report. It is in charge of writing usage stats to the directory and report usage stats.
Method signatures and docstrings:
- def write_usage_data(self, data: UsageStatsToWrite, dir_path: str) -> None:... | Implement the Python class `UsageReportClient` described below.
Class description:
The client implementation for usage report. It is in charge of writing usage stats to the directory and report usage stats.
Method signatures and docstrings:
- def write_usage_data(self, data: UsageStatsToWrite, dir_path: str) -> None:... | edba68c3e7cf255d1d6479329f305adb7fa4c3ed | <|skeleton|>
class UsageReportClient:
"""The client implementation for usage report. It is in charge of writing usage stats to the directory and report usage stats."""
def write_usage_data(self, data: UsageStatsToWrite, dir_path: str) -> None:
"""Write the usage data to the directory. Params: data: Dat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UsageReportClient:
"""The client implementation for usage report. It is in charge of writing usage stats to the directory and report usage stats."""
def write_usage_data(self, data: UsageStatsToWrite, dir_path: str) -> None:
"""Write the usage data to the directory. Params: data: Data to report d... | the_stack_v2_python_sparse | python/ray/_private/usage/usage_lib.py | ray-project/ray | train | 29,482 |
3cf747d7448df78ec5e2af3708bb560103b6a650 | [
"super().__init__()\nself.eta = eta\nself.update_rule = update_rule",
"relative_return = self.relative_return[time]\ndot_product = np.dot(self.weights, relative_return)\nif self.update_rule == 'MU':\n new_weight = self.weights * np.exp(self.eta * relative_return / dot_product)\nelif self.update_rule == 'EM':\n... | <|body_start_0|>
super().__init__()
self.eta = eta
self.update_rule = update_rule
<|end_body_0|>
<|body_start_1|>
relative_return = self.relative_return[time]
dot_product = np.dot(self.weights, relative_return)
if self.update_rule == 'MU':
new_weight = self.w... | This class implements the Exponential Gradient Portfolio strategy. It is reproduced with modification from the following paper: `Li, B., Hoi, S. C.H., 2012. OnLine Portfolio Selection: A Survey. ACM Comput. Surv. V, N, Article A (December 2012), 33 pages. <https://arxiv.org/abs/1212.2129>`_ Exponential gradient strateg... | EG | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EG:
"""This class implements the Exponential Gradient Portfolio strategy. It is reproduced with modification from the following paper: `Li, B., Hoi, S. C.H., 2012. OnLine Portfolio Selection: A Survey. ACM Comput. Surv. V, N, Article A (December 2012), 33 pages. <https://arxiv.org/abs/1212.2129>`... | stack_v2_sparse_classes_36k_train_003090 | 2,875 | permissive | [
{
"docstring": "Initializes with the designated update rule and eta, the learning rate. :param update_rule: (str) 'MU': Multiplicative Update, 'GP': Gradient Projection, 'EM': Expectation Maximization. All three update rules return similar results with slight differences. :param eta: (float) Learning rate with ... | 2 | stack_v2_sparse_classes_30k_train_010541 | Implement the Python class `EG` described below.
Class description:
This class implements the Exponential Gradient Portfolio strategy. It is reproduced with modification from the following paper: `Li, B., Hoi, S. C.H., 2012. OnLine Portfolio Selection: A Survey. ACM Comput. Surv. V, N, Article A (December 2012), 33 pa... | Implement the Python class `EG` described below.
Class description:
This class implements the Exponential Gradient Portfolio strategy. It is reproduced with modification from the following paper: `Li, B., Hoi, S. C.H., 2012. OnLine Portfolio Selection: A Survey. ACM Comput. Surv. V, N, Article A (December 2012), 33 pa... | 046c47d995da08b1003bba3f9c07d5bfb73d9c1f | <|skeleton|>
class EG:
"""This class implements the Exponential Gradient Portfolio strategy. It is reproduced with modification from the following paper: `Li, B., Hoi, S. C.H., 2012. OnLine Portfolio Selection: A Survey. ACM Comput. Surv. V, N, Article A (December 2012), 33 pages. <https://arxiv.org/abs/1212.2129>`... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EG:
"""This class implements the Exponential Gradient Portfolio strategy. It is reproduced with modification from the following paper: `Li, B., Hoi, S. C.H., 2012. OnLine Portfolio Selection: A Survey. ACM Comput. Surv. V, N, Article A (December 2012), 33 pages. <https://arxiv.org/abs/1212.2129>`_ Exponential... | the_stack_v2_python_sparse | src/collection/portfoliolab/online_portfolio_selection/eg.py | Ta-nu-ki/dissertacao | train | 0 |
3bb8a88a44f85f67263e33c347de5260be8c87ca | [
"super(SampleModifier, self).__init__(modifier_dict)\nself.modifier_dict = modifier_dict\nself.default = default\nself.samples: List[str] = list(self.modifier_dict.keys())",
"if sample in self.samples:\n return self.modifier_dict[sample]\nelif self.default is not None:\n return self.default\nelse:\n rais... | <|body_start_0|>
super(SampleModifier, self).__init__(modifier_dict)
self.modifier_dict = modifier_dict
self.default = default
self.samples: List[str] = list(self.modifier_dict.keys())
<|end_body_0|>
<|body_start_1|>
if sample in self.samples:
return self.modifier_di... | SampleModifier | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SampleModifier:
def __init__(self, modifier_dict: ModifierDict, default: Union[str, int, float, bool, Dict, None]=None):
"""A Sample Modifier is a Modifier, that modifies the configuration based on the given sample Args: modifier_dict : A dict containing the information, how a parameter ... | stack_v2_sparse_classes_36k_train_003091 | 3,538 | permissive | [
{
"docstring": "A Sample Modifier is a Modifier, that modifies the configuration based on the given sample Args: modifier_dict : A dict containing the information, how a parameter should be modified based on the sample. default: If set, the default is used for all sample not specified in the modifier dict. Defa... | 2 | stack_v2_sparse_classes_30k_train_011122 | Implement the Python class `SampleModifier` described below.
Class description:
Implement the SampleModifier class.
Method signatures and docstrings:
- def __init__(self, modifier_dict: ModifierDict, default: Union[str, int, float, bool, Dict, None]=None): A Sample Modifier is a Modifier, that modifies the configurat... | Implement the Python class `SampleModifier` described below.
Class description:
Implement the SampleModifier class.
Method signatures and docstrings:
- def __init__(self, modifier_dict: ModifierDict, default: Union[str, int, float, bool, Dict, None]=None): A Sample Modifier is a Modifier, that modifies the configurat... | 229fac41ec8fb34fc4ae9584b1ea428ef95b914e | <|skeleton|>
class SampleModifier:
def __init__(self, modifier_dict: ModifierDict, default: Union[str, int, float, bool, Dict, None]=None):
"""A Sample Modifier is a Modifier, that modifies the configuration based on the given sample Args: modifier_dict : A dict containing the information, how a parameter ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SampleModifier:
def __init__(self, modifier_dict: ModifierDict, default: Union[str, int, float, bool, Dict, None]=None):
"""A Sample Modifier is a Modifier, that modifies the configuration based on the given sample Args: modifier_dict : A dict containing the information, how a parameter should be modi... | the_stack_v2_python_sparse | code_generation/modifiers.py | KIT-CMS/CROWN | train | 6 | |
b6703b402b74a938fae621465c30750f63f04112 | [
"siteconfig1 = SiteConfiguration.objects.get_current()\nself.assertFalse(siteconfig1.is_expired())\nsiteconfig2 = SiteConfiguration.objects.get(site=self.siteconfig.site)\nsiteconfig2.set('foobar', 123)\nsiteconfig2.save(clear_caches=False)\nself.assertTrue(siteconfig1.is_expired())\nSiteConfiguration.objects.check... | <|body_start_0|>
siteconfig1 = SiteConfiguration.objects.get_current()
self.assertFalse(siteconfig1.is_expired())
siteconfig2 = SiteConfiguration.objects.get(site=self.siteconfig.site)
siteconfig2.set('foobar', 123)
siteconfig2.save(clear_caches=False)
self.assertTrue(sit... | Unit tests for SiteConfigurationManager. | SiteConfigurationManagerTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SiteConfigurationManagerTests:
"""Unit tests for SiteConfigurationManager."""
def test_check_expired_with_stale_cache(self):
"""Testing SiteConfigurationManager.check_expired with stale cache"""
<|body_0|>
def test_check_expired_with_expired_cache(self):
"""Testi... | stack_v2_sparse_classes_36k_train_003092 | 19,826 | no_license | [
{
"docstring": "Testing SiteConfigurationManager.check_expired with stale cache",
"name": "test_check_expired_with_stale_cache",
"signature": "def test_check_expired_with_stale_cache(self)"
},
{
"docstring": "Testing SiteConfigurationManager.check_expired with an expired state in cache",
"na... | 3 | null | Implement the Python class `SiteConfigurationManagerTests` described below.
Class description:
Unit tests for SiteConfigurationManager.
Method signatures and docstrings:
- def test_check_expired_with_stale_cache(self): Testing SiteConfigurationManager.check_expired with stale cache
- def test_check_expired_with_expir... | Implement the Python class `SiteConfigurationManagerTests` described below.
Class description:
Unit tests for SiteConfigurationManager.
Method signatures and docstrings:
- def test_check_expired_with_stale_cache(self): Testing SiteConfigurationManager.check_expired with stale cache
- def test_check_expired_with_expir... | 99ea69d80a3a393b0da4da3152ef26e808dd8487 | <|skeleton|>
class SiteConfigurationManagerTests:
"""Unit tests for SiteConfigurationManager."""
def test_check_expired_with_stale_cache(self):
"""Testing SiteConfigurationManager.check_expired with stale cache"""
<|body_0|>
def test_check_expired_with_expired_cache(self):
"""Testi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SiteConfigurationManagerTests:
"""Unit tests for SiteConfigurationManager."""
def test_check_expired_with_stale_cache(self):
"""Testing SiteConfigurationManager.check_expired with stale cache"""
siteconfig1 = SiteConfiguration.objects.get_current()
self.assertFalse(siteconfig1.is_... | the_stack_v2_python_sparse | djblets/siteconfig/tests.py | chipx86/djblets | train | 2 |
38da1f777e88912da5bf93fb89b3631f97a5fd3e | [
"super().__init__(target, opt_level, use_vm)\nself._log_file = log_file\nself._n_trial = n_trial\nself._tuner = tuner\nself._early_stopping = early_stopping\nself._use_transfer_learning = use_transfer_learning\nif isinstance(builder, Dict):\n builder = build_autotvm_builder(builder)\nif isinstance(runner, Dict):... | <|body_start_0|>
super().__init__(target, opt_level, use_vm)
self._log_file = log_file
self._n_trial = n_trial
self._tuner = tuner
self._early_stopping = early_stopping
self._use_transfer_learning = use_transfer_learning
if isinstance(builder, Dict):
b... | AutoTVMTuner | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoTVMTuner:
def __init__(self, target: Union[str, Target], log_file: str, n_trial: int, tuner: Dict, opt_level: int=3, use_vm: bool=False, early_stopping: Optional[int]=None, builder: Union[Dict, Any]=dict(type='LocalBuilder', timeout=10), runner: Union[Dict, Any]=dict(type='LocalRunner', numb... | stack_v2_sparse_classes_36k_train_003093 | 13,280 | permissive | [
{
"docstring": "The AutoTVM tuner. Args: target (Union[str, Target]): The target platform to tune. log_file (str): the log file path. n_trial (int): Maximum number of configs to try. tuner (Dict): The autotvm tuner config. opt_level (int, optional): The optimization level. Defaults to 3. use_vm (bool, optional)... | 3 | null | Implement the Python class `AutoTVMTuner` described below.
Class description:
Implement the AutoTVMTuner class.
Method signatures and docstrings:
- def __init__(self, target: Union[str, Target], log_file: str, n_trial: int, tuner: Dict, opt_level: int=3, use_vm: bool=False, early_stopping: Optional[int]=None, builder... | Implement the Python class `AutoTVMTuner` described below.
Class description:
Implement the AutoTVMTuner class.
Method signatures and docstrings:
- def __init__(self, target: Union[str, Target], log_file: str, n_trial: int, tuner: Dict, opt_level: int=3, use_vm: bool=False, early_stopping: Optional[int]=None, builder... | 5479c8774f5b88d7ed9d399d4e305cb42cc2e73a | <|skeleton|>
class AutoTVMTuner:
def __init__(self, target: Union[str, Target], log_file: str, n_trial: int, tuner: Dict, opt_level: int=3, use_vm: bool=False, early_stopping: Optional[int]=None, builder: Union[Dict, Any]=dict(type='LocalBuilder', timeout=10), runner: Union[Dict, Any]=dict(type='LocalRunner', numb... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutoTVMTuner:
def __init__(self, target: Union[str, Target], log_file: str, n_trial: int, tuner: Dict, opt_level: int=3, use_vm: bool=False, early_stopping: Optional[int]=None, builder: Union[Dict, Any]=dict(type='LocalBuilder', timeout=10), runner: Union[Dict, Any]=dict(type='LocalRunner', number=20, repeat=... | the_stack_v2_python_sparse | mmdeploy/backend/tvm/tuner.py | open-mmlab/mmdeploy | train | 2,164 | |
9d4486e4cdc6a542b74519b0884bc8d7324a2cd1 | [
"super(SlowQueryLogEntry, self).__init__()\nself['query'] = None\nself['query_time'] = None\nself['lock_time'] = None\nself['rows_examined'] = None\nself['rows_sent'] = None",
"param = self.copy()\nparam['clsname'] = self.__class__.__name__\ntry:\n param['datetime'] = param['datetime'].strftime('%Y-%m-%d %H:%M... | <|body_start_0|>
super(SlowQueryLogEntry, self).__init__()
self['query'] = None
self['query_time'] = None
self['lock_time'] = None
self['rows_examined'] = None
self['rows_sent'] = None
<|end_body_0|>
<|body_start_1|>
param = self.copy()
param['clsname'] =... | Class representing an entry of the Slow Query Log SlowQueryLogEntry inherits from LogEntryBase, which inherits from dict. Instances of SlowQueryLogEntry can be used just like dictionaries. | SlowQueryLogEntry | [
"LicenseRef-scancode-free-unknown",
"CC-BY-SA-4.0",
"LicenseRef-scancode-proprietary-license",
"GPL-1.0-or-later",
"MIT",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SlowQueryLogEntry:
"""Class representing an entry of the Slow Query Log SlowQueryLogEntry inherits from LogEntryBase, which inherits from dict. Instances of SlowQueryLogEntry can be used just like dictionaries."""
def __init__(self):
"""Constructor"""
<|body_0|>
def __st... | stack_v2_sparse_classes_36k_train_003094 | 27,243 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "String representation of SlowQueryLogEntry",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | null | Implement the Python class `SlowQueryLogEntry` described below.
Class description:
Class representing an entry of the Slow Query Log SlowQueryLogEntry inherits from LogEntryBase, which inherits from dict. Instances of SlowQueryLogEntry can be used just like dictionaries.
Method signatures and docstrings:
- def __init... | Implement the Python class `SlowQueryLogEntry` described below.
Class description:
Class representing an entry of the Slow Query Log SlowQueryLogEntry inherits from LogEntryBase, which inherits from dict. Instances of SlowQueryLogEntry can be used just like dictionaries.
Method signatures and docstrings:
- def __init... | 2cb4b45dd14a230aa0e800042e893f8dfb23beda | <|skeleton|>
class SlowQueryLogEntry:
"""Class representing an entry of the Slow Query Log SlowQueryLogEntry inherits from LogEntryBase, which inherits from dict. Instances of SlowQueryLogEntry can be used just like dictionaries."""
def __init__(self):
"""Constructor"""
<|body_0|>
def __st... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SlowQueryLogEntry:
"""Class representing an entry of the Slow Query Log SlowQueryLogEntry inherits from LogEntryBase, which inherits from dict. Instances of SlowQueryLogEntry can be used just like dictionaries."""
def __init__(self):
"""Constructor"""
super(SlowQueryLogEntry, self).__init... | the_stack_v2_python_sparse | MY_REPOS/My-Medium-Blog/archive/_SCRAP/gists/parser.py | bgoonz/UsefulResourceRepo2.0 | train | 10 |
98684cecab5835f9a205d111dc364250334865dd | [
"super(L2Norm, self).__init__()\nself.n_dims = n_dims\nself.weight = nn.Parameter(torch.Tensor(self.n_dims))\nself.eps = eps\nself.scale = scale",
"x_float = x.float()\nnorm = x_float.pow(2).sum(1, keepdim=True).sqrt() + self.eps\nreturn (self.weight[None, :, None, None].float().expand_as(x_float) * x_float / nor... | <|body_start_0|>
super(L2Norm, self).__init__()
self.n_dims = n_dims
self.weight = nn.Parameter(torch.Tensor(self.n_dims))
self.eps = eps
self.scale = scale
<|end_body_0|>
<|body_start_1|>
x_float = x.float()
norm = x_float.pow(2).sum(1, keepdim=True).sqrt() + se... | L2Norm | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class L2Norm:
def __init__(self, n_dims, scale=20.0, eps=1e-10):
"""L2 normalization layer. Args: n_dims (int): Number of dimensions to be normalized scale (float, optional): Defaults to 20.. eps (float, optional): Used to avoid division by zero. Defaults to 1e-10."""
<|body_0|>
d... | stack_v2_sparse_classes_36k_train_003095 | 4,901 | permissive | [
{
"docstring": "L2 normalization layer. Args: n_dims (int): Number of dimensions to be normalized scale (float, optional): Defaults to 20.. eps (float, optional): Used to avoid division by zero. Defaults to 1e-10.",
"name": "__init__",
"signature": "def __init__(self, n_dims, scale=20.0, eps=1e-10)"
}... | 2 | stack_v2_sparse_classes_30k_train_013437 | Implement the Python class `L2Norm` described below.
Class description:
Implement the L2Norm class.
Method signatures and docstrings:
- def __init__(self, n_dims, scale=20.0, eps=1e-10): L2 normalization layer. Args: n_dims (int): Number of dimensions to be normalized scale (float, optional): Defaults to 20.. eps (fl... | Implement the Python class `L2Norm` described below.
Class description:
Implement the L2Norm class.
Method signatures and docstrings:
- def __init__(self, n_dims, scale=20.0, eps=1e-10): L2 normalization layer. Args: n_dims (int): Number of dimensions to be normalized scale (float, optional): Defaults to 20.. eps (fl... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class L2Norm:
def __init__(self, n_dims, scale=20.0, eps=1e-10):
"""L2 normalization layer. Args: n_dims (int): Number of dimensions to be normalized scale (float, optional): Defaults to 20.. eps (float, optional): Used to avoid division by zero. Defaults to 1e-10."""
<|body_0|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class L2Norm:
def __init__(self, n_dims, scale=20.0, eps=1e-10):
"""L2 normalization layer. Args: n_dims (int): Number of dimensions to be normalized scale (float, optional): Defaults to 20.. eps (float, optional): Used to avoid division by zero. Defaults to 1e-10."""
super(L2Norm, self).__init__()
... | the_stack_v2_python_sparse | ai/mmdetection/mmdet/models/necks/ssd_neck.py | alldatacenter/alldata | train | 774 | |
a70c6eccd37f38faa2d507ae37e02368f2024281 | [
"args = search_parser.parse_args()\nis_not_valid_input = validate_search_payload(args)\nif is_not_valid_input:\n return is_not_valid_input\nif args['q'] is not None:\n businesses_query = BusinessModel.query.filter(BusinessModel.business_name.ilike('%' + args['q'] + '%'))\nelse:\n businesses_query = Busines... | <|body_start_0|>
args = search_parser.parse_args()
is_not_valid_input = validate_search_payload(args)
if is_not_valid_input:
return is_not_valid_input
if args['q'] is not None:
businesses_query = BusinessModel.query.filter(BusinessModel.business_name.ilike('%' + a... | Class Representing Businesses Endpoints | BusinessList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BusinessList:
"""Class Representing Businesses Endpoints"""
def get(self, current_user, token):
"""returns all businesses in the databases"""
<|body_0|>
def post(self, current_user, token):
"""posts a business"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_003096 | 7,899 | permissive | [
{
"docstring": "returns all businesses in the databases",
"name": "get",
"signature": "def get(self, current_user, token)"
},
{
"docstring": "posts a business",
"name": "post",
"signature": "def post(self, current_user, token)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003718 | Implement the Python class `BusinessList` described below.
Class description:
Class Representing Businesses Endpoints
Method signatures and docstrings:
- def get(self, current_user, token): returns all businesses in the databases
- def post(self, current_user, token): posts a business | Implement the Python class `BusinessList` described below.
Class description:
Class Representing Businesses Endpoints
Method signatures and docstrings:
- def get(self, current_user, token): returns all businesses in the databases
- def post(self, current_user, token): posts a business
<|skeleton|>
class BusinessList... | 6a36b51876479adf99874d91dd0bc765f4839dd6 | <|skeleton|>
class BusinessList:
"""Class Representing Businesses Endpoints"""
def get(self, current_user, token):
"""returns all businesses in the databases"""
<|body_0|>
def post(self, current_user, token):
"""posts a business"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BusinessList:
"""Class Representing Businesses Endpoints"""
def get(self, current_user, token):
"""returns all businesses in the databases"""
args = search_parser.parse_args()
is_not_valid_input = validate_search_payload(args)
if is_not_valid_input:
return is_n... | the_stack_v2_python_sparse | apis/v2/weconnect_api/business_api.py | tibetegya/WeConnect | train | 1 |
704bb574576df2e763201c4db2f5c9c063449b9d | [
"if root is None:\n return '[]'\nresult = ['[', str(root.val)]\nfor child in root.children:\n result.append(self.serialize(child))\nresult.append(']')\nreturn ''.join(result)",
"if data == '[]':\n return None\ni = 1\nnum = 0\nwhile i < len(data) - 1 and data[i].isdigit():\n num = num * 10 + int(data[i... | <|body_start_0|>
if root is None:
return '[]'
result = ['[', str(root.val)]
for child in root.children:
result.append(self.serialize(child))
result.append(']')
return ''.join(result)
<|end_body_0|>
<|body_start_1|>
if data == '[]':
ret... | Codec | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_003097 | 1,567 | permissive | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root: 'Node') -> str"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def des... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | 4ddea0a532fe7c5d053ffbd6870174ec99fc2d60 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
if root is None:
return '[]'
result = ['[', str(root.val)]
for child in root.children:
result.append(self.serialize(child))
res... | the_stack_v2_python_sparse | 0401-0500/0428-Serialize and Deserialize N-ary Tree/0428-Serialize and Deserialize N-ary Tree.py | jiadaizhao/LeetCode | train | 52 | |
28ec64779078f456a17c5e1ccd7c461b993b83d2 | [
"super(_Bottleneck, self).__init__()\nself.in_channels = in_channels\nself.mid_channels = mid_channels\nself.out_channels = out_channels\nself.stride = stride\nself.dilate = dilate\nself.groups = groups\nself.initialW = initialW\nself.bn_kwargs = bn_kwargs\nself.residual_conv = residual_conv\nwith self.init_scope()... | <|body_start_0|>
super(_Bottleneck, self).__init__()
self.in_channels = in_channels
self.mid_channels = mid_channels
self.out_channels = out_channels
self.stride = stride
self.dilate = dilate
self.groups = groups
self.initialW = initialW
self.bn_kw... | Bottleneck in ResNet-v2 with pre-activation setting. | _Bottleneck | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Bottleneck:
"""Bottleneck in ResNet-v2 with pre-activation setting."""
def __init__(self, in_channels, mid_channels, out_channels, stride=1, pad=1, dilate=1, groups=1, initialW=None, bn_kwargs={}, residual_conv=False):
"""CTOR"""
<|body_0|>
def forward(self, x):
... | stack_v2_sparse_classes_36k_train_003098 | 7,508 | permissive | [
{
"docstring": "CTOR",
"name": "__init__",
"signature": "def __init__(self, in_channels, mid_channels, out_channels, stride=1, pad=1, dilate=1, groups=1, initialW=None, bn_kwargs={}, residual_conv=False)"
},
{
"docstring": "forward computation",
"name": "forward",
"signature": "def forwa... | 2 | stack_v2_sparse_classes_30k_test_000078 | Implement the Python class `_Bottleneck` described below.
Class description:
Bottleneck in ResNet-v2 with pre-activation setting.
Method signatures and docstrings:
- def __init__(self, in_channels, mid_channels, out_channels, stride=1, pad=1, dilate=1, groups=1, initialW=None, bn_kwargs={}, residual_conv=False): CTOR... | Implement the Python class `_Bottleneck` described below.
Class description:
Bottleneck in ResNet-v2 with pre-activation setting.
Method signatures and docstrings:
- def __init__(self, in_channels, mid_channels, out_channels, stride=1, pad=1, dilate=1, groups=1, initialW=None, bn_kwargs={}, residual_conv=False): CTOR... | 0ca435433b9953e33656173c4d60ebd61c5c5e87 | <|skeleton|>
class _Bottleneck:
"""Bottleneck in ResNet-v2 with pre-activation setting."""
def __init__(self, in_channels, mid_channels, out_channels, stride=1, pad=1, dilate=1, groups=1, initialW=None, bn_kwargs={}, residual_conv=False):
"""CTOR"""
<|body_0|>
def forward(self, x):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _Bottleneck:
"""Bottleneck in ResNet-v2 with pre-activation setting."""
def __init__(self, in_channels, mid_channels, out_channels, stride=1, pad=1, dilate=1, groups=1, initialW=None, bn_kwargs={}, residual_conv=False):
"""CTOR"""
super(_Bottleneck, self).__init__()
self.in_channe... | the_stack_v2_python_sparse | chainerlp/links/models/resnet_v2.py | MetaVai/gradient-scaling | train | 0 |
a73385757582857689d968ab4ae864af8ef10c2c | [
"visual = ball_game.load_sprite('ball.png')\nboard = ball_game.Board()\nself.assertEqual('<rect(0, 0, 61, 18)>', str(board.get_rect()))\nself.assertEqual('<Sprite sprite(in 0 groups)>', str(board.get_visual()))\nboard.set_limits(5, 10)\nself.assertEqual(5, board.left_limit)\nself.assertEqual(10, board.right_limit)"... | <|body_start_0|>
visual = ball_game.load_sprite('ball.png')
board = ball_game.Board()
self.assertEqual('<rect(0, 0, 61, 18)>', str(board.get_rect()))
self.assertEqual('<Sprite sprite(in 0 groups)>', str(board.get_visual()))
board.set_limits(5, 10)
self.assertEqual(5, boar... | PrimesTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrimesTest:
def test_class_board(self):
"""Method testing the class Board which is controlled by player."""
<|body_0|>
def test_class_ball(self):
"""Method testing the class Ball which is controlled by game logic."""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_003099 | 1,070 | no_license | [
{
"docstring": "Method testing the class Board which is controlled by player.",
"name": "test_class_board",
"signature": "def test_class_board(self)"
},
{
"docstring": "Method testing the class Ball which is controlled by game logic.",
"name": "test_class_ball",
"signature": "def test_cl... | 2 | stack_v2_sparse_classes_30k_train_015533 | Implement the Python class `PrimesTest` described below.
Class description:
Implement the PrimesTest class.
Method signatures and docstrings:
- def test_class_board(self): Method testing the class Board which is controlled by player.
- def test_class_ball(self): Method testing the class Ball which is controlled by ga... | Implement the Python class `PrimesTest` described below.
Class description:
Implement the PrimesTest class.
Method signatures and docstrings:
- def test_class_board(self): Method testing the class Board which is controlled by player.
- def test_class_ball(self): Method testing the class Ball which is controlled by ga... | d1930cd345c656e774e960696037bdba11a4e9c1 | <|skeleton|>
class PrimesTest:
def test_class_board(self):
"""Method testing the class Board which is controlled by player."""
<|body_0|>
def test_class_ball(self):
"""Method testing the class Ball which is controlled by game logic."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrimesTest:
def test_class_board(self):
"""Method testing the class Board which is controlled by player."""
visual = ball_game.load_sprite('ball.png')
board = ball_game.Board()
self.assertEqual('<rect(0, 0, 61, 18)>', str(board.get_rect()))
self.assertEqual('<Sprite spr... | the_stack_v2_python_sparse | classes_test.py | PROPERAT/pyCue | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.