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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f3ce86b52355c19f611785358d90e63a6a46c8eb | [
"mineral_field = self.state.mineral_field\nif mineral_field:\n close_points = range(-11, 12)\n center_position = center.position\n add_positions = self.building_positions.append\n viable_points = [point for point in (Point2((x + center_position.x, y + center_position.y)) for x in close_points for y in c... | <|body_start_0|>
mineral_field = self.state.mineral_field
if mineral_field:
close_points = range(-11, 12)
center_position = center.position
add_positions = self.building_positions.append
viable_points = [point for point in (Point2((x + center_position.x, y... | Ok for now | BuildingPositioning | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BuildingPositioning:
"""Ok for now"""
async def prepare_building_positions(self, center):
"""Check all possible positions behind the mineral line when a hatchery is built"""
<|body_0|>
async def get_production_position(self):
"""Find the safest position looping t... | stack_v2_sparse_classes_36k_train_011400 | 2,516 | permissive | [
{
"docstring": "Check all possible positions behind the mineral line when a hatchery is built",
"name": "prepare_building_positions",
"signature": "async def prepare_building_positions(self, center)"
},
{
"docstring": "Find the safest position looping through all possible ones",
"name": "get... | 2 | null | Implement the Python class `BuildingPositioning` described below.
Class description:
Ok for now
Method signatures and docstrings:
- async def prepare_building_positions(self, center): Check all possible positions behind the mineral line when a hatchery is built
- async def get_production_position(self): Find the safe... | Implement the Python class `BuildingPositioning` described below.
Class description:
Ok for now
Method signatures and docstrings:
- async def prepare_building_positions(self, center): Check all possible positions behind the mineral line when a hatchery is built
- async def get_production_position(self): Find the safe... | 345df784098cb9eb055b3901fe7455807c58a4e1 | <|skeleton|>
class BuildingPositioning:
"""Ok for now"""
async def prepare_building_positions(self, center):
"""Check all possible positions behind the mineral line when a hatchery is built"""
<|body_0|>
async def get_production_position(self):
"""Find the safest position looping t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BuildingPositioning:
"""Ok for now"""
async def prepare_building_positions(self, center):
"""Check all possible positions behind the mineral line when a hatchery is built"""
mineral_field = self.state.mineral_field
if mineral_field:
close_points = range(-11, 12)
... | the_stack_v2_python_sparse | actions/macro/building_positioning.py | drakonnan1st/JackBot | train | 0 |
fa4e99b78515dc081319c1bdd6bb716e9d53dbe8 | [
"logged_in_user = token_verification.verify_tokens()\ngeneral_helper_functions.abort_user_if_not_admin(logged_in_user)\ndata = request.get_json()\ngeneral_helper_functions.json_null_request(data)\ntry:\n name = data['name']\n price = data['price']\n min_quantity = data['min_quantity']\n inventory = data... | <|body_start_0|>
logged_in_user = token_verification.verify_tokens()
general_helper_functions.abort_user_if_not_admin(logged_in_user)
data = request.get_json()
general_helper_functions.json_null_request(data)
try:
name = data['name']
price = data['price']
... | Simple class that holds the products endpoints | Products | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Products:
"""Simple class that holds the products endpoints"""
def post(self):
"""POST /products endpoint"""
<|body_0|>
def get(self):
"""GET /products retrieves all products"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
logged_in_user = token... | stack_v2_sparse_classes_36k_train_011401 | 5,144 | no_license | [
{
"docstring": "POST /products endpoint",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "GET /products retrieves all products",
"name": "get",
"signature": "def get(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015919 | Implement the Python class `Products` described below.
Class description:
Simple class that holds the products endpoints
Method signatures and docstrings:
- def post(self): POST /products endpoint
- def get(self): GET /products retrieves all products | Implement the Python class `Products` described below.
Class description:
Simple class that holds the products endpoints
Method signatures and docstrings:
- def post(self): POST /products endpoint
- def get(self): GET /products retrieves all products
<|skeleton|>
class Products:
"""Simple class that holds the pr... | 944173cf41648ea218fd8440c3741939d9cd2754 | <|skeleton|>
class Products:
"""Simple class that holds the products endpoints"""
def post(self):
"""POST /products endpoint"""
<|body_0|>
def get(self):
"""GET /products retrieves all products"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Products:
"""Simple class that holds the products endpoints"""
def post(self):
"""POST /products endpoint"""
logged_in_user = token_verification.verify_tokens()
general_helper_functions.abort_user_if_not_admin(logged_in_user)
data = request.get_json()
general_helpe... | the_stack_v2_python_sparse | app/api/v2/views/products.py | TooColline/Store-Manager-Api-V2 | train | 1 |
1407a1406d8f1f1aa6b85954f9263abc181dae20 | [
"super(SRTM, self).__init__(site, **kwargs)\nif math.fabs(self.site.ul_lonlat[1]) > 60 or math.fabs(self.site.lr_lonlat[1]) > 60:\n raise ValueError('Latitude over +-60deg - No SRTM data available!')\nself.srtm_codes = self.get_srtm_codes(self.site)\nif not self.dem_version:\n self.dem_version = 1001",
"fil... | <|body_start_0|>
super(SRTM, self).__init__(site, **kwargs)
if math.fabs(self.site.ul_lonlat[1]) > 60 or math.fabs(self.site.lr_lonlat[1]) > 60:
raise ValueError('Latitude over +-60deg - No SRTM data available!')
self.srtm_codes = self.get_srtm_codes(self.site)
if not self.de... | Base class to get an SRTM DEM/MNT for a given site. | SRTM | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SRTM:
"""Base class to get an SRTM DEM/MNT for a given site."""
def __init__(self, site, **kwargs):
"""Initialise an SRTM-type DEM. :param site: The :class:`prepare_mnt.mnt.SiteInfo` struct containing the basic information. :param kwargs: Forwarded parameters to :class:`prepare_mnt.m... | stack_v2_sparse_classes_36k_train_011402 | 4,554 | permissive | [
{
"docstring": "Initialise an SRTM-type DEM. :param site: The :class:`prepare_mnt.mnt.SiteInfo` struct containing the basic information. :param kwargs: Forwarded parameters to :class:`prepare_mnt.mnt.MNTBase`",
"name": "__init__",
"signature": "def __init__(self, site, **kwargs)"
},
{
"docstring... | 4 | null | Implement the Python class `SRTM` described below.
Class description:
Base class to get an SRTM DEM/MNT for a given site.
Method signatures and docstrings:
- def __init__(self, site, **kwargs): Initialise an SRTM-type DEM. :param site: The :class:`prepare_mnt.mnt.SiteInfo` struct containing the basic information. :pa... | Implement the Python class `SRTM` described below.
Class description:
Base class to get an SRTM DEM/MNT for a given site.
Method signatures and docstrings:
- def __init__(self, site, **kwargs): Initialise an SRTM-type DEM. :param site: The :class:`prepare_mnt.mnt.SiteInfo` struct containing the basic information. :pa... | 9688780f8dd8244e60603e1f11385e1fadc90cb4 | <|skeleton|>
class SRTM:
"""Base class to get an SRTM DEM/MNT for a given site."""
def __init__(self, site, **kwargs):
"""Initialise an SRTM-type DEM. :param site: The :class:`prepare_mnt.mnt.SiteInfo` struct containing the basic information. :param kwargs: Forwarded parameters to :class:`prepare_mnt.m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SRTM:
"""Base class to get an SRTM DEM/MNT for a given site."""
def __init__(self, site, **kwargs):
"""Initialise an SRTM-type DEM. :param site: The :class:`prepare_mnt.mnt.SiteInfo` struct containing the basic information. :param kwargs: Forwarded parameters to :class:`prepare_mnt.mnt.MNTBase`""... | the_stack_v2_python_sparse | StartMaja/prepare_mnt/mnt/SRTM.py | alexgoussev/maja_gitlab | train | 0 |
f4390148ca2a74b34541e1e09af395c607b3f6ef | [
"self._tub = tub\nself._num_records = num_records\nself._active_loop = False",
"if is_delete:\n if not self._active_loop:\n self._tub.delete_last_n_records(self._num_records)\n self._active_loop = True\nelse:\n self._active_loop = False"
] | <|body_start_0|>
self._tub = tub
self._num_records = num_records
self._active_loop = False
<|end_body_0|>
<|body_start_1|>
if is_delete:
if not self._active_loop:
self._tub.delete_last_n_records(self._num_records)
self._active_loop = True
... | Donkey part which deletes a bunch of records from the end of tub. This allows to remove bad data already during recording. As this gets called in the vehicle loop the deletion runs only once in each continuous activation. A new execution requires to release of the input trigger. The action could result in a multiple nu... | TubWiper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TubWiper:
"""Donkey part which deletes a bunch of records from the end of tub. This allows to remove bad data already during recording. As this gets called in the vehicle loop the deletion runs only once in each continuous activation. A new execution requires to release of the input trigger. The ... | stack_v2_sparse_classes_36k_train_011403 | 6,381 | permissive | [
{
"docstring": ":param tub: tub to operate on :param num_records: number or records to delete",
"name": "__init__",
"signature": "def __init__(self, tub, num_records=20)"
},
{
"docstring": "Method in the vehicle loop. Delete records when trigger switches from False to True only. :param is_delete... | 2 | stack_v2_sparse_classes_30k_train_005696 | Implement the Python class `TubWiper` described below.
Class description:
Donkey part which deletes a bunch of records from the end of tub. This allows to remove bad data already during recording. As this gets called in the vehicle loop the deletion runs only once in each continuous activation. A new execution require... | Implement the Python class `TubWiper` described below.
Class description:
Donkey part which deletes a bunch of records from the end of tub. This allows to remove bad data already during recording. As this gets called in the vehicle loop the deletion runs only once in each continuous activation. A new execution require... | 9f91ad1aaff054522b24c2c1e727d1a111e266f4 | <|skeleton|>
class TubWiper:
"""Donkey part which deletes a bunch of records from the end of tub. This allows to remove bad data already during recording. As this gets called in the vehicle loop the deletion runs only once in each continuous activation. A new execution requires to release of the input trigger. The ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TubWiper:
"""Donkey part which deletes a bunch of records from the end of tub. This allows to remove bad data already during recording. As this gets called in the vehicle loop the deletion runs only once in each continuous activation. A new execution requires to release of the input trigger. The action could ... | the_stack_v2_python_sparse | donkeycar/parts/tub_v2.py | autorope/donkeycar | train | 1,861 |
a4cb066a6f50340b2d4a171e26743012817b3a1a | [
"self.mainframe = parent\nwx.Frame.__init__(self, parent, title=title, size=(400, 250))\nself.panel = wx.Panel(self, pos=(0, 0), size=(400, 250))\nself.panel.SetBackgroundColour('#FFFFFF')\nbookName_tip = wx.StaticText(self.panel, label='书名:', pos=(5, 8), size=(35, 25))\nbookName_tip.SetBackgroundColour('#FFFFFF')\... | <|body_start_0|>
self.mainframe = parent
wx.Frame.__init__(self, parent, title=title, size=(400, 250))
self.panel = wx.Panel(self, pos=(0, 0), size=(400, 250))
self.panel.SetBackgroundColour('#FFFFFF')
bookName_tip = wx.StaticText(self.panel, label='书名:', pos=(5, 8), size=(35, 25... | 用来显示书籍的信息 | ShowFrame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShowFrame:
"""用来显示书籍的信息"""
def __init__(self, parent, title, select_id):
"""初始化该小窗口的布局"""
<|body_0|>
def showAllText(self):
"""显示概述本原始信息"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.mainframe = parent
wx.Frame.__init__(self, pare... | stack_v2_sparse_classes_36k_train_011404 | 13,549 | no_license | [
{
"docstring": "初始化该小窗口的布局",
"name": "__init__",
"signature": "def __init__(self, parent, title, select_id)"
},
{
"docstring": "显示概述本原始信息",
"name": "showAllText",
"signature": "def showAllText(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005456 | Implement the Python class `ShowFrame` described below.
Class description:
用来显示书籍的信息
Method signatures and docstrings:
- def __init__(self, parent, title, select_id): 初始化该小窗口的布局
- def showAllText(self): 显示概述本原始信息 | Implement the Python class `ShowFrame` described below.
Class description:
用来显示书籍的信息
Method signatures and docstrings:
- def __init__(self, parent, title, select_id): 初始化该小窗口的布局
- def showAllText(self): 显示概述本原始信息
<|skeleton|>
class ShowFrame:
"""用来显示书籍的信息"""
def __init__(self, parent, title, select_id):
... | e19c56fb353e9bc961a568da41dedba6ae6aa05f | <|skeleton|>
class ShowFrame:
"""用来显示书籍的信息"""
def __init__(self, parent, title, select_id):
"""初始化该小窗口的布局"""
<|body_0|>
def showAllText(self):
"""显示概述本原始信息"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShowFrame:
"""用来显示书籍的信息"""
def __init__(self, parent, title, select_id):
"""初始化该小窗口的布局"""
self.mainframe = parent
wx.Frame.__init__(self, parent, title=title, size=(400, 250))
self.panel = wx.Panel(self, pos=(0, 0), size=(400, 250))
self.panel.SetBackgroundColour('... | the_stack_v2_python_sparse | SXB/venv/Tkinter-master/t3.py | sh2268411762/Python_Three | train | 1 |
da50f22afea10eb52aa6d948742c228c14e2bc67 | [
"self.delete_snapshots = delete_snapshots\nself.protection_source_id = protection_source_id\nself.rpo_policy_id = rpo_policy_id",
"if dictionary is None:\n return None\ndelete_snapshots = dictionary.get('deleteSnapshots')\nprotection_source_id = dictionary.get('protectionSourceId')\nrpo_policy_id = dictionary.... | <|body_start_0|>
self.delete_snapshots = delete_snapshots
self.protection_source_id = protection_source_id
self.rpo_policy_id = rpo_policy_id
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
delete_snapshots = dictionary.get('deleteSnapshots')
... | Implementation of the 'UnprotectObjectParams' model. Specifies the parameters to unprotect an object. Attributes: delete_snapshots (bool): Specifies whether to delete the snapshots of the Protection Object. protection_source_id (long|int, required): Specifies the id of the Protection Source to be unprotected. rpo_polic... | UnprotectObjectParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnprotectObjectParams:
"""Implementation of the 'UnprotectObjectParams' model. Specifies the parameters to unprotect an object. Attributes: delete_snapshots (bool): Specifies whether to delete the snapshots of the Protection Object. protection_source_id (long|int, required): Specifies the id of t... | stack_v2_sparse_classes_36k_train_011405 | 2,158 | permissive | [
{
"docstring": "Constructor for the UnprotectObjectParams class",
"name": "__init__",
"signature": "def __init__(self, delete_snapshots=None, protection_source_id=None, rpo_policy_id=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A di... | 2 | null | Implement the Python class `UnprotectObjectParams` described below.
Class description:
Implementation of the 'UnprotectObjectParams' model. Specifies the parameters to unprotect an object. Attributes: delete_snapshots (bool): Specifies whether to delete the snapshots of the Protection Object. protection_source_id (lon... | Implement the Python class `UnprotectObjectParams` described below.
Class description:
Implementation of the 'UnprotectObjectParams' model. Specifies the parameters to unprotect an object. Attributes: delete_snapshots (bool): Specifies whether to delete the snapshots of the Protection Object. protection_source_id (lon... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class UnprotectObjectParams:
"""Implementation of the 'UnprotectObjectParams' model. Specifies the parameters to unprotect an object. Attributes: delete_snapshots (bool): Specifies whether to delete the snapshots of the Protection Object. protection_source_id (long|int, required): Specifies the id of t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnprotectObjectParams:
"""Implementation of the 'UnprotectObjectParams' model. Specifies the parameters to unprotect an object. Attributes: delete_snapshots (bool): Specifies whether to delete the snapshots of the Protection Object. protection_source_id (long|int, required): Specifies the id of the Protection... | the_stack_v2_python_sparse | cohesity_management_sdk/models/unprotect_object_params.py | cohesity/management-sdk-python | train | 24 |
706ce40d5d8b3a9f27e80e9314b0219b28e489db | [
"self.nums = nums\nself.size = len(nums)\nself.dp = [[0] * len(nums)] * len(nums)\nif nums:\n self.dp[0][0] = nums[0]\n for m in range(1, self.size):\n self.dp[0][m] = self.dp[0][m - 1] + self.nums[m]",
"if not self.nums:\n return 0\nreturn self.dp[0][j] if i == 0 else self.dp[0][j] - self.dp[0][i... | <|body_start_0|>
self.nums = nums
self.size = len(nums)
self.dp = [[0] * len(nums)] * len(nums)
if nums:
self.dp[0][0] = nums[0]
for m in range(1, self.size):
self.dp[0][m] = self.dp[0][m - 1] + self.nums[m]
<|end_body_0|>
<|body_start_1|>
... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.nums = nums
self.size = len(nums)
self... | stack_v2_sparse_classes_36k_train_011406 | 760 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, i, j)"
}
] | 2 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int
<|skeleton|>
class NumArray:
def __init__(self, nums):
... | 2f46f85e1e297b0a50fdb66956b1d05622a4063d | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self.nums = nums
self.size = len(nums)
self.dp = [[0] * len(nums)] * len(nums)
if nums:
self.dp[0][0] = nums[0]
for m in range(1, self.size):
self.dp[0][m] = self.dp[... | the_stack_v2_python_sparse | dan/Problems/Easy/dp/303. Range Sum Query - Immutable/solution.py | xudaaaaan/Leetcode | train | 0 | |
618b529d4ad878940a03c6cdc5dbcfce6cfb014e | [
"self.zamg = ZamgDevice(session=async_get_clientsession(hass))\nself.zamg.set_default_station(entry.data[CONF_STATION_ID])\nsuper().__init__(hass, LOGGER, name=DOMAIN, update_interval=MIN_TIME_BETWEEN_UPDATES)",
"try:\n if self.api_fields:\n self.zamg.set_parameters(self.api_fields)\n self.zamg.reque... | <|body_start_0|>
self.zamg = ZamgDevice(session=async_get_clientsession(hass))
self.zamg.set_default_station(entry.data[CONF_STATION_ID])
super().__init__(hass, LOGGER, name=DOMAIN, update_interval=MIN_TIME_BETWEEN_UPDATES)
<|end_body_0|>
<|body_start_1|>
try:
if self.api_fi... | Class to manage fetching ZAMG weather data. | ZamgDataUpdateCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZamgDataUpdateCoordinator:
"""Class to manage fetching ZAMG weather data."""
def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry) -> None:
"""Initialize global ZAMG data updater."""
<|body_0|>
async def _async_update_data(self) -> ZamgDevice:
"""Fetch d... | stack_v2_sparse_classes_36k_train_011407 | 1,868 | permissive | [
{
"docstring": "Initialize global ZAMG data updater.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry) -> None"
},
{
"docstring": "Fetch data from ZAMG api.",
"name": "_async_update_data",
"signature": "async def _async_update_data(self) -... | 2 | stack_v2_sparse_classes_30k_train_001340 | Implement the Python class `ZamgDataUpdateCoordinator` described below.
Class description:
Class to manage fetching ZAMG weather data.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry) -> None: Initialize global ZAMG data updater.
- async def _async_update_data(self) -... | Implement the Python class `ZamgDataUpdateCoordinator` described below.
Class description:
Class to manage fetching ZAMG weather data.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry) -> None: Initialize global ZAMG data updater.
- async def _async_update_data(self) -... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ZamgDataUpdateCoordinator:
"""Class to manage fetching ZAMG weather data."""
def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry) -> None:
"""Initialize global ZAMG data updater."""
<|body_0|>
async def _async_update_data(self) -> ZamgDevice:
"""Fetch d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZamgDataUpdateCoordinator:
"""Class to manage fetching ZAMG weather data."""
def __init__(self, hass: HomeAssistant, *, entry: ConfigEntry) -> None:
"""Initialize global ZAMG data updater."""
self.zamg = ZamgDevice(session=async_get_clientsession(hass))
self.zamg.set_default_stati... | the_stack_v2_python_sparse | homeassistant/components/zamg/coordinator.py | home-assistant/core | train | 35,501 |
b5972ef8dd652525f3c5872fdeda865bac35af64 | [
"for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n if nums[i] == nums[j]:\n return nums[i]",
"res = []\nfor i in range(len(nums)):\n if nums[i] not in res:\n res.append(nums[i])\n else:\n return nums[i]",
"i = 0\nwhile i < len(nums):\n if nums[i] == i:\... | <|body_start_0|>
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] == nums[j]:
return nums[i]
<|end_body_0|>
<|body_start_1|>
res = []
for i in range(len(nums)):
if nums[i] not in res:
res.append(n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findRepeatNumber(self, nums: List[int]) -> int:
"""找到任意个重复的数组即可,首先可以暴力遍历 但是暴力遍历肯定会存在内存溢出的问题,即超时"""
<|body_0|>
def findRepeatNumber1(self, nums: List[int]) -> int:
"""暴力遍历肯定不可取, 下面想新的办法 由于只需要找到数组中任意一个重复的数字,因此遍历数组,遇到重复的数字即返回 为了判断一个数字是否重复遇到,使用列表存储已经遇到的数字,如... | stack_v2_sparse_classes_36k_train_011408 | 4,455 | no_license | [
{
"docstring": "找到任意个重复的数组即可,首先可以暴力遍历 但是暴力遍历肯定会存在内存溢出的问题,即超时",
"name": "findRepeatNumber",
"signature": "def findRepeatNumber(self, nums: List[int]) -> int"
},
{
"docstring": "暴力遍历肯定不可取, 下面想新的办法 由于只需要找到数组中任意一个重复的数字,因此遍历数组,遇到重复的数字即返回 为了判断一个数字是否重复遇到,使用列表存储已经遇到的数字,如果遇到数字已经在 列表里面,则当前数字是重复数字 初始化列表为空列... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findRepeatNumber(self, nums: List[int]) -> int: 找到任意个重复的数组即可,首先可以暴力遍历 但是暴力遍历肯定会存在内存溢出的问题,即超时
- def findRepeatNumber1(self, nums: List[int]) -> int: 暴力遍历肯定不可取, 下面想新的办法 由于只需要找到... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findRepeatNumber(self, nums: List[int]) -> int: 找到任意个重复的数组即可,首先可以暴力遍历 但是暴力遍历肯定会存在内存溢出的问题,即超时
- def findRepeatNumber1(self, nums: List[int]) -> int: 暴力遍历肯定不可取, 下面想新的办法 由于只需要找到... | 51943e2c2c4ec70c7c1d5b53c9fdf0a719428d7a | <|skeleton|>
class Solution:
def findRepeatNumber(self, nums: List[int]) -> int:
"""找到任意个重复的数组即可,首先可以暴力遍历 但是暴力遍历肯定会存在内存溢出的问题,即超时"""
<|body_0|>
def findRepeatNumber1(self, nums: List[int]) -> int:
"""暴力遍历肯定不可取, 下面想新的办法 由于只需要找到数组中任意一个重复的数字,因此遍历数组,遇到重复的数字即返回 为了判断一个数字是否重复遇到,使用列表存储已经遇到的数字,如... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findRepeatNumber(self, nums: List[int]) -> int:
"""找到任意个重复的数组即可,首先可以暴力遍历 但是暴力遍历肯定会存在内存溢出的问题,即超时"""
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] == nums[j]:
return nums[i]
def findRepeatNumber1(self, n... | the_stack_v2_python_sparse | 剑指offer/PythonVersion/03_数组中重复的数字.py | LeBron-Jian/BasicAlgorithmPractice | train | 13 | |
fbb7a5d004d83daf7fda015705aa5d324a4a5753 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn FileAssessmentRequest()",
"from .threat_assessment_request import ThreatAssessmentRequest\nfrom .threat_assessment_request import ThreatAssessmentRequest\nfields: Dict[str, Callable[[Any], None]] = {'contentData': lambda n: setattr(sel... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return FileAssessmentRequest()
<|end_body_0|>
<|body_start_1|>
from .threat_assessment_request import ThreatAssessmentRequest
from .threat_assessment_request import ThreatAssessmentRequest
... | FileAssessmentRequest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileAssessmentRequest:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FileAssessmentRequest:
"""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 th... | stack_v2_sparse_classes_36k_train_011409 | 2,451 | 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: FileAssessmentRequest",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminat... | 3 | null | Implement the Python class `FileAssessmentRequest` described below.
Class description:
Implement the FileAssessmentRequest class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FileAssessmentRequest: Creates a new instance of the appropriate class base... | Implement the Python class `FileAssessmentRequest` described below.
Class description:
Implement the FileAssessmentRequest class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FileAssessmentRequest: Creates a new instance of the appropriate class base... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class FileAssessmentRequest:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FileAssessmentRequest:
"""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 th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileAssessmentRequest:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FileAssessmentRequest:
"""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 Retur... | the_stack_v2_python_sparse | msgraph/generated/models/file_assessment_request.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
68aacf10881d2e2aebd61fbd1dccb81fbcd94c01 | [
"super().__init__(url=url + URL_SUFFIX + '/create')\nself.type_ = type_\nself.permissions = permissions\nself.user_id = user_id\nself.group_id = group_id\nself.resource_type = resource_type\nself.resource_id = resource_id",
"assert (self.user_id is not None) != (self.group_id is not None), \"Either 'user_id' or '... | <|body_start_0|>
super().__init__(url=url + URL_SUFFIX + '/create')
self.type_ = type_
self.permissions = permissions
self.user_id = user_id
self.group_id = group_id
self.resource_type = resource_type
self.resource_id = resource_id
<|end_body_0|>
<|body_start_1|>... | Create | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Create:
def __init__(self, url: str, type_: typing.Union[int, AuthorizationType], permissions: typing.Iterable[str], resource_type: typing.Union[str, pycamunda.resource.ResourceType], resource_id: str, user_id: str=None, group_id: str=None):
"""Create an auth. :param url: Camunda Rest en... | stack_v2_sparse_classes_36k_train_011410 | 14,505 | permissive | [
{
"docstring": "Create an auth. :param url: Camunda Rest engine URL. :param type_: Id of the authorization. :param permissions: Permissions provided by this authorization. A permission be 'READ' or 'CREATE' for example. :param user_id: Id of the user this authorization is for. The value '*' means all users. :pa... | 2 | stack_v2_sparse_classes_30k_train_005120 | Implement the Python class `Create` described below.
Class description:
Implement the Create class.
Method signatures and docstrings:
- def __init__(self, url: str, type_: typing.Union[int, AuthorizationType], permissions: typing.Iterable[str], resource_type: typing.Union[str, pycamunda.resource.ResourceType], resour... | Implement the Python class `Create` described below.
Class description:
Implement the Create class.
Method signatures and docstrings:
- def __init__(self, url: str, type_: typing.Union[int, AuthorizationType], permissions: typing.Iterable[str], resource_type: typing.Union[str, pycamunda.resource.ResourceType], resour... | 3faac4037212df139d415ee1a54a6594ae5e9ac5 | <|skeleton|>
class Create:
def __init__(self, url: str, type_: typing.Union[int, AuthorizationType], permissions: typing.Iterable[str], resource_type: typing.Union[str, pycamunda.resource.ResourceType], resource_id: str, user_id: str=None, group_id: str=None):
"""Create an auth. :param url: Camunda Rest en... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Create:
def __init__(self, url: str, type_: typing.Union[int, AuthorizationType], permissions: typing.Iterable[str], resource_type: typing.Union[str, pycamunda.resource.ResourceType], resource_id: str, user_id: str=None, group_id: str=None):
"""Create an auth. :param url: Camunda Rest engine URL. :par... | the_stack_v2_python_sparse | pycamunda/auth.py | pklauke/pycamunda | train | 40 | |
54bdef9c33cbf106f165a9a24ef14b18ef6db9dc | [
"digits_strs = [str(d) for d in digits]\nnum_str = ''.join(digits_strs)\nnum = int(num_str)\nnum += 1\nnum_str = str(num)\ni = 0\nprint(num_str)\nfor ns in num_str:\n digits[i] = int(ns)\n i += 1\nprint(digits)",
"i = len(digits) - 1\nwhile i >= 0:\n digits[i] += 1\n digits[i] %= 10\n if digits[i] ... | <|body_start_0|>
digits_strs = [str(d) for d in digits]
num_str = ''.join(digits_strs)
num = int(num_str)
num += 1
num_str = str(num)
i = 0
print(num_str)
for ns in num_str:
digits[i] = int(ns)
i += 1
print(digits)
<|end_bod... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def plus_one(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_0|>
def plus_one2(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
digits_strs = [str(d) for d in... | stack_v2_sparse_classes_36k_train_011411 | 1,658 | no_license | [
{
"docstring": ":type digits: List[int] :rtype: List[int]",
"name": "plus_one",
"signature": "def plus_one(self, digits)"
},
{
"docstring": ":type digits: List[int] :rtype: List[int]",
"name": "plus_one2",
"signature": "def plus_one2(self, digits)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def plus_one(self, digits): :type digits: List[int] :rtype: List[int]
- def plus_one2(self, digits): :type digits: List[int] :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def plus_one(self, digits): :type digits: List[int] :rtype: List[int]
- def plus_one2(self, digits): :type digits: List[int] :rtype: List[int]
<|skeleton|>
class Solution:
... | 3b13b36f37eb364410b3b5b4f10a1808d8b1111e | <|skeleton|>
class Solution:
def plus_one(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_0|>
def plus_one2(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def plus_one(self, digits):
""":type digits: List[int] :rtype: List[int]"""
digits_strs = [str(d) for d in digits]
num_str = ''.join(digits_strs)
num = int(num_str)
num += 1
num_str = str(num)
i = 0
print(num_str)
for ns in num_... | the_stack_v2_python_sparse | leetcode/66.py | yanggelinux/algorithm-data-structure | train | 0 | |
ea2d2b274ea793eced5751654c092d8b3f1591a1 | [
"for mission in self.browse(cr, uid, ids, context=context):\n fuel_request_obj = self.pool.get('fleet.vehicle.log.fuel')\n if mission.transport in ('1', '4') and (not mission.fuel_requested):\n info = 'Mission:\\t' + mission.name + '\\nStart date:\\t' + mission.start_date + ' - End date:\\t' + mission.... | <|body_start_0|>
for mission in self.browse(cr, uid, ids, context=context):
fuel_request_obj = self.pool.get('fleet.vehicle.log.fuel')
if mission.transport in ('1', '4') and (not mission.fuel_requested):
info = 'Mission:\t' + mission.name + '\nStart date:\t' + mission.sta... | To manage employee_missions | employee_missions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class employee_missions:
"""To manage employee_missions"""
def request_fuel(self, cr, uid, ids, context=None):
"""Request fuel and car for mission from mission if the transport type is car. @param ids: :List of id of mission @return: True or False"""
<|body_0|>
def mission_app... | stack_v2_sparse_classes_36k_train_011412 | 5,079 | no_license | [
{
"docstring": "Request fuel and car for mission from mission if the transport type is car. @param ids: :List of id of mission @return: True or False",
"name": "request_fuel",
"signature": "def request_fuel(self, cr, uid, ids, context=None)"
},
{
"docstring": "Workflow method change record state... | 2 | stack_v2_sparse_classes_30k_train_008755 | Implement the Python class `employee_missions` described below.
Class description:
To manage employee_missions
Method signatures and docstrings:
- def request_fuel(self, cr, uid, ids, context=None): Request fuel and car for mission from mission if the transport type is car. @param ids: :List of id of mission @return:... | Implement the Python class `employee_missions` described below.
Class description:
To manage employee_missions
Method signatures and docstrings:
- def request_fuel(self, cr, uid, ids, context=None): Request fuel and car for mission from mission if the transport type is car. @param ids: :List of id of mission @return:... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class employee_missions:
"""To manage employee_missions"""
def request_fuel(self, cr, uid, ids, context=None):
"""Request fuel and car for mission from mission if the transport type is car. @param ids: :List of id of mission @return: True or False"""
<|body_0|>
def mission_app... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class employee_missions:
"""To manage employee_missions"""
def request_fuel(self, cr, uid, ids, context=None):
"""Request fuel and car for mission from mission if the transport type is car. @param ids: :List of id of mission @return: True or False"""
for mission in self.browse(cr, uid, ids, con... | the_stack_v2_python_sparse | v_7/Dongola/ntc/fuel_request_ntc/fuel_request.py | musabahmed/baba | train | 0 |
2592d9fdce78a4314e2c8cef8c791e4ddee155bc | [
"logger.info('initializing RBF kernel')\nself.d = int(d)\nself.n_rffs = int(n_rffs)\nself.n_features = 2 * n_rffs\nself.dtype = dtype\nself.freq_weights = np.asarray(np.random.normal(size=(self.d, self.n_rffs), loc=0, scale=1.0), dtype=self.dtype)\nself.bf_scale = 1.0 / np.sqrt(self.n_rffs)\nif np.size(log_lengthsc... | <|body_start_0|>
logger.info('initializing RBF kernel')
self.d = int(d)
self.n_rffs = int(n_rffs)
self.n_features = 2 * n_rffs
self.dtype = dtype
self.freq_weights = np.asarray(np.random.normal(size=(self.d, self.n_rffs), loc=0, scale=1.0), dtype=self.dtype)
self.... | random fourier features for an RBF kernel | RBF_RFF | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RBF_RFF:
"""random fourier features for an RBF kernel"""
def __init__(self, d, log_lengthscale=0, n_rffs=1000, dtype=np.float64, tune_len=True):
"""squared exponential kernel Input: d : number of input dims n_rffs : number of random features (will actually used twice this value)"""
... | stack_v2_sparse_classes_36k_train_011413 | 1,789 | no_license | [
{
"docstring": "squared exponential kernel Input: d : number of input dims n_rffs : number of random features (will actually used twice this value)",
"name": "__init__",
"signature": "def __init__(self, d, log_lengthscale=0, n_rffs=1000, dtype=np.float64, tune_len=True)"
},
{
"docstring": "Get t... | 2 | stack_v2_sparse_classes_30k_train_003797 | Implement the Python class `RBF_RFF` described below.
Class description:
random fourier features for an RBF kernel
Method signatures and docstrings:
- def __init__(self, d, log_lengthscale=0, n_rffs=1000, dtype=np.float64, tune_len=True): squared exponential kernel Input: d : number of input dims n_rffs : number of r... | Implement the Python class `RBF_RFF` described below.
Class description:
random fourier features for an RBF kernel
Method signatures and docstrings:
- def __init__(self, d, log_lengthscale=0, n_rffs=1000, dtype=np.float64, tune_len=True): squared exponential kernel Input: d : number of input dims n_rffs : number of r... | 1bed882b8a94ee58fd0bde6920ee85f81ffb77bb | <|skeleton|>
class RBF_RFF:
"""random fourier features for an RBF kernel"""
def __init__(self, d, log_lengthscale=0, n_rffs=1000, dtype=np.float64, tune_len=True):
"""squared exponential kernel Input: d : number of input dims n_rffs : number of random features (will actually used twice this value)"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RBF_RFF:
"""random fourier features for an RBF kernel"""
def __init__(self, d, log_lengthscale=0, n_rffs=1000, dtype=np.float64, tune_len=True):
"""squared exponential kernel Input: d : number of input dims n_rffs : number of random features (will actually used twice this value)"""
logger... | the_stack_v2_python_sparse | gp_grief/kern/rbf_rff.py | scwolof/gp_grief | train | 2 |
1df6fd0eaa3e0368594eaedbcedd65f56d7dffb1 | [
"if not nums or k < 1 or k > len(nums):\n return None\nl, r, n = (0, len(nums) - 1, len(nums))\nwhile l <= r:\n pivot_pos = self.partition(nums, l, r)\n if pivot_pos == n - k:\n return nums[pivot_pos]\n elif pivot_pos < n - k:\n l = pivot_pos + 1\n else:\n r = pivot_pos - 1",
"... | <|body_start_0|>
if not nums or k < 1 or k > len(nums):
return None
l, r, n = (0, len(nums) - 1, len(nums))
while l <= r:
pivot_pos = self.partition(nums, l, r)
if pivot_pos == n - k:
return nums[pivot_pos]
elif pivot_pos < n - k:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findKthLargest(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def partition(self, nums, l, r):
"""make sure start <= k <= end compare the pivots position with k whether to repeat again"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k_train_011414 | 986 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "findKthLargest",
"signature": "def findKthLargest(self, nums, k)"
},
{
"docstring": "make sure start <= k <= end compare the pivots position with k whether to repeat again",
"name": "partition",
"signature": "def p... | 2 | stack_v2_sparse_classes_30k_train_001579 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findKthLargest(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def partition(self, nums, l, r): make sure start <= k <= end compare the pivots position with ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findKthLargest(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def partition(self, nums, l, r): make sure start <= k <= end compare the pivots position with ... | fe7afbead2f1e252f4bc5692e0f94a6ce32f3c44 | <|skeleton|>
class Solution:
def findKthLargest(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def partition(self, nums, l, r):
"""make sure start <= k <= end compare the pivots position with k whether to repeat again"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findKthLargest(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
if not nums or k < 1 or k > len(nums):
return None
l, r, n = (0, len(nums) - 1, len(nums))
while l <= r:
pivot_pos = self.partition(nums, l, r)
... | the_stack_v2_python_sparse | Python/Algorithm/Devide and Conquer/Binary Search/Advanced/Kth Largest Element in an Array.py | fagan2888/Coding-Interview | train | 0 | |
e338e4071919ac9a4671a84ba70b0206b7e9544f | [
"process_move_id = context and context.get('active_id', False) or False\ntotal_qty = context and context.get('total_qty', 0.0) or 0.0\nproduct_id = context and context.get('product_id', False) or False\nprocess_qty = context and context.get('process_qty', 0.0) or 0.0\nalready_rejected_qty = context and context.get(... | <|body_start_0|>
process_move_id = context and context.get('active_id', False) or False
total_qty = context and context.get('total_qty', 0.0) or 0.0
product_id = context and context.get('product_id', False) or False
process_qty = context and context.get('process_qty', 0.0) or 0.0
... | process_qty_to_update_reject | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class process_qty_to_update_reject:
def default_get(self, cr, uid, fields, context):
"""-Process -Set default values of -Active_id -Product -Total Qty"""
<|body_0|>
def _check_validation_reject_qty(self, cr, uid, total_qty, rejected_qty):
"""- Process - Warning raise, if r... | stack_v2_sparse_classes_36k_train_011415 | 8,156 | no_license | [
{
"docstring": "-Process -Set default values of -Active_id -Product -Total Qty",
"name": "default_get",
"signature": "def default_get(self, cr, uid, fields, context)"
},
{
"docstring": "- Process - Warning raise, if rejected qty > total qty or rejected qty < 0",
"name": "_check_validation_re... | 5 | stack_v2_sparse_classes_30k_train_002797 | Implement the Python class `process_qty_to_update_reject` described below.
Class description:
Implement the process_qty_to_update_reject class.
Method signatures and docstrings:
- def default_get(self, cr, uid, fields, context): -Process -Set default values of -Active_id -Product -Total Qty
- def _check_validation_re... | Implement the Python class `process_qty_to_update_reject` described below.
Class description:
Implement the process_qty_to_update_reject class.
Method signatures and docstrings:
- def default_get(self, cr, uid, fields, context): -Process -Set default values of -Active_id -Product -Total Qty
- def _check_validation_re... | d3daac105636ac4e146816232c616298dc5bb742 | <|skeleton|>
class process_qty_to_update_reject:
def default_get(self, cr, uid, fields, context):
"""-Process -Set default values of -Active_id -Product -Total Qty"""
<|body_0|>
def _check_validation_reject_qty(self, cr, uid, total_qty, rejected_qty):
"""- Process - Warning raise, if r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class process_qty_to_update_reject:
def default_get(self, cr, uid, fields, context):
"""-Process -Set default values of -Active_id -Product -Total Qty"""
process_move_id = context and context.get('active_id', False) or False
total_qty = context and context.get('total_qty', 0.0) or 0.0
... | the_stack_v2_python_sparse | l10n_in_mrp_subcontract/wizard/process_qty_to_reject.py | Odoo-India/odoo-india | train | 10 | |
20ee31d1471e0d8b666b2fabc9d982494caafc22 | [
"if request.user.user_type == User.developer or request.user.user_type == User.admin or request.user.user_type == User.accounts:\n qs = self.get_queryset()\nelse:\n qs = self.get_queryset().filter(user_id__exact=request.user)\nserializer = LorryReceiptSerializer(qs, many=True)\nreturn Response(serializer.data... | <|body_start_0|>
if request.user.user_type == User.developer or request.user.user_type == User.admin or request.user.user_type == User.accounts:
qs = self.get_queryset()
else:
qs = self.get_queryset().filter(user_id__exact=request.user)
serializer = LorryReceiptSerializer... | LorryReceiptList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LorryReceiptList:
def get(self, request, *args, **kwargs):
"""Overriding the get method"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Overriding the post method"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if request.user.user_type =... | stack_v2_sparse_classes_36k_train_011416 | 14,344 | no_license | [
{
"docstring": "Overriding the get method",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Overriding the post method",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021136 | Implement the Python class `LorryReceiptList` described below.
Class description:
Implement the LorryReceiptList class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Overriding the get method
- def post(self, request, *args, **kwargs): Overriding the post method | Implement the Python class `LorryReceiptList` described below.
Class description:
Implement the LorryReceiptList class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Overriding the get method
- def post(self, request, *args, **kwargs): Overriding the post method
<|skeleton|>
class Lorr... | b76b9b0f3f3b70928c38856a24f963654f2139dc | <|skeleton|>
class LorryReceiptList:
def get(self, request, *args, **kwargs):
"""Overriding the get method"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Overriding the post method"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LorryReceiptList:
def get(self, request, *args, **kwargs):
"""Overriding the get method"""
if request.user.user_type == User.developer or request.user.user_type == User.admin or request.user.user_type == User.accounts:
qs = self.get_queryset()
else:
qs = self.ge... | the_stack_v2_python_sparse | operations/views.py | nileshnagarwal/NimbusApp | train | 0 | |
68c052fde143a7d580b1fbb89c74a9cb50102194 | [
"MIN = 1999999999\nab = 'abcdefghijklmnopqrstuvwxyz'\nfor x in ab:\n idx = s.find(x)\n if idx != -1:\n if idx == s.rfind(x):\n if idx < MIN:\n MIN = idx\nreturn -1 if MIN == 1999999999 else MIN",
"letters = 'abcdefghijklmnopqrstuvwxyz'\nindex = [s.index(l) for l in letters i... | <|body_start_0|>
MIN = 1999999999
ab = 'abcdefghijklmnopqrstuvwxyz'
for x in ab:
idx = s.find(x)
if idx != -1:
if idx == s.rfind(x):
if idx < MIN:
MIN = idx
return -1 if MIN == 1999999999 else MIN
<|end_b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def firstUniqChar(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def firstUniqChar(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
MIN = 1999999999
ab = 'abcdefghijklmnopqrstuvwxyz'
... | stack_v2_sparse_classes_36k_train_011417 | 978 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "firstUniqChar",
"signature": "def firstUniqChar(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "firstUniqChar",
"signature": "def firstUniqChar(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstUniqChar(self, s): :type s: str :rtype: int
- def firstUniqChar(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstUniqChar(self, s): :type s: str :rtype: int
- def firstUniqChar(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def firstUniqChar(self, s):
... | 8bb17099be02d997d554519be360ef4aa1c028e3 | <|skeleton|>
class Solution:
def firstUniqChar(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def firstUniqChar(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def firstUniqChar(self, s):
""":type s: str :rtype: int"""
MIN = 1999999999
ab = 'abcdefghijklmnopqrstuvwxyz'
for x in ab:
idx = s.find(x)
if idx != -1:
if idx == s.rfind(x):
if idx < MIN:
... | the_stack_v2_python_sparse | Google/1. easy/387. First Unique Character in a String.py | yemao616/summer18 | train | 0 | |
90601a5194897661efbb0583b8a32d239c787db7 | [
"self.format_string = unicode(self.FORMAT_STRING)\nself.format_string_short = unicode(self.FORMAT_STRING_SHORT)\nself.source_string = unicode(self.SOURCE_LONG)\nself.source_string_short = unicode(self.SOURCE_SHORT)",
"if self.DATA_TYPE != event_object.data_type:\n raise errors.WrongFormatter(u'Unsupported data... | <|body_start_0|>
self.format_string = unicode(self.FORMAT_STRING)
self.format_string_short = unicode(self.FORMAT_STRING_SHORT)
self.source_string = unicode(self.SOURCE_LONG)
self.source_string_short = unicode(self.SOURCE_SHORT)
<|end_body_0|>
<|body_start_1|>
if self.DATA_TYPE !... | Base class to format event type specific data using a format string. Define the (long) format string and the short format string by defining FORMAT_STRING and FORMAT_STRING_SHORT. The syntax of the format strings is similar to that of format() where the place holder for a certain event object attribute is defined as {a... | EventFormatter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventFormatter:
"""Base class to format event type specific data using a format string. Define the (long) format string and the short format string by defining FORMAT_STRING and FORMAT_STRING_SHORT. The syntax of the format strings is similar to that of format() where the place holder for a certa... | stack_v2_sparse_classes_36k_train_011418 | 15,049 | permissive | [
{
"docstring": "Set up the formatter and determine if this is the right formatter.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Return a list of messages extracted from an event object. The l2t_csv and other formats are dependent on a message field, referred to as d... | 3 | stack_v2_sparse_classes_30k_test_000393 | Implement the Python class `EventFormatter` described below.
Class description:
Base class to format event type specific data using a format string. Define the (long) format string and the short format string by defining FORMAT_STRING and FORMAT_STRING_SHORT. The syntax of the format strings is similar to that of form... | Implement the Python class `EventFormatter` described below.
Class description:
Base class to format event type specific data using a format string. Define the (long) format string and the short format string by defining FORMAT_STRING and FORMAT_STRING_SHORT. The syntax of the format strings is similar to that of form... | b4dc64b3a2d2906e8947824c493a2bc311d765c1 | <|skeleton|>
class EventFormatter:
"""Base class to format event type specific data using a format string. Define the (long) format string and the short format string by defining FORMAT_STRING and FORMAT_STRING_SHORT. The syntax of the format strings is similar to that of format() where the place holder for a certa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventFormatter:
"""Base class to format event type specific data using a format string. Define the (long) format string and the short format string by defining FORMAT_STRING and FORMAT_STRING_SHORT. The syntax of the format strings is similar to that of format() where the place holder for a certain event obje... | the_stack_v2_python_sparse | plaso/lib/eventdata.py | iwm911/plaso | train | 0 |
b94c9c7d7c2f42509bd2d6aaa8a39c14b9b05835 | [
"stack = []\ncurstring = ''\ncurnum = 0\nfor c in s:\n if c == '[':\n stack.append(curstring)\n stack.append(curnum)\n curnum = 0\n curstring = ''\n elif c == ']':\n num = stack.pop()\n prevstring = stack.pop()\n curstring = prevstring + num * curstring\n el... | <|body_start_0|>
stack = []
curstring = ''
curnum = 0
for c in s:
if c == '[':
stack.append(curstring)
stack.append(curnum)
curnum = 0
curstring = ''
elif c == ']':
num = stack.pop()
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def decodeString(self, s):
"""Stack time O(S+|s|) space O(S) 本题难点在于括号内嵌套括号,需要从内向外生成与拼接字符串,这与栈的先入后出特性对应。 算法流程: 构建辅助栈 stack, 遍历字符串 s 中每个字符 c; 当 c 为数字时,将数字字符转化为数字 multi,用于后续倍数计算; 当 c 为字母时,在 res 尾部添加 c; 当 c 为 [ 时,将当前 multi 和 res 入栈,并分别置空置 000: 记录此 [ 前的临时结果 res 至栈,用于发现对应 ] 后的拼接操作; 记... | stack_v2_sparse_classes_36k_train_011419 | 3,130 | no_license | [
{
"docstring": "Stack time O(S+|s|) space O(S) 本题难点在于括号内嵌套括号,需要从内向外生成与拼接字符串,这与栈的先入后出特性对应。 算法流程: 构建辅助栈 stack, 遍历字符串 s 中每个字符 c; 当 c 为数字时,将数字字符转化为数字 multi,用于后续倍数计算; 当 c 为字母时,在 res 尾部添加 c; 当 c 为 [ 时,将当前 multi 和 res 入栈,并分别置空置 000: 记录此 [ 前的临时结果 res 至栈,用于发现对应 ] 后的拼接操作; 记录此 [ 前的倍数 multi 至栈,用于发现对应 ] 后,获取 multi × [...] 字... | 2 | stack_v2_sparse_classes_30k_train_012442 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def decodeString(self, s): Stack time O(S+|s|) space O(S) 本题难点在于括号内嵌套括号,需要从内向外生成与拼接字符串,这与栈的先入后出特性对应。 算法流程: 构建辅助栈 stack, 遍历字符串 s 中每个字符 c; 当 c 为数字时,将数字字符转化为数字 multi,用于后续倍数计算; 当 c 为... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def decodeString(self, s): Stack time O(S+|s|) space O(S) 本题难点在于括号内嵌套括号,需要从内向外生成与拼接字符串,这与栈的先入后出特性对应。 算法流程: 构建辅助栈 stack, 遍历字符串 s 中每个字符 c; 当 c 为数字时,将数字字符转化为数字 multi,用于后续倍数计算; 当 c 为... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def decodeString(self, s):
"""Stack time O(S+|s|) space O(S) 本题难点在于括号内嵌套括号,需要从内向外生成与拼接字符串,这与栈的先入后出特性对应。 算法流程: 构建辅助栈 stack, 遍历字符串 s 中每个字符 c; 当 c 为数字时,将数字字符转化为数字 multi,用于后续倍数计算; 当 c 为字母时,在 res 尾部添加 c; 当 c 为 [ 时,将当前 multi 和 res 入栈,并分别置空置 000: 记录此 [ 前的临时结果 res 至栈,用于发现对应 ] 后的拼接操作; 记... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def decodeString(self, s):
"""Stack time O(S+|s|) space O(S) 本题难点在于括号内嵌套括号,需要从内向外生成与拼接字符串,这与栈的先入后出特性对应。 算法流程: 构建辅助栈 stack, 遍历字符串 s 中每个字符 c; 当 c 为数字时,将数字字符转化为数字 multi,用于后续倍数计算; 当 c 为字母时,在 res 尾部添加 c; 当 c 为 [ 时,将当前 multi 和 res 入栈,并分别置空置 000: 记录此 [ 前的临时结果 res 至栈,用于发现对应 ] 后的拼接操作; 记录此 [ 前的倍数 mult... | the_stack_v2_python_sparse | LeetCode/Stack/394_decode_string.py | XyK0907/for_work | train | 0 | |
924c9ee167da3a5c3b6b52216960a97fd5d7a697 | [
"self.dag_info = dag_info\nself.application_server_info = application_server_info\nself.dag_database_copy_info = dag_database_copy_info\nself.dag_database_info = dag_database_info\nself.name = name\nself.owner_id = owner_id\nself.standalone_database_copy_info = standalone_database_copy_info\nself.mtype = mtype\nsel... | <|body_start_0|>
self.dag_info = dag_info
self.application_server_info = application_server_info
self.dag_database_copy_info = dag_database_copy_info
self.dag_database_info = dag_database_info
self.name = name
self.owner_id = owner_id
self.standalone_database_copy... | Implementation of the 'ExchangeProtectionSource' model. Specifies an object representing an Exchange entity. DAG - Database availability group Attributes: dag_info (DagInfo): Specifies the Exchange DAG information if ExchangeProtectionSourceType is 'kExchangeDAG'. application_server_info (ApplicationServerInfo): Specif... | ExchangeProtectionSource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExchangeProtectionSource:
"""Implementation of the 'ExchangeProtectionSource' model. Specifies an object representing an Exchange entity. DAG - Database availability group Attributes: dag_info (DagInfo): Specifies the Exchange DAG information if ExchangeProtectionSourceType is 'kExchangeDAG'. app... | stack_v2_sparse_classes_36k_train_011420 | 5,196 | permissive | [
{
"docstring": "Constructor for the ExchangeProtectionSource class",
"name": "__init__",
"signature": "def __init__(self, dag_info=None, application_server_info=None, dag_database_copy_info=None, dag_database_info=None, name=None, owner_id=None, standalone_database_copy_info=None, mtype=None, uuid=None)... | 2 | stack_v2_sparse_classes_30k_train_009785 | Implement the Python class `ExchangeProtectionSource` described below.
Class description:
Implementation of the 'ExchangeProtectionSource' model. Specifies an object representing an Exchange entity. DAG - Database availability group Attributes: dag_info (DagInfo): Specifies the Exchange DAG information if ExchangeProt... | Implement the Python class `ExchangeProtectionSource` described below.
Class description:
Implementation of the 'ExchangeProtectionSource' model. Specifies an object representing an Exchange entity. DAG - Database availability group Attributes: dag_info (DagInfo): Specifies the Exchange DAG information if ExchangeProt... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ExchangeProtectionSource:
"""Implementation of the 'ExchangeProtectionSource' model. Specifies an object representing an Exchange entity. DAG - Database availability group Attributes: dag_info (DagInfo): Specifies the Exchange DAG information if ExchangeProtectionSourceType is 'kExchangeDAG'. app... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExchangeProtectionSource:
"""Implementation of the 'ExchangeProtectionSource' model. Specifies an object representing an Exchange entity. DAG - Database availability group Attributes: dag_info (DagInfo): Specifies the Exchange DAG information if ExchangeProtectionSourceType is 'kExchangeDAG'. application_serv... | the_stack_v2_python_sparse | cohesity_management_sdk/models/exchange_protection_source.py | cohesity/management-sdk-python | train | 24 |
e450095e7de6421b5f6d3828ebbdc25a03ee1493 | [
"[teams] = valuelist\nteams = [team.splitlines() for team in re.split('(?:\\r\\n|\\n){2,}', teams.strip())]\nif len(teams) == 1:\n teams = [[trainer] for trainer in teams[0]]\nself.data = teams",
"if not self.data:\n return ''\nelif all((len(team) == 1 for team in self.data)):\n return '\\n'.join((traine... | <|body_start_0|>
[teams] = valuelist
teams = [team.splitlines() for team in re.split('(?:\r\n|\n){2,}', teams.strip())]
if len(teams) == 1:
teams = [[trainer] for trainer in teams[0]]
self.data = teams
<|end_body_0|>
<|body_start_1|>
if not self.data:
ret... | A field for entering trainers who will participate in a battle. | BattleTrainerField | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BattleTrainerField:
"""A field for entering trainers who will participate in a battle."""
def process_formdata(self, valuelist):
"""Split the input into lists of names."""
<|body_0|>
def _value(self):
"""Re-join all the lists of names into one string."""
... | stack_v2_sparse_classes_36k_train_011421 | 21,218 | no_license | [
{
"docstring": "Split the input into lists of names.",
"name": "process_formdata",
"signature": "def process_formdata(self, valuelist)"
},
{
"docstring": "Re-join all the lists of names into one string.",
"name": "_value",
"signature": "def _value(self)"
},
{
"docstring": "Do som... | 4 | stack_v2_sparse_classes_30k_train_011484 | Implement the Python class `BattleTrainerField` described below.
Class description:
A field for entering trainers who will participate in a battle.
Method signatures and docstrings:
- def process_formdata(self, valuelist): Split the input into lists of names.
- def _value(self): Re-join all the lists of names into on... | Implement the Python class `BattleTrainerField` described below.
Class description:
A field for entering trainers who will participate in a battle.
Method signatures and docstrings:
- def process_formdata(self, valuelist): Split the input into lists of names.
- def _value(self): Re-join all the lists of names into on... | 872c0b21ed8d45a4c88d51969d3531b8b7913e71 | <|skeleton|>
class BattleTrainerField:
"""A field for entering trainers who will participate in a battle."""
def process_formdata(self, valuelist):
"""Split the input into lists of names."""
<|body_0|>
def _value(self):
"""Re-join all the lists of names into one string."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BattleTrainerField:
"""A field for entering trainers who will participate in a battle."""
def process_formdata(self, valuelist):
"""Split the input into lists of names."""
[teams] = valuelist
teams = [team.splitlines() for team in re.split('(?:\r\n|\n){2,}', teams.strip())]
... | the_stack_v2_python_sparse | asb/views/battle.py | CatTrinket/tcod-asb | train | 1 |
a2027fc35fac278eedc0d6b16539ecf32c5ecaa2 | [
"super(DNN, self).__init__()\nself._dropout = dropout\nself.hidden_layers = [None for _ in range(10)]\nfor i in range(10):\n self.hidden_layers[i] = tf.keras.layers.Dense(100, activation='relu', use_bias=True, trainable=trainable, name='dense_{}'.format(i), kernel_initializer='he_normal')\nself.linear = tf.keras... | <|body_start_0|>
super(DNN, self).__init__()
self._dropout = dropout
self.hidden_layers = [None for _ in range(10)]
for i in range(10):
self.hidden_layers[i] = tf.keras.layers.Dense(100, activation='relu', use_bias=True, trainable=trainable, name='dense_{}'.format(i), kernel_... | Deep Neural Network with 10 hidden layers. Attributes: hidden_layers: A list of 10 tf.keras.layers.Dense layers with ReLU. linear: Fully-connected layer. | DNN | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DNN:
"""Deep Neural Network with 10 hidden layers. Attributes: hidden_layers: A list of 10 tf.keras.layers.Dense layers with ReLU. linear: Fully-connected layer."""
def __init__(self, trainable=True, dropout=0.15):
"""Creates the DNN layers. Args: trainable: Whether the DNN parameter... | stack_v2_sparse_classes_36k_train_011422 | 10,796 | permissive | [
{
"docstring": "Creates the DNN layers. Args: trainable: Whether the DNN parameters are trainable or not. dropout: Coefficient for dropout regularization.",
"name": "__init__",
"signature": "def __init__(self, trainable=True, dropout=0.15)"
},
{
"docstring": "Creates the output tensor given an i... | 2 | stack_v2_sparse_classes_30k_train_005335 | Implement the Python class `DNN` described below.
Class description:
Deep Neural Network with 10 hidden layers. Attributes: hidden_layers: A list of 10 tf.keras.layers.Dense layers with ReLU. linear: Fully-connected layer.
Method signatures and docstrings:
- def __init__(self, trainable=True, dropout=0.15): Creates t... | Implement the Python class `DNN` described below.
Class description:
Deep Neural Network with 10 hidden layers. Attributes: hidden_layers: A list of 10 tf.keras.layers.Dense layers with ReLU. linear: Fully-connected layer.
Method signatures and docstrings:
- def __init__(self, trainable=True, dropout=0.15): Creates t... | 727ec399ad17b4dd1f71ce69a26fc3b0371d9fa7 | <|skeleton|>
class DNN:
"""Deep Neural Network with 10 hidden layers. Attributes: hidden_layers: A list of 10 tf.keras.layers.Dense layers with ReLU. linear: Fully-connected layer."""
def __init__(self, trainable=True, dropout=0.15):
"""Creates the DNN layers. Args: trainable: Whether the DNN parameter... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DNN:
"""Deep Neural Network with 10 hidden layers. Attributes: hidden_layers: A list of 10 tf.keras.layers.Dense layers with ReLU. linear: Fully-connected layer."""
def __init__(self, trainable=True, dropout=0.15):
"""Creates the DNN layers. Args: trainable: Whether the DNN parameters are trainab... | the_stack_v2_python_sparse | neural_additive_models/models.py | Ayoob7/google-research | train | 2 |
1f77a8793896e5e203e3554182e1908f5efcfc7b | [
"self.Sim = Sim\nself.MyCallBack = Callback(progress_callback=progress_callback, call_at=parameters['callback_period'], temperature_plot=temperature_plot, heat_flux_plot=heat_flux_plot, queue=queue)\nself.save_results = save_results\nself.progress_callback = progress_callback\nself.temperature_plot = temperature_pl... | <|body_start_0|>
self.Sim = Sim
self.MyCallBack = Callback(progress_callback=progress_callback, call_at=parameters['callback_period'], temperature_plot=temperature_plot, heat_flux_plot=heat_flux_plot, queue=queue)
self.save_results = save_results
self.progress_callback = progress_callbac... | Holding variables and defining methods for the simulation | SimulationController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimulationController:
"""Holding variables and defining methods for the simulation"""
def __init__(self, Sim, parameters: dict, progress_callback=None, queue=None, temperature_plot=None, heat_flux_plot=None, save_results: bool=False):
"""Args: Sim ... whole simulation object paramete... | stack_v2_sparse_classes_36k_train_011423 | 7,512 | permissive | [
{
"docstring": "Args: Sim ... whole simulation object parameters ... all defined parameters of simulation heat_flux_plot ... reference of heat flux plot temperature_plot ... reference of temperature plot queue ... reference of the shared queue progress_callback ... reference of progress callback save_results ..... | 2 | stack_v2_sparse_classes_30k_train_020667 | Implement the Python class `SimulationController` described below.
Class description:
Holding variables and defining methods for the simulation
Method signatures and docstrings:
- def __init__(self, Sim, parameters: dict, progress_callback=None, queue=None, temperature_plot=None, heat_flux_plot=None, save_results: bo... | Implement the Python class `SimulationController` described below.
Class description:
Holding variables and defining methods for the simulation
Method signatures and docstrings:
- def __init__(self, Sim, parameters: dict, progress_callback=None, queue=None, temperature_plot=None, heat_flux_plot=None, save_results: bo... | 636182fa4c57913002675ed3afca8c1b3dc35e1c | <|skeleton|>
class SimulationController:
"""Holding variables and defining methods for the simulation"""
def __init__(self, Sim, parameters: dict, progress_callback=None, queue=None, temperature_plot=None, heat_flux_plot=None, save_results: bool=False):
"""Args: Sim ... whole simulation object paramete... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimulationController:
"""Holding variables and defining methods for the simulation"""
def __init__(self, Sim, parameters: dict, progress_callback=None, queue=None, temperature_plot=None, heat_flux_plot=None, save_results: bool=False):
"""Args: Sim ... whole simulation object parameters ... all de... | the_stack_v2_python_sparse | heat_transfer_simulation_utilities.py | grdddj/Diploma-Thesis---Inverse-Heat-Transfer | train | 2 |
c85dc4ee458c38a2bd3a8826419bc0d5d8c3bd57 | [
"for user, tenant_id in self._iterate_per_tenants():\n senlin_scenario = senlin_utils.SenlinScenario({'user': user, 'task': self.context['task']})\n profile = senlin_scenario._create_profile(self.config)\n self.context['tenants'][tenant_id]['profile'] = profile.id",
"for user, tenant_id in self._iterate_... | <|body_start_0|>
for user, tenant_id in self._iterate_per_tenants():
senlin_scenario = senlin_utils.SenlinScenario({'user': user, 'task': self.context['task']})
profile = senlin_scenario._create_profile(self.config)
self.context['tenants'][tenant_id]['profile'] = profile.id
<... | Context creates a temporary profile for Senlin test. | ProfilesGenerator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfilesGenerator:
"""Context creates a temporary profile for Senlin test."""
def setup(self):
"""Create test profiles."""
<|body_0|>
def cleanup(self):
"""Delete created test profiles."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for user, t... | stack_v2_sparse_classes_36k_train_011424 | 2,305 | permissive | [
{
"docstring": "Create test profiles.",
"name": "setup",
"signature": "def setup(self)"
},
{
"docstring": "Delete created test profiles.",
"name": "cleanup",
"signature": "def cleanup(self)"
}
] | 2 | null | Implement the Python class `ProfilesGenerator` described below.
Class description:
Context creates a temporary profile for Senlin test.
Method signatures and docstrings:
- def setup(self): Create test profiles.
- def cleanup(self): Delete created test profiles. | Implement the Python class `ProfilesGenerator` described below.
Class description:
Context creates a temporary profile for Senlin test.
Method signatures and docstrings:
- def setup(self): Create test profiles.
- def cleanup(self): Delete created test profiles.
<|skeleton|>
class ProfilesGenerator:
"""Context cr... | 9ff67887bf848c5966bb4a2f37018500d30dbe45 | <|skeleton|>
class ProfilesGenerator:
"""Context creates a temporary profile for Senlin test."""
def setup(self):
"""Create test profiles."""
<|body_0|>
def cleanup(self):
"""Delete created test profiles."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProfilesGenerator:
"""Context creates a temporary profile for Senlin test."""
def setup(self):
"""Create test profiles."""
for user, tenant_id in self._iterate_per_tenants():
senlin_scenario = senlin_utils.SenlinScenario({'user': user, 'task': self.context['task']})
... | the_stack_v2_python_sparse | rally_openstack/task/contexts/senlin/profiles.py | openstack/rally-openstack | train | 41 |
7827ddd9f4cfc18c123f16a5583632fe720d95b8 | [
"self.nums = nums\nself.lens = len(nums)\nself.BIT = [0] * (self.lens + 1)\nfor i in range(self.lens):\n k = i + 1\n while k <= self.lens:\n self.BIT[k] += nums[i]\n k += k & -k",
"diff = val - self.nums[i]\nself.nums[i] = val\ni += 1\nwhile i <= self.lens:\n self.BIT[i] += diff\n i += i... | <|body_start_0|>
self.nums = nums
self.lens = len(nums)
self.BIT = [0] * (self.lens + 1)
for i in range(self.lens):
k = i + 1
while k <= self.lens:
self.BIT[k] += nums[i]
k += k & -k
<|end_body_0|>
<|body_start_1|>
diff = v... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
"""update 操作一直都是遍历左侧 :type i: int :type val: int :rtype: void"""
<|body_1|>
def sumRange(self, i, j):
"""sum: 遍历右侧 上一层已经把左侧的值加上去了,而左侧的索引又是小于右侧,所以... | stack_v2_sparse_classes_36k_train_011425 | 1,921 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": "update 操作一直都是遍历左侧 :type i: int :type val: int :rtype: void",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docstring": "sum: 遍历右侧 上一层已经把左侧的值加上去... | 3 | stack_v2_sparse_classes_30k_train_008866 | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): update 操作一直都是遍历左侧 :type i: int :type val: int :rtype: void
- def sumRange(self, i, j): sum: 遍历右侧 上一层已经... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): update 操作一直都是遍历左侧 :type i: int :type val: int :rtype: void
- def sumRange(self, i, j): sum: 遍历右侧 上一层已经... | 212f8b83d6ac22db1a777f980075d9e12ce521d2 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
"""update 操作一直都是遍历左侧 :type i: int :type val: int :rtype: void"""
<|body_1|>
def sumRange(self, i, j):
"""sum: 遍历右侧 上一层已经把左侧的值加上去了,而左侧的索引又是小于右侧,所以... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self.nums = nums
self.lens = len(nums)
self.BIT = [0] * (self.lens + 1)
for i in range(self.lens):
k = i + 1
while k <= self.lens:
self.BIT[k] += nums[i]
... | the_stack_v2_python_sparse | Data Structures and Algorithm Analysis/tree/Binary Indexed Tree.py | FrankieZhen/Lookoop | train | 1 | |
e7d8f8aee7912478c24376017d6fa0e23ce9e49a | [
"if not email:\n raise ValueError('Users must have an email address')\nuser = self.model(email=self.normalize_email(email), **extra_fields)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(email=email, password=password, **extra_fields)\nuser.is_admin = True\nuser... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email), **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<|body_start_1|>
user = s... | A custom user manager for sef. | CustomUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomUserManager:
"""A custom user manager for sef."""
def create_user(self, email=None, password=None, **extra_fields):
"""Create and save a User with the given email, password."""
<|body_0|>
def create_superuser(self, email=None, password=None, **extra_fields):
... | stack_v2_sparse_classes_36k_train_011426 | 2,020 | no_license | [
{
"docstring": "Create and save a User with the given email, password.",
"name": "create_user",
"signature": "def create_user(self, email=None, password=None, **extra_fields)"
},
{
"docstring": "Create and save a User.",
"name": "create_superuser",
"signature": "def create_superuser(self... | 2 | stack_v2_sparse_classes_30k_train_020632 | Implement the Python class `CustomUserManager` described below.
Class description:
A custom user manager for sef.
Method signatures and docstrings:
- def create_user(self, email=None, password=None, **extra_fields): Create and save a User with the given email, password.
- def create_superuser(self, email=None, passwo... | Implement the Python class `CustomUserManager` described below.
Class description:
A custom user manager for sef.
Method signatures and docstrings:
- def create_user(self, email=None, password=None, **extra_fields): Create and save a User with the given email, password.
- def create_superuser(self, email=None, passwo... | 345e6f4964c6223c5765793e1d04ba73a499d935 | <|skeleton|>
class CustomUserManager:
"""A custom user manager for sef."""
def create_user(self, email=None, password=None, **extra_fields):
"""Create and save a User with the given email, password."""
<|body_0|>
def create_superuser(self, email=None, password=None, **extra_fields):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomUserManager:
"""A custom user manager for sef."""
def create_user(self, email=None, password=None, **extra_fields):
"""Create and save a User with the given email, password."""
if not email:
raise ValueError('Users must have an email address')
user = self.model(e... | the_stack_v2_python_sparse | sef/user/models/models.py | dmbuguah/sef-api | train | 0 |
c2f2115a4594c0cf5a2c1627d82f006cad890554 | [
"assert isinstance(response, scrapy.http.response.html.HtmlResponse)\nurls = [response.url]\nposts_per_page = 25\nlast_page = response.selector.xpath('//a[contains(@title, \"Click to jump to page\")]/strong[2]/text()').extract_first()\nif last_page:\n last_page = read_number(last_page)\nelse:\n last_page = 0\... | <|body_start_0|>
assert isinstance(response, scrapy.http.response.html.HtmlResponse)
urls = [response.url]
posts_per_page = 25
last_page = response.selector.xpath('//a[contains(@title, "Click to jump to page")]/strong[2]/text()').extract_first()
if last_page:
last_pag... | scrape images from angling addicts forum | AnglingAddictsImageSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnglingAddictsImageSpider:
"""scrape images from angling addicts forum"""
def parse_subforums(self, response):
"""get links to report boards"""
<|body_0|>
def parse_pages(self, response):
"""get links to all reports from boards"""
<|body_1|>
def pars... | stack_v2_sparse_classes_36k_train_011427 | 4,571 | no_license | [
{
"docstring": "get links to report boards",
"name": "parse_subforums",
"signature": "def parse_subforums(self, response)"
},
{
"docstring": "get links to all reports from boards",
"name": "parse_pages",
"signature": "def parse_pages(self, response)"
},
{
"docstring": "for each b... | 3 | null | Implement the Python class `AnglingAddictsImageSpider` described below.
Class description:
scrape images from angling addicts forum
Method signatures and docstrings:
- def parse_subforums(self, response): get links to report boards
- def parse_pages(self, response): get links to all reports from boards
- def parse_im... | Implement the Python class `AnglingAddictsImageSpider` described below.
Class description:
scrape images from angling addicts forum
Method signatures and docstrings:
- def parse_subforums(self, response): get links to report boards
- def parse_pages(self, response): get links to all reports from boards
- def parse_im... | 9123aa6baf538b662143b9098d963d55165e8409 | <|skeleton|>
class AnglingAddictsImageSpider:
"""scrape images from angling addicts forum"""
def parse_subforums(self, response):
"""get links to report boards"""
<|body_0|>
def parse_pages(self, response):
"""get links to all reports from boards"""
<|body_1|>
def pars... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnglingAddictsImageSpider:
"""scrape images from angling addicts forum"""
def parse_subforums(self, response):
"""get links to report boards"""
assert isinstance(response, scrapy.http.response.html.HtmlResponse)
urls = [response.url]
posts_per_page = 25
last_page =... | the_stack_v2_python_sparse | imgscrape/spiders/angling_addicts.py | gmonkman/python | train | 0 |
271522da66065e77ba710d952907f78a75fc3536 | [
"if not nums:\n return 0\ncum_sum = [0]\nfor num in nums:\n cum_sum.append(cum_sum[-1] + num)\nres = 0\nfor i in range(len(cum_sum) - 1):\n for j in range(i + 1, len(cum_sum)):\n if cum_sum[j] - cum_sum[i] == k:\n res += 1\nreturn res",
"if not nums:\n return 0\ncounts_map = {0: 1}\n... | <|body_start_0|>
if not nums:
return 0
cum_sum = [0]
for num in nums:
cum_sum.append(cum_sum[-1] + num)
res = 0
for i in range(len(cum_sum) - 1):
for j in range(i + 1, len(cum_sum)):
if cum_sum[j] - cum_sum[i] == k:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subarray_sum(self, nums: List[int], k: int) -> int:
"""Time complexity O(n**2). Although this is faster than O(n**3) solution (brutal force without cumulative array), it is still not fast enough to pass the test."""
<|body_0|>
def subarray_sum_hash_map(self, nu... | stack_v2_sparse_classes_36k_train_011428 | 1,152 | no_license | [
{
"docstring": "Time complexity O(n**2). Although this is faster than O(n**3) solution (brutal force without cumulative array), it is still not fast enough to pass the test.",
"name": "subarray_sum",
"signature": "def subarray_sum(self, nums: List[int], k: int) -> int"
},
{
"docstring": "O(n) so... | 2 | stack_v2_sparse_classes_30k_train_007870 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subarray_sum(self, nums: List[int], k: int) -> int: Time complexity O(n**2). Although this is faster than O(n**3) solution (brutal force without cumulative array), it is stil... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subarray_sum(self, nums: List[int], k: int) -> int: Time complexity O(n**2). Although this is faster than O(n**3) solution (brutal force without cumulative array), it is stil... | 5625e6396b746255f3343253c75447ead95879c7 | <|skeleton|>
class Solution:
def subarray_sum(self, nums: List[int], k: int) -> int:
"""Time complexity O(n**2). Although this is faster than O(n**3) solution (brutal force without cumulative array), it is still not fast enough to pass the test."""
<|body_0|>
def subarray_sum_hash_map(self, nu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def subarray_sum(self, nums: List[int], k: int) -> int:
"""Time complexity O(n**2). Although this is faster than O(n**3) solution (brutal force without cumulative array), it is still not fast enough to pass the test."""
if not nums:
return 0
cum_sum = [0]
... | the_stack_v2_python_sparse | 560_subarray_sum_equals_k/solution.py | FluffyFu/Leetcode | train | 0 | |
7c7aadf180f5945e5395d110ad6c651d698b224c | [
"if user is None:\n user = ctx.author\nwith utils.Embed(use_random_colour=True) as embed:\n embed.set_image(url=user.avatar_url)\nawait ctx.send(embed=embed)",
"data = {'channel_name': ctx.channel.name, 'category_name': ctx.channel.category.name, 'guild_name': ctx.guild.name, 'guild_icon_url': str(ctx.guild... | <|body_start_0|>
if user is None:
user = ctx.author
with utils.Embed(use_random_colour=True) as embed:
embed.set_image(url=user.avatar_url)
await ctx.send(embed=embed)
<|end_body_0|>
<|body_start_1|>
data = {'channel_name': ctx.channel.name, 'category_name': ctx.... | UserInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserInfo:
async def avatar(self, ctx: utils.Context, user: discord.User=None):
"""Shows you the avatar of a given user"""
<|body_0|>
async def createlog(self, ctx: utils.Context, amount: int=100):
"""Create a log of chat"""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_011429 | 2,686 | no_license | [
{
"docstring": "Shows you the avatar of a given user",
"name": "avatar",
"signature": "async def avatar(self, ctx: utils.Context, user: discord.User=None)"
},
{
"docstring": "Create a log of chat",
"name": "createlog",
"signature": "async def createlog(self, ctx: utils.Context, amount: i... | 2 | stack_v2_sparse_classes_30k_train_005034 | Implement the Python class `UserInfo` described below.
Class description:
Implement the UserInfo class.
Method signatures and docstrings:
- async def avatar(self, ctx: utils.Context, user: discord.User=None): Shows you the avatar of a given user
- async def createlog(self, ctx: utils.Context, amount: int=100): Create... | Implement the Python class `UserInfo` described below.
Class description:
Implement the UserInfo class.
Method signatures and docstrings:
- async def avatar(self, ctx: utils.Context, user: discord.User=None): Shows you the avatar of a given user
- async def createlog(self, ctx: utils.Context, amount: int=100): Create... | 454a21afb33db5acc06e939caec8e545d762142e | <|skeleton|>
class UserInfo:
async def avatar(self, ctx: utils.Context, user: discord.User=None):
"""Shows you the avatar of a given user"""
<|body_0|>
async def createlog(self, ctx: utils.Context, amount: int=100):
"""Create a log of chat"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserInfo:
async def avatar(self, ctx: utils.Context, user: discord.User=None):
"""Shows you the avatar of a given user"""
if user is None:
user = ctx.author
with utils.Embed(use_random_colour=True) as embed:
embed.set_image(url=user.avatar_url)
await ctx... | the_stack_v2_python_sparse | cogs/user_info.py | fadedmax/Apple.Py | train | 0 | |
c44a8969aa528e1ed7199439dc037e57cd7f53eb | [
"\"\"\"For Frequency Prescalar-0\"\"\"\nbus.write_byte_data(PCA9530_2C_1_DEFAULT_ADDRESS, PCA9530_2C_1_REG_PSC0, PCA9530_2C_1_PSC0_USERDEFINED)\n'For Frequency Prescalar-1'\nbus.write_byte_data(PCA9530_2C_1_DEFAULT_ADDRESS, PCA9530_2C_1_REG_PSC1, PCA9530_2C_1_PSC1_USERDEFINED)",
"\"\"\"For PWM Register-0\"\"\"\nb... | <|body_start_0|>
"""For Frequency Prescalar-0"""
bus.write_byte_data(PCA9530_2C_1_DEFAULT_ADDRESS, PCA9530_2C_1_REG_PSC0, PCA9530_2C_1_PSC0_USERDEFINED)
'For Frequency Prescalar-1'
bus.write_byte_data(PCA9530_2C_1_DEFAULT_ADDRESS, PCA9530_2C_1_REG_PSC1, PCA9530_2C_1_PSC1_USERDEFINED)
<|e... | PCA9530_2C_1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PCA9530_2C_1:
def set_frequency(self):
"""Select the Frequency Prescalar Configuration from the given provided value"""
<|body_0|>
def set_pulse_width(self):
"""Select the PWM Register Configuration from the given provided value"""
<|body_1|>
def set_led... | stack_v2_sparse_classes_36k_train_011430 | 3,054 | no_license | [
{
"docstring": "Select the Frequency Prescalar Configuration from the given provided value",
"name": "set_frequency",
"signature": "def set_frequency(self)"
},
{
"docstring": "Select the PWM Register Configuration from the given provided value",
"name": "set_pulse_width",
"signature": "d... | 3 | null | Implement the Python class `PCA9530_2C_1` described below.
Class description:
Implement the PCA9530_2C_1 class.
Method signatures and docstrings:
- def set_frequency(self): Select the Frequency Prescalar Configuration from the given provided value
- def set_pulse_width(self): Select the PWM Register Configuration fro... | Implement the Python class `PCA9530_2C_1` described below.
Class description:
Implement the PCA9530_2C_1 class.
Method signatures and docstrings:
- def set_frequency(self): Select the Frequency Prescalar Configuration from the given provided value
- def set_pulse_width(self): Select the PWM Register Configuration fro... | 736b29434a451a384c2f52490c849239c3190951 | <|skeleton|>
class PCA9530_2C_1:
def set_frequency(self):
"""Select the Frequency Prescalar Configuration from the given provided value"""
<|body_0|>
def set_pulse_width(self):
"""Select the PWM Register Configuration from the given provided value"""
<|body_1|>
def set_led... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PCA9530_2C_1:
def set_frequency(self):
"""Select the Frequency Prescalar Configuration from the given provided value"""
"""For Frequency Prescalar-0"""
bus.write_byte_data(PCA9530_2C_1_DEFAULT_ADDRESS, PCA9530_2C_1_REG_PSC0, PCA9530_2C_1_PSC0_USERDEFINED)
'For Frequency Prescal... | the_stack_v2_python_sparse | PCA9530_2C_1.py | ControlEverythingCommunity/CE_PYTHON_LIB | train | 7 | |
5ee5a9b2e48106404a54cfb20a359fdbc17cbb9a | [
"super(BridgeAPI, self).__init__(address, protocol=protocol, prefix=prefix)\nif not device_name:\n raise ValueError('No device_name specified for register (call your app something).')\nself._device_name = device_name\nself._username = username",
"if username:\n self._username = username\n return\nif self... | <|body_start_0|>
super(BridgeAPI, self).__init__(address, protocol=protocol, prefix=prefix)
if not device_name:
raise ValueError('No device_name specified for register (call your app something).')
self._device_name = device_name
self._username = username
<|end_body_0|>
<|bod... | BridgeAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BridgeAPI:
def __init__(self, device_name, address, protocol=None, prefix=None, username=None):
"""Create a BridgeAPI instance. \\param device_name How to identify ourselves to the hub, \\param address DNS name or IP address of the hub, \\param protocol [opt] Which protocol (http or http... | stack_v2_sparse_classes_36k_train_011431 | 2,327 | permissive | [
{
"docstring": "Create a BridgeAPI instance. \\\\param device_name How to identify ourselves to the hub, \\\\param address DNS name or IP address of the hub, \\\\param protocol [opt] Which protocol (http or https) to use, \\\\param prefix [opt] Top-level URL (should be \"/api\"), \\\\param username [opt] Author... | 2 | stack_v2_sparse_classes_30k_train_021514 | Implement the Python class `BridgeAPI` described below.
Class description:
Implement the BridgeAPI class.
Method signatures and docstrings:
- def __init__(self, device_name, address, protocol=None, prefix=None, username=None): Create a BridgeAPI instance. \\param device_name How to identify ourselves to the hub, \\pa... | Implement the Python class `BridgeAPI` described below.
Class description:
Implement the BridgeAPI class.
Method signatures and docstrings:
- def __init__(self, device_name, address, protocol=None, prefix=None, username=None): Create a BridgeAPI instance. \\param device_name How to identify ourselves to the hub, \\pa... | 81ed372117bcad691176aac960302f497adf8d82 | <|skeleton|>
class BridgeAPI:
def __init__(self, device_name, address, protocol=None, prefix=None, username=None):
"""Create a BridgeAPI instance. \\param device_name How to identify ourselves to the hub, \\param address DNS name or IP address of the hub, \\param protocol [opt] Which protocol (http or http... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BridgeAPI:
def __init__(self, device_name, address, protocol=None, prefix=None, username=None):
"""Create a BridgeAPI instance. \\param device_name How to identify ourselves to the hub, \\param address DNS name or IP address of the hub, \\param protocol [opt] Which protocol (http or https) to use, \\p... | the_stack_v2_python_sparse | python/humble.py | kfsone/tinker | train | 0 | |
723628b68bee3512a809c1cdb715d71fc593e5b8 | [
"super(Decoder, self).__init__()\nself.N = N\nself.dm = dm\nself.embedding = tf.keras.layers.Embedding(target_vocab, self.dm)\nself.positional_encoding = positional_encoding(max_seq_len, self.dm)\nself.blocks = [DecoderBlock(self.dm, h, hidden, drop_rate) for n in range(self.N)]\nself.dropout = tf.keras.layers.Drop... | <|body_start_0|>
super(Decoder, self).__init__()
self.N = N
self.dm = dm
self.embedding = tf.keras.layers.Embedding(target_vocab, self.dm)
self.positional_encoding = positional_encoding(max_seq_len, self.dm)
self.blocks = [DecoderBlock(self.dm, h, hidden, drop_rate) for n... | Perform encoder part of the transformer | Decoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
"""Perform encoder part of the transformer"""
def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1):
"""initialized the variables Arg: - N: the number of blocks in the encoder - dm: integer representing the dimensionality of the model - h: integer re... | stack_v2_sparse_classes_36k_train_011432 | 2,995 | no_license | [
{
"docstring": "initialized the variables Arg: - N: the number of blocks in the encoder - dm: integer representing the dimensionality of the model - h: integer representing the number of heads - hidden: the number of hidden units in the fully connected layer - target_vocab: the size of the target vocabulary - m... | 2 | null | Implement the Python class `Decoder` described below.
Class description:
Perform encoder part of the transformer
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1): initialized the variables Arg: - N: the number of blocks in the encoder - dm: integer rep... | Implement the Python class `Decoder` described below.
Class description:
Perform encoder part of the transformer
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1): initialized the variables Arg: - N: the number of blocks in the encoder - dm: integer rep... | 1d86c9606371697854878b833b810d73c9af7ee7 | <|skeleton|>
class Decoder:
"""Perform encoder part of the transformer"""
def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1):
"""initialized the variables Arg: - N: the number of blocks in the encoder - dm: integer representing the dimensionality of the model - h: integer re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Decoder:
"""Perform encoder part of the transformer"""
def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1):
"""initialized the variables Arg: - N: the number of blocks in the encoder - dm: integer representing the dimensionality of the model - h: integer representing th... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/10-transformer_decoder.py | macoyulloa/holbertonschool-machine_learning | train | 0 |
77e0b3ab49b02f0f6a904c9f69f199240e3e9cd2 | [
"final_strs = []\nfor s in strs:\n length = len(s)\n curr_str = '{},{}'.format(str(length), s)\n final_strs.append(curr_str)\nreturn ''.join(final_strs)",
"index = 0\nfinal_strs = []\nnum_regex = re.compile('\\\\d')\nwhile index < len(s):\n start_index = index\n while num_regex.match(s[index]):\n ... | <|body_start_0|>
final_strs = []
for s in strs:
length = len(s)
curr_str = '{},{}'.format(str(length), s)
final_strs.append(curr_str)
return ''.join(final_strs)
<|end_body_0|>
<|body_start_1|>
index = 0
final_strs = []
num_regex = re.c... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
<|body_0|>
def decode(self, s: str) -> [str]:
"""Decodes a single string to a list of strings."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
final_str... | stack_v2_sparse_classes_36k_train_011433 | 1,069 | no_license | [
{
"docstring": "Encodes a list of strings to a single string.",
"name": "encode",
"signature": "def encode(self, strs: [str]) -> str"
},
{
"docstring": "Decodes a single string to a list of strings.",
"name": "decode",
"signature": "def decode(self, s: str) -> [str]"
}
] | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs: [str]) -> str: Encodes a list of strings to a single string.
- def decode(self, s: str) -> [str]: Decodes a single string to a list of strings. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs: [str]) -> str: Encodes a list of strings to a single string.
- def decode(self, s: str) -> [str]: Decodes a single string to a list of strings.
<|skeleton|>
cla... | b17d53619c7b2cc5851cd2a02fa3e81f676914de | <|skeleton|>
class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
<|body_0|>
def decode(self, s: str) -> [str]:
"""Decodes a single string to a list of strings."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, strs: [str]) -> str:
"""Encodes a list of strings to a single string."""
final_strs = []
for s in strs:
length = len(s)
curr_str = '{},{}'.format(str(length), s)
final_strs.append(curr_str)
return ''.join(final_strs)
... | the_stack_v2_python_sparse | solutions/encodeDecode.py | echrisinger/Blind-75 | train | 7 | |
de66eaf46a6325a476b5383eb4b6ed45fc8f6c90 | [
"if isinstance(xScale, PQU):\n xScale = float(xScale.inUnitsOf(xUnit).value)\nparams = {'xScale': xScale}\nif domainMin is None:\n domainMin = -xScale / 10.0\nif domainMax is None:\n domainMax = xScale * 6.0\nUnivariatePDF.__init__(self, xUnit=xUnit, domainMin=domainMin, domainMax=domainMax, params=params,... | <|body_start_0|>
if isinstance(xScale, PQU):
xScale = float(xScale.inUnitsOf(xUnit).value)
params = {'xScale': xScale}
if domainMin is None:
domainMin = -xScale / 10.0
if domainMax is None:
domainMax = xScale * 6.0
UnivariatePDF.__init__(self, ... | PoissonDistribution | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PoissonDistribution:
def __init__(self, xUnit='', xScale=1.0, domainMin=None, domainMax=None, xLabel='indep. variable', yLabel='PDF'):
"""Poisson distribution (http://en.wikipedia.org/wiki/Poisson_distribution) since only k=0 implemented, this is also an exponential distribution (http://... | stack_v2_sparse_classes_36k_train_011434 | 43,025 | permissive | [
{
"docstring": "Poisson distribution (http://en.wikipedia.org/wiki/Poisson_distribution) since only k=0 implemented, this is also an exponential distribution (http://en.wikipedia.org/wiki/Exponential_distribution) Outside of the interval (domainMin,domainMax), getValue() evaluates to None since this pdf is unde... | 3 | stack_v2_sparse_classes_30k_train_004831 | Implement the Python class `PoissonDistribution` described below.
Class description:
Implement the PoissonDistribution class.
Method signatures and docstrings:
- def __init__(self, xUnit='', xScale=1.0, domainMin=None, domainMax=None, xLabel='indep. variable', yLabel='PDF'): Poisson distribution (http://en.wikipedia.... | Implement the Python class `PoissonDistribution` described below.
Class description:
Implement the PoissonDistribution class.
Method signatures and docstrings:
- def __init__(self, xUnit='', xScale=1.0, domainMin=None, domainMax=None, xLabel='indep. variable', yLabel='PDF'): Poisson distribution (http://en.wikipedia.... | 9566131c37b45fc37f5f8ad07903264864575b6e | <|skeleton|>
class PoissonDistribution:
def __init__(self, xUnit='', xScale=1.0, domainMin=None, domainMax=None, xLabel='indep. variable', yLabel='PDF'):
"""Poisson distribution (http://en.wikipedia.org/wiki/Poisson_distribution) since only k=0 implemented, this is also an exponential distribution (http://... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PoissonDistribution:
def __init__(self, xUnit='', xScale=1.0, domainMin=None, domainMax=None, xLabel='indep. variable', yLabel='PDF'):
"""Poisson distribution (http://en.wikipedia.org/wiki/Poisson_distribution) since only k=0 implemented, this is also an exponential distribution (http://en.wikipedia.o... | the_stack_v2_python_sparse | fudge/core/math/pdf.py | alhajri/FUDGE | train | 0 | |
6df74a7b58d9f860c5892b65596339ad13e745f8 | [
"if not root:\n return []\nres = []\nr = [root]\nwhile r:\n t = r.pop()\n if t.children:\n r.extend(t.children)\n res.append(t.val)\nres.reverse()\nreturn res",
"res = []\n\ndef rec(root):\n if not root:\n return res\n for c in root.children:\n rec(c)\n res.append(root.va... | <|body_start_0|>
if not root:
return []
res = []
r = [root]
while r:
t = r.pop()
if t.children:
r.extend(t.children)
res.append(t.val)
res.reverse()
return res
<|end_body_0|>
<|body_start_1|>
res = [... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def postorder_stack(self, root):
""":type root: Node :rtype: List[int] 非递归-栈"""
<|body_0|>
def postorder_recursive(self, root):
""":type root: Node :rtype: List[int] 递归"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
... | stack_v2_sparse_classes_36k_train_011435 | 1,009 | permissive | [
{
"docstring": ":type root: Node :rtype: List[int] 非递归-栈",
"name": "postorder_stack",
"signature": "def postorder_stack(self, root)"
},
{
"docstring": ":type root: Node :rtype: List[int] 递归",
"name": "postorder_recursive",
"signature": "def postorder_recursive(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def postorder_stack(self, root): :type root: Node :rtype: List[int] 非递归-栈
- def postorder_recursive(self, root): :type root: Node :rtype: List[int] 递归 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def postorder_stack(self, root): :type root: Node :rtype: List[int] 非递归-栈
- def postorder_recursive(self, root): :type root: Node :rtype: List[int] 递归
<|skeleton|>
class Solutio... | ee92fb657475d998e6c201f222cb20bcbc2bfd64 | <|skeleton|>
class Solution:
def postorder_stack(self, root):
""":type root: Node :rtype: List[int] 非递归-栈"""
<|body_0|>
def postorder_recursive(self, root):
""":type root: Node :rtype: List[int] 递归"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def postorder_stack(self, root):
""":type root: Node :rtype: List[int] 非递归-栈"""
if not root:
return []
res = []
r = [root]
while r:
t = r.pop()
if t.children:
r.extend(t.children)
res.append(t.val... | the_stack_v2_python_sparse | leetcode/0590.py | ShumaoHou/MyOJ | train | 0 | |
c5e36a012e1a682da5cd9e2e7619834cf3375505 | [
"if not prices:\n return 0\nprofit, buyprice = (0, prices[0])\nfor p in prices[1:]:\n profit = max(profit, p - buyprice)\n buyprice = min(buyprice, p)\nreturn profit",
"if len(prices) <= 1:\n return 0\nsell1 = 0\nbuy1 = -sys.maxsize\nfor p in prices:\n buy1 = max(buy1, -p)\n sell1 = max(sell1, p... | <|body_start_0|>
if not prices:
return 0
profit, buyprice = (0, prices[0])
for p in prices[1:]:
profit = max(profit, p - buyprice)
buyprice = min(buyprice, p)
return profit
<|end_body_0|>
<|body_start_1|>
if len(prices) <= 1:
retur... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit1(self, prices):
""":type prices: List[int] :rtype: int The transition relation is constructed by the following four equations. Actually, sell2 is the only state ... | stack_v2_sparse_classes_36k_train_011436 | 1,956 | no_license | [
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
},
{
"docstring": ":type prices: List[int] :rtype: int The transition relation is constructed by the following four equations. Actually, sell2 is the only state we record for ite... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit1(self, prices): :type prices: List[int] :rtype: int The transition relation is constructed by the... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit1(self, prices): :type prices: List[int] :rtype: int The transition relation is constructed by the... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit1(self, prices):
""":type prices: List[int] :rtype: int The transition relation is constructed by the following four equations. Actually, sell2 is the only state ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
if not prices:
return 0
profit, buyprice = (0, prices[0])
for p in prices[1:]:
profit = max(profit, p - buyprice)
buyprice = min(buyprice, p)
return prof... | the_stack_v2_python_sparse | B/BestTimetoBuyandSellStock.py | bssrdf/pyleet | train | 2 | |
16213237b91407e8652d7413ed4b0816671210dc | [
"self.fstat_info = fstat_info\nself.full_path = full_path\nself.name = name\nself.mtype = mtype",
"if dictionary is None:\n return None\nfstat_info = cohesity_management_sdk.models.file_stat_info.FileStatInfo.from_dictionary(dictionary.get('fstatInfo')) if dictionary.get('fstatInfo') else None\nfull_path = dic... | <|body_start_0|>
self.fstat_info = fstat_info
self.full_path = full_path
self.name = name
self.mtype = mtype
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
fstat_info = cohesity_management_sdk.models.file_stat_info.FileStatInfo.from_dictio... | Implementation of the 'VmDirEntry' model. VmDirEntry is the struct to represent a file or a folder on a VM. Attributes: fstat_info (FileStatInfo): FstatInfo is the stat information for the file. full_path (string): FullPath is the full path of the file/directory. name (string): Name is the name of the file or folder. F... | VmDirEntry | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VmDirEntry:
"""Implementation of the 'VmDirEntry' model. VmDirEntry is the struct to represent a file or a folder on a VM. Attributes: fstat_info (FileStatInfo): FstatInfo is the stat information for the file. full_path (string): FullPath is the full path of the file/directory. name (string): Nam... | stack_v2_sparse_classes_36k_train_011437 | 2,533 | permissive | [
{
"docstring": "Constructor for the VmDirEntry class",
"name": "__init__",
"signature": "def __init__(self, fstat_info=None, full_path=None, name=None, mtype=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation o... | 2 | null | Implement the Python class `VmDirEntry` described below.
Class description:
Implementation of the 'VmDirEntry' model. VmDirEntry is the struct to represent a file or a folder on a VM. Attributes: fstat_info (FileStatInfo): FstatInfo is the stat information for the file. full_path (string): FullPath is the full path of... | Implement the Python class `VmDirEntry` described below.
Class description:
Implementation of the 'VmDirEntry' model. VmDirEntry is the struct to represent a file or a folder on a VM. Attributes: fstat_info (FileStatInfo): FstatInfo is the stat information for the file. full_path (string): FullPath is the full path of... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class VmDirEntry:
"""Implementation of the 'VmDirEntry' model. VmDirEntry is the struct to represent a file or a folder on a VM. Attributes: fstat_info (FileStatInfo): FstatInfo is the stat information for the file. full_path (string): FullPath is the full path of the file/directory. name (string): Nam... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VmDirEntry:
"""Implementation of the 'VmDirEntry' model. VmDirEntry is the struct to represent a file or a folder on a VM. Attributes: fstat_info (FileStatInfo): FstatInfo is the stat information for the file. full_path (string): FullPath is the full path of the file/directory. name (string): Name is the name... | the_stack_v2_python_sparse | cohesity_management_sdk/models/vm_dir_entry.py | cohesity/management-sdk-python | train | 24 |
63cfb61ea82d11af274acd160ae070c6992fb9d6 | [
"self._commManager = commMngr\nself._machines = set()\nself._relayIter = self._machines.__iter__()\nself._containerIter = self._machines.__iter__()",
"if machine in self._machines:\n raise InternalError('Tried to register the same machine twice.')\nmsg = Message()\nmsg.msgType = msgTypes.COMM_INFO\nmsg.dest = ... | <|body_start_0|>
self._commManager = commMngr
self._machines = set()
self._relayIter = self._machines.__iter__()
self._containerIter = self._machines.__iter__()
<|end_body_0|>
<|body_start_1|>
if machine in self._machines:
raise InternalError('Tried to register the s... | # TODO: Add description | LoadBalancer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadBalancer:
"""# TODO: Add description"""
def __init__(self, commMngr):
"""# TODO: Add description"""
<|body_0|>
def registerMachine(self, machine):
"""Register a new machine in which containers can be started. @param machine: Machine which should be registered... | stack_v2_sparse_classes_36k_train_011438 | 18,143 | permissive | [
{
"docstring": "# TODO: Add description",
"name": "__init__",
"signature": "def __init__(self, commMngr)"
},
{
"docstring": "Register a new machine in which containers can be started. @param machine: Machine which should be registered. @type machine: core.balancer.Machine",
"name": "register... | 5 | stack_v2_sparse_classes_30k_train_019382 | Implement the Python class `LoadBalancer` described below.
Class description:
# TODO: Add description
Method signatures and docstrings:
- def __init__(self, commMngr): # TODO: Add description
- def registerMachine(self, machine): Register a new machine in which containers can be started. @param machine: Machine which... | Implement the Python class `LoadBalancer` described below.
Class description:
# TODO: Add description
Method signatures and docstrings:
- def __init__(self, commMngr): # TODO: Add description
- def registerMachine(self, machine): Register a new machine in which containers can be started. @param machine: Machine which... | c277efd809fce8f0f18b009fb3b9c7f785cc3739 | <|skeleton|>
class LoadBalancer:
"""# TODO: Add description"""
def __init__(self, commMngr):
"""# TODO: Add description"""
<|body_0|>
def registerMachine(self, machine):
"""Register a new machine in which containers can be started. @param machine: Machine which should be registered... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoadBalancer:
"""# TODO: Add description"""
def __init__(self, commMngr):
"""# TODO: Add description"""
self._commManager = commMngr
self._machines = set()
self._relayIter = self._machines.__iter__()
self._containerIter = self._machines.__iter__()
def register... | the_stack_v2_python_sparse | framework/core/machine.py | LCROBOT/rce | train | 0 |
a7761fd27dde869d14df70a5edc58025834e9163 | [
"self.data_train = tfds.load('ted_hrlr_translate/pt_to_en', split='train', as_supervised=True)\nself.data_valid = tfds.load('ted_hrlr_translate/pt_to_en', split='validation', as_supervised=True)\na, b = self.tokenize_dataset(self.data_train)\nself.tokenizer_en = b\nself.tokenizer_pt = a",
"pp = []\nee = []\nfor p... | <|body_start_0|>
self.data_train = tfds.load('ted_hrlr_translate/pt_to_en', split='train', as_supervised=True)
self.data_valid = tfds.load('ted_hrlr_translate/pt_to_en', split='validation', as_supervised=True)
a, b = self.tokenize_dataset(self.data_train)
self.tokenizer_en = b
se... | Class methods | Dataset | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dataset:
"""Class methods"""
def __init__(self):
"""class constructor"""
<|body_0|>
def tokenize_dataset(self, data):
"""creates sub-word tokenizers for our dataset"""
<|body_1|>
def encode(self, pt, en):
"""encodes a translation into tokens"... | stack_v2_sparse_classes_36k_train_011439 | 1,609 | no_license | [
{
"docstring": "class constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "creates sub-word tokenizers for our dataset",
"name": "tokenize_dataset",
"signature": "def tokenize_dataset(self, data)"
},
{
"docstring": "encodes a translation into tok... | 3 | stack_v2_sparse_classes_30k_train_015801 | Implement the Python class `Dataset` described below.
Class description:
Class methods
Method signatures and docstrings:
- def __init__(self): class constructor
- def tokenize_dataset(self, data): creates sub-word tokenizers for our dataset
- def encode(self, pt, en): encodes a translation into tokens | Implement the Python class `Dataset` described below.
Class description:
Class methods
Method signatures and docstrings:
- def __init__(self): class constructor
- def tokenize_dataset(self, data): creates sub-word tokenizers for our dataset
- def encode(self, pt, en): encodes a translation into tokens
<|skeleton|>
c... | 91300120d38acb6440a6dbb8c408b1193c07de88 | <|skeleton|>
class Dataset:
"""Class methods"""
def __init__(self):
"""class constructor"""
<|body_0|>
def tokenize_dataset(self, data):
"""creates sub-word tokenizers for our dataset"""
<|body_1|>
def encode(self, pt, en):
"""encodes a translation into tokens"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dataset:
"""Class methods"""
def __init__(self):
"""class constructor"""
self.data_train = tfds.load('ted_hrlr_translate/pt_to_en', split='train', as_supervised=True)
self.data_valid = tfds.load('ted_hrlr_translate/pt_to_en', split='validation', as_supervised=True)
a, b = ... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/1-dataset.py | anaruzz/holbertonschool-machine_learning | train | 0 |
edfb2b827c14318933570b5d6103647768e0638e | [
"checkin = Checkin(username=username)\ncol = Client().get_collection(guild_id, 'checkin')\ncol.insert_one(checkin.to_dict)",
"col = Client().get_collection(guild_id, 'checkin')\nres = col.find_one({'username': username}, {'_id': False})\ntime_left = res['expire_at'] - datetime.utcnow()\nreturn int(time_left.total... | <|body_start_0|>
checkin = Checkin(username=username)
col = Client().get_collection(guild_id, 'checkin')
col.insert_one(checkin.to_dict)
<|end_body_0|>
<|body_start_1|>
col = Client().get_collection(guild_id, 'checkin')
res = col.find_one({'username': username}, {'_id': False})
... | A class that deals with the checkin collection db. | CheckinService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckinService:
"""A class that deals with the checkin collection db."""
def checkin_user(guild_id: int, username: str):
"""Checks in the user. :param guild_id: the id to identify the db. :param username: the username to add to the users collection. :return: None"""
<|body_0|... | stack_v2_sparse_classes_36k_train_011440 | 1,159 | no_license | [
{
"docstring": "Checks in the user. :param guild_id: the id to identify the db. :param username: the username to add to the users collection. :return: None",
"name": "checkin_user",
"signature": "def checkin_user(guild_id: int, username: str)"
},
{
"docstring": "Checks the remaining time a user ... | 2 | stack_v2_sparse_classes_30k_train_005435 | Implement the Python class `CheckinService` described below.
Class description:
A class that deals with the checkin collection db.
Method signatures and docstrings:
- def checkin_user(guild_id: int, username: str): Checks in the user. :param guild_id: the id to identify the db. :param username: the username to add to... | Implement the Python class `CheckinService` described below.
Class description:
A class that deals with the checkin collection db.
Method signatures and docstrings:
- def checkin_user(guild_id: int, username: str): Checks in the user. :param guild_id: the id to identify the db. :param username: the username to add to... | 60f8c572b0bfce64909f38d91f08ddfda1b40377 | <|skeleton|>
class CheckinService:
"""A class that deals with the checkin collection db."""
def checkin_user(guild_id: int, username: str):
"""Checks in the user. :param guild_id: the id to identify the db. :param username: the username to add to the users collection. :return: None"""
<|body_0|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CheckinService:
"""A class that deals with the checkin collection db."""
def checkin_user(guild_id: int, username: str):
"""Checks in the user. :param guild_id: the id to identify the db. :param username: the username to add to the users collection. :return: None"""
checkin = Checkin(user... | the_stack_v2_python_sparse | src/modules/services/checkin.py | ksyeo1010/poynt | train | 0 |
005e82747d80348c953b99e0be6367fbbde8e836 | [
"self.host = host\nself.port = port\nself.connection = None\nself.database = None\nself.product = None\nself.customer = None\nself.rental = None",
"if self.connection is None:\n try:\n self.connection = MongoClient(self.host, self.port)\n LOGGER.info('connected to mongo')\n LOGGER.info('en... | <|body_start_0|>
self.host = host
self.port = port
self.connection = None
self.database = None
self.product = None
self.customer = None
self.rental = None
<|end_body_0|>
<|body_start_1|>
if self.connection is None:
try:
self.co... | establish MongoDB connection (per assignment's example) | MongoDBConnection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MongoDBConnection:
"""establish MongoDB connection (per assignment's example)"""
def __init__(self, host='127.0.0.1', port=27017):
"""use public ip-address and port"""
<|body_0|>
def __enter__(self):
"""enter"""
<|body_1|>
def __exit__(self, exc_type... | stack_v2_sparse_classes_36k_train_011441 | 7,711 | no_license | [
{
"docstring": "use public ip-address and port",
"name": "__init__",
"signature": "def __init__(self, host='127.0.0.1', port=27017)"
},
{
"docstring": "enter",
"name": "__enter__",
"signature": "def __enter__(self)"
},
{
"docstring": "exit",
"name": "__exit__",
"signature... | 3 | stack_v2_sparse_classes_30k_train_013280 | Implement the Python class `MongoDBConnection` described below.
Class description:
establish MongoDB connection (per assignment's example)
Method signatures and docstrings:
- def __init__(self, host='127.0.0.1', port=27017): use public ip-address and port
- def __enter__(self): enter
- def __exit__(self, exc_type, ex... | Implement the Python class `MongoDBConnection` described below.
Class description:
establish MongoDB connection (per assignment's example)
Method signatures and docstrings:
- def __init__(self, host='127.0.0.1', port=27017): use public ip-address and port
- def __enter__(self): enter
- def __exit__(self, exc_type, ex... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class MongoDBConnection:
"""establish MongoDB connection (per assignment's example)"""
def __init__(self, host='127.0.0.1', port=27017):
"""use public ip-address and port"""
<|body_0|>
def __enter__(self):
"""enter"""
<|body_1|>
def __exit__(self, exc_type... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MongoDBConnection:
"""establish MongoDB connection (per assignment's example)"""
def __init__(self, host='127.0.0.1', port=27017):
"""use public ip-address and port"""
self.host = host
self.port = port
self.connection = None
self.database = None
self.produc... | the_stack_v2_python_sparse | students/florentin_popescu/Lesson_09/database.py | JavaRod/SP_Python220B_2019 | train | 1 |
968a7478ba91e7d8269d1d349a06b0ad7a234713 | [
"self.link_map = {}\nself._parse_links(response)\nself._parse_upcoming(response)\nfor start, links in self.link_map.items():\n meeting = Meeting(title='Commission', description='', classification=COMMISSION, start=start, end=None, all_day=False, time_notes='', location=self.location, links=links, source=response... | <|body_start_0|>
self.link_map = {}
self._parse_links(response)
self._parse_upcoming(response)
for start, links in self.link_map.items():
meeting = Meeting(title='Commission', description='', classification=COMMISSION, start=start, end=None, all_day=False, time_notes='', loca... | ChiSsa26Spider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChiSsa26Spider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs."""
<|body_0|>
def _parse_links(self, response):
"""Parse or generate links."""
<|body... | stack_v2_sparse_classes_36k_train_011442 | 3,351 | permissive | [
{
"docstring": "`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs.",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "Parse or generate links.",
"name": "_parse_links",
"signature": "... | 3 | stack_v2_sparse_classes_30k_train_009977 | Implement the Python class `ChiSsa26Spider` described below.
Class description:
Implement the ChiSsa26Spider class.
Method signatures and docstrings:
- def parse(self, response): `parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs.
- def _pars... | Implement the Python class `ChiSsa26Spider` described below.
Class description:
Implement the ChiSsa26Spider class.
Method signatures and docstrings:
- def parse(self, response): `parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs.
- def _pars... | 611fce6a2705446e25a2fc33e32090a571eb35d1 | <|skeleton|>
class ChiSsa26Spider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs."""
<|body_0|>
def _parse_links(self, response):
"""Parse or generate links."""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChiSsa26Spider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs."""
self.link_map = {}
self._parse_links(response)
self._parse_upcoming(response)
for start, link... | the_stack_v2_python_sparse | city_scrapers/spiders/chi_ssa_26.py | City-Bureau/city-scrapers | train | 308 | |
f6718c95d2fc137a47c3d02148bd1e571c72797f | [
"assert 0 < smoothing < 1, 'Smoothing factor should be in (0.0, 1.0)'\nassert reduction in {'batchmean', 'none', 'sum'}\nsuper().__init__()\nself.smoothing = smoothing\nself.ignore_index = ignore_index\nself.reduction = reduction",
"target = target.view(-1, 1)\nsmoothed_target = torch.zeros(input.shape, requires_... | <|body_start_0|>
assert 0 < smoothing < 1, 'Smoothing factor should be in (0.0, 1.0)'
assert reduction in {'batchmean', 'none', 'sum'}
super().__init__()
self.smoothing = smoothing
self.ignore_index = ignore_index
self.reduction = reduction
<|end_body_0|>
<|body_start_1|... | Computes cross entropy loss with uniformly smoothed targets. | SmoothedCrossEntropyLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SmoothedCrossEntropyLoss:
"""Computes cross entropy loss with uniformly smoothed targets."""
def __init__(self, smoothing: float=0.1, ignore_index: int=-1, reduction: str='batchmean'):
"""Cross entropy loss with uniformly smoothed targets. :param float smoothing: Label smoothing fact... | stack_v2_sparse_classes_36k_train_011443 | 4,120 | permissive | [
{
"docstring": "Cross entropy loss with uniformly smoothed targets. :param float smoothing: Label smoothing factor, between 0 and 1 (exclusive; default is 0.1) :param int ignore_index: Index to be ignored. (PAD_ID by default) :param str reduction: Style of reduction to be done. One of 'batchmean'(default), 'non... | 2 | stack_v2_sparse_classes_30k_train_002046 | Implement the Python class `SmoothedCrossEntropyLoss` described below.
Class description:
Computes cross entropy loss with uniformly smoothed targets.
Method signatures and docstrings:
- def __init__(self, smoothing: float=0.1, ignore_index: int=-1, reduction: str='batchmean'): Cross entropy loss with uniformly smoot... | Implement the Python class `SmoothedCrossEntropyLoss` described below.
Class description:
Computes cross entropy loss with uniformly smoothed targets.
Method signatures and docstrings:
- def __init__(self, smoothing: float=0.1, ignore_index: int=-1, reduction: str='batchmean'): Cross entropy loss with uniformly smoot... | be5595fc5f40f7d281f9318ff26095c0d15ed5da | <|skeleton|>
class SmoothedCrossEntropyLoss:
"""Computes cross entropy loss with uniformly smoothed targets."""
def __init__(self, smoothing: float=0.1, ignore_index: int=-1, reduction: str='batchmean'):
"""Cross entropy loss with uniformly smoothed targets. :param float smoothing: Label smoothing fact... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SmoothedCrossEntropyLoss:
"""Computes cross entropy loss with uniformly smoothed targets."""
def __init__(self, smoothing: float=0.1, ignore_index: int=-1, reduction: str='batchmean'):
"""Cross entropy loss with uniformly smoothed targets. :param float smoothing: Label smoothing factor, between 0... | the_stack_v2_python_sparse | mwptoolkit/loss/smoothed_cross_entropy_loss.py | TalhaAbid/MWPToolkit | train | 0 |
bcd5c3ae1b9bd5f2b68c8487f989775cf5d802b8 | [
"pos = await self.hw_device.get_raw_position()\nassert pos in ('L', 'I'), \"Valve position is 'I' or 'L'\"\nreturn self._reverse_position_mapping[pos]",
"await super().set_position(position)\ntarget_pos = self.position_mapping[position]\nreturn await self.hw_device.set_raw_position(target_pos)"
] | <|body_start_0|>
pos = await self.hw_device.get_raw_position()
assert pos in ('L', 'I'), "Valve position is 'I' or 'L'"
return self._reverse_position_mapping[pos]
<|end_body_0|>
<|body_start_1|>
await super().set_position(position)
target_pos = self.position_mapping[position]
... | KnauerInjectionValve | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KnauerInjectionValve:
async def get_position(self) -> str:
"""Get current valve position."""
<|body_0|>
async def set_position(self, position: str):
"""Move valve to position."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pos = await self.hw_devic... | stack_v2_sparse_classes_36k_train_011444 | 2,692 | permissive | [
{
"docstring": "Get current valve position.",
"name": "get_position",
"signature": "async def get_position(self) -> str"
},
{
"docstring": "Move valve to position.",
"name": "set_position",
"signature": "async def set_position(self, position: str)"
}
] | 2 | null | Implement the Python class `KnauerInjectionValve` described below.
Class description:
Implement the KnauerInjectionValve class.
Method signatures and docstrings:
- async def get_position(self) -> str: Get current valve position.
- async def set_position(self, position: str): Move valve to position. | Implement the Python class `KnauerInjectionValve` described below.
Class description:
Implement the KnauerInjectionValve class.
Method signatures and docstrings:
- async def get_position(self) -> str: Get current valve position.
- async def set_position(self, position: str): Move valve to position.
<|skeleton|>
clas... | 0fbd0626565f95baa9ef890af7d9f7142cb8904e | <|skeleton|>
class KnauerInjectionValve:
async def get_position(self) -> str:
"""Get current valve position."""
<|body_0|>
async def set_position(self, position: str):
"""Move valve to position."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KnauerInjectionValve:
async def get_position(self) -> str:
"""Get current valve position."""
pos = await self.hw_device.get_raw_position()
assert pos in ('L', 'I'), "Valve position is 'I' or 'L'"
return self._reverse_position_mapping[pos]
async def set_position(self, posit... | the_stack_v2_python_sparse | src/flowchem/devices/knauer/knauer_valve_component.py | cambiegroup/flowchem | train | 14 | |
ab0650814e26b6a37b37fef41a14f0f8039a2c14 | [
"try:\n if 'wx_group_id' not in vals:\n wx_officialaccount_id = vals['wx_officialaccount']\n wx_officialaccount = self.env['wx.officialaccount'].search([('id', '=', wx_officialaccount_id)])\n appid = wx_officialaccount.wx_appid\n appsecret = wx_officialaccount.wx_appsecret\n gr... | <|body_start_0|>
try:
if 'wx_group_id' not in vals:
wx_officialaccount_id = vals['wx_officialaccount']
wx_officialaccount = self.env['wx.officialaccount'].search([('id', '=', wx_officialaccount_id)])
appid = wx_officialaccount.wx_appid
... | 实体:微信商品分组 | wx_product_group | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class wx_product_group:
"""实体:微信商品分组"""
def create(self, vals):
"""功能:创建小店分组 :param vals: :return:"""
<|body_0|>
def write(self, vals):
"""功能:更新小店分组 :param vals: :return:"""
<|body_1|>
def unlink(self):
"""功能:删除小店分组 :return:"""
<|body_2|>
... | stack_v2_sparse_classes_36k_train_011445 | 6,138 | no_license | [
{
"docstring": "功能:创建小店分组 :param vals: :return:",
"name": "create",
"signature": "def create(self, vals)"
},
{
"docstring": "功能:更新小店分组 :param vals: :return:",
"name": "write",
"signature": "def write(self, vals)"
},
{
"docstring": "功能:删除小店分组 :return:",
"name": "unlink",
"... | 3 | null | Implement the Python class `wx_product_group` described below.
Class description:
实体:微信商品分组
Method signatures and docstrings:
- def create(self, vals): 功能:创建小店分组 :param vals: :return:
- def write(self, vals): 功能:更新小店分组 :param vals: :return:
- def unlink(self): 功能:删除小店分组 :return: | Implement the Python class `wx_product_group` described below.
Class description:
实体:微信商品分组
Method signatures and docstrings:
- def create(self, vals): 功能:创建小店分组 :param vals: :return:
- def write(self, vals): 功能:更新小店分组 :param vals: :return:
- def unlink(self): 功能:删除小店分组 :return:
<|skeleton|>
class wx_product_group:
... | 5a4fd72991c846d5cb7c5082f6bdfef5b2bca572 | <|skeleton|>
class wx_product_group:
"""实体:微信商品分组"""
def create(self, vals):
"""功能:创建小店分组 :param vals: :return:"""
<|body_0|>
def write(self, vals):
"""功能:更新小店分组 :param vals: :return:"""
<|body_1|>
def unlink(self):
"""功能:删除小店分组 :return:"""
<|body_2|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class wx_product_group:
"""实体:微信商品分组"""
def create(self, vals):
"""功能:创建小店分组 :param vals: :return:"""
try:
if 'wx_group_id' not in vals:
wx_officialaccount_id = vals['wx_officialaccount']
wx_officialaccount = self.env['wx.officialaccount'].search([('i... | the_stack_v2_python_sparse | yuancloud/plugin/wx_shop/models/product_group.py | cash2one/yuancloud | train | 0 |
471768b702e783f9154bc5d1c308bca8df19c5b7 | [
"script = self._getTypeBasedMethod('getBaobabSource')\nif script is not None:\n return script(self, **kw)\nreturn self.aq_parent.getBaobabSource(**kw)",
"script = self._getTypeBasedMethod('getBaobabDestination')\nif script is not None:\n return script(self, **kw)\nreturn self.aq_parent.getBaobabDestination(... | <|body_start_0|>
script = self._getTypeBasedMethod('getBaobabSource')
if script is not None:
return script(self, **kw)
return self.aq_parent.getBaobabSource(**kw)
<|end_body_0|>
<|body_start_1|>
script = self._getTypeBasedMethod('getBaobabDestination')
if script is n... | A Cash DeliveryLine object allows to implement lines in Cash Deliveries (packing list, Check payment, Cash Movement, etc.). It may include a price (for insurance, for customs, for invoices, for orders). | CashDeliveryLine | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CashDeliveryLine:
"""A Cash DeliveryLine object allows to implement lines in Cash Deliveries (packing list, Check payment, Cash Movement, etc.). It may include a price (for insurance, for customs, for invoices, for orders)."""
def getBaobabSource(self, **kw):
"""Returns a calculated ... | stack_v2_sparse_classes_36k_train_011446 | 4,159 | no_license | [
{
"docstring": "Returns a calculated source",
"name": "getBaobabSource",
"signature": "def getBaobabSource(self, **kw)"
},
{
"docstring": "Returns a calculated destination",
"name": "getBaobabDestination",
"signature": "def getBaobabDestination(self, **kw)"
},
{
"docstring": "Ret... | 4 | null | Implement the Python class `CashDeliveryLine` described below.
Class description:
A Cash DeliveryLine object allows to implement lines in Cash Deliveries (packing list, Check payment, Cash Movement, etc.). It may include a price (for insurance, for customs, for invoices, for orders).
Method signatures and docstrings:... | Implement the Python class `CashDeliveryLine` described below.
Class description:
A Cash DeliveryLine object allows to implement lines in Cash Deliveries (packing list, Check payment, Cash Movement, etc.). It may include a price (for insurance, for customs, for invoices, for orders).
Method signatures and docstrings:... | dc02bfa887ffab9841abebc3f5c16d874388cef5 | <|skeleton|>
class CashDeliveryLine:
"""A Cash DeliveryLine object allows to implement lines in Cash Deliveries (packing list, Check payment, Cash Movement, etc.). It may include a price (for insurance, for customs, for invoices, for orders)."""
def getBaobabSource(self, **kw):
"""Returns a calculated ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CashDeliveryLine:
"""A Cash DeliveryLine object allows to implement lines in Cash Deliveries (packing list, Check payment, Cash Movement, etc.). It may include a price (for insurance, for customs, for invoices, for orders)."""
def getBaobabSource(self, **kw):
"""Returns a calculated source"""
... | the_stack_v2_python_sparse | bt5/erp5_banking_core/DocumentTemplateItem/portal_components/document.erp5.CashDeliveryLine.py | jgpjuniorj/j | train | 1 |
0ed4c611f606d32470e24993c68fc6ee07bdfbbc | [
"query = urllib.parse.quote(query)\nurl = 'https://www.youtube.com/results?search_query=' + query\nrespone = urllib.request.urlopen(url)\nhtml = respone.read()\nsoup = BeautifulSoup(html, 'html.parser')\nres = soup.find_all(attrs={'class': 'yt-uix-tile-link'})[0]['href']\nif len(res) > 20 or res.find('user') != -1:... | <|body_start_0|>
query = urllib.parse.quote(query)
url = 'https://www.youtube.com/results?search_query=' + query
respone = urllib.request.urlopen(url)
html = respone.read()
soup = BeautifulSoup(html, 'html.parser')
res = soup.find_all(attrs={'class': 'yt-uix-tile-link'})[... | Searches youtube for videos using the BeautifulSoup Library | YouTube | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YouTube:
"""Searches youtube for videos using the BeautifulSoup Library"""
def find_first(query):
"""Fint the first result from youtube :param query: topic to look for :return: link/url to the video"""
<|body_0|>
def rand_find(query):
"""Returns a random result o... | stack_v2_sparse_classes_36k_train_011447 | 1,411 | no_license | [
{
"docstring": "Fint the first result from youtube :param query: topic to look for :return: link/url to the video",
"name": "find_first",
"signature": "def find_first(query)"
},
{
"docstring": "Returns a random result of a youtube video for a topic :param query: topic :return: link/url to the vi... | 2 | stack_v2_sparse_classes_30k_train_013106 | Implement the Python class `YouTube` described below.
Class description:
Searches youtube for videos using the BeautifulSoup Library
Method signatures and docstrings:
- def find_first(query): Fint the first result from youtube :param query: topic to look for :return: link/url to the video
- def rand_find(query): Retu... | Implement the Python class `YouTube` described below.
Class description:
Searches youtube for videos using the BeautifulSoup Library
Method signatures and docstrings:
- def find_first(query): Fint the first result from youtube :param query: topic to look for :return: link/url to the video
- def rand_find(query): Retu... | f9360a57e4118b6c85373165659d96e8697764e4 | <|skeleton|>
class YouTube:
"""Searches youtube for videos using the BeautifulSoup Library"""
def find_first(query):
"""Fint the first result from youtube :param query: topic to look for :return: link/url to the video"""
<|body_0|>
def rand_find(query):
"""Returns a random result o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class YouTube:
"""Searches youtube for videos using the BeautifulSoup Library"""
def find_first(query):
"""Fint the first result from youtube :param query: topic to look for :return: link/url to the video"""
query = urllib.parse.quote(query)
url = 'https://www.youtube.com/results?search... | the_stack_v2_python_sparse | src/commands/Youtube/youtube.py | AlexandruLis/Discord-Py-Bot | train | 1 |
47a85fa77491dc7588f4828becadd070abc5390f | [
"\"\"\"\n Classification 1: consider two neighbors\n i, i+1 can not be robbed at the same time, so either i is not robbed or i+1 is not robbed.\n when i is not robbed, i-1 and i+1 can be any status robbed/un-robbed, it's like the houses are in a line\n when i+1 is not robbed, i and i+2 c... | <|body_start_0|>
"""
Classification 1: consider two neighbors
i, i+1 can not be robbed at the same time, so either i is not robbed or i+1 is not robbed.
when i is not robbed, i-1 and i+1 can be any status robbed/un-robbed, it's like the houses are in a line
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rob_line_case(nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
"""
Classification 1: consider two neighb... | stack_v2_sparse_classes_36k_train_011448 | 1,926 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob",
"signature": "def rob(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob_line_case",
"signature": "def rob_line_case(nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def rob_line_case(nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def rob_line_case(nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def rob(self, nums):
... | b6942c05c27556e5fe47879e8b823845c84c5430 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rob_line_case(nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
"""
Classification 1: consider two neighbors
i, i+1 can not be robbed at the same time, so either i is not robbed or i+1 is not robbed.
when i is not robbed, i-1 and i+1 can b... | the_stack_v2_python_sparse | Algorithms/leetcode/213_house_robber_II.py | leeo1116/PyCharm | train | 0 | |
d2d3e1bb2665b61bd62616e966193fcb1b26e2af | [
"def short_addr():\n ans = ''\n tmp = ''\n for i in range(6):\n tmp = letters[random.randint(0, 10000) % 62]\n ans += tmp\n return ans\nif longUrl in full_tiny:\n return 'http://tinyurl.com/' + full_tiny[longUrl]\nelse:\n suffix = short_addr()\n full_tiny[longUrl] = suffix\n ti... | <|body_start_0|>
def short_addr():
ans = ''
tmp = ''
for i in range(6):
tmp = letters[random.randint(0, 10000) % 62]
ans += tmp
return ans
if longUrl in full_tiny:
return 'http://tinyurl.com/' + full_tiny[longUrl... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, longUrl):
"""encode a url to a shortened url type longUrl: str rtype: str"""
<|body_0|>
def decode(self, shortUrl):
"""decode a shortened url to its original url type shortUrl : str rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_36k_train_011449 | 1,319 | no_license | [
{
"docstring": "encode a url to a shortened url type longUrl: str rtype: str",
"name": "encode",
"signature": "def encode(self, longUrl)"
},
{
"docstring": "decode a shortened url to its original url type shortUrl : str rtype: str",
"name": "decode",
"signature": "def decode(self, shortU... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, longUrl): encode a url to a shortened url type longUrl: str rtype: str
- def decode(self, shortUrl): decode a shortened url to its original url type shortUrl : str rty... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, longUrl): encode a url to a shortened url type longUrl: str rtype: str
- def decode(self, shortUrl): decode a shortened url to its original url type shortUrl : str rty... | 1804863ca931abedbbb8053bcc771115d0c23a2d | <|skeleton|>
class Codec:
def encode(self, longUrl):
"""encode a url to a shortened url type longUrl: str rtype: str"""
<|body_0|>
def decode(self, shortUrl):
"""decode a shortened url to its original url type shortUrl : str rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, longUrl):
"""encode a url to a shortened url type longUrl: str rtype: str"""
def short_addr():
ans = ''
tmp = ''
for i in range(6):
tmp = letters[random.randint(0, 10000) % 62]
ans += tmp
re... | the_stack_v2_python_sparse | leetcode/encode_decode_tinyurl.py | PyRPy/algorithms_books | train | 1 | |
c0772d4905c32cf14023d31fb1d1b80ed1b02d51 | [
"if BucketListItem.query.filter_by(bucketlist_id=bucketlist_id).filter(BucketListItem.name.ilike(item)).first():\n return True\nreturn False",
"if completed is not None:\n self.completed = completed\nif name is None and completed is None:\n name = self.name\nif name is None and completed is not None:\n ... | <|body_start_0|>
if BucketListItem.query.filter_by(bucketlist_id=bucketlist_id).filter(BucketListItem.name.ilike(item)).first():
return True
return False
<|end_body_0|>
<|body_start_1|>
if completed is not None:
self.completed = completed
if name is None and comp... | Class used as a representation of the bucketlist item model | BucketListItem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BucketListItem:
"""Class used as a representation of the bucketlist item model"""
def __item_exists(self, item, bucketlist_id):
"""Method is used to verify that a bucketlist name exists in the database"""
<|body_0|>
def save_bucketlist_item(self, name=None, completed=Non... | stack_v2_sparse_classes_36k_train_011450 | 1,790 | no_license | [
{
"docstring": "Method is used to verify that a bucketlist name exists in the database",
"name": "__item_exists",
"signature": "def __item_exists(self, item, bucketlist_id)"
},
{
"docstring": "Method is used to add a bucketlist item to the database",
"name": "save_bucketlist_item",
"sign... | 3 | stack_v2_sparse_classes_30k_train_007826 | Implement the Python class `BucketListItem` described below.
Class description:
Class used as a representation of the bucketlist item model
Method signatures and docstrings:
- def __item_exists(self, item, bucketlist_id): Method is used to verify that a bucketlist name exists in the database
- def save_bucketlist_ite... | Implement the Python class `BucketListItem` described below.
Class description:
Class used as a representation of the bucketlist item model
Method signatures and docstrings:
- def __item_exists(self, item, bucketlist_id): Method is used to verify that a bucketlist name exists in the database
- def save_bucketlist_ite... | 6bc4dfaa5dc97ecaeb808a71f29dca92bc0eb4d1 | <|skeleton|>
class BucketListItem:
"""Class used as a representation of the bucketlist item model"""
def __item_exists(self, item, bucketlist_id):
"""Method is used to verify that a bucketlist name exists in the database"""
<|body_0|>
def save_bucketlist_item(self, name=None, completed=Non... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BucketListItem:
"""Class used as a representation of the bucketlist item model"""
def __item_exists(self, item, bucketlist_id):
"""Method is used to verify that a bucketlist name exists in the database"""
if BucketListItem.query.filter_by(bucketlist_id=bucketlist_id).filter(BucketListItem... | the_stack_v2_python_sparse | myapp/models/bucketlist_item.py | malmike/BucketListAPI | train | 0 |
5e979f0b17c07e64bdf52808dcdc16fe2b2671b6 | [
"data_type_dict = {'base_station_set': BaseStation, 'mec_set': Mec, 'hmds_set': VrHMD}\nprint(f'\\n*** decoding {str(data_type_dict[data_type])} objects ***')\nfor key, value in data_set[data_type].items():\n data_type_object = data_type_dict[data_type].from_dict(value)\n data_set[data_type][key] = data_type_... | <|body_start_0|>
data_type_dict = {'base_station_set': BaseStation, 'mec_set': Mec, 'hmds_set': VrHMD}
print(f'\n*** decoding {str(data_type_dict[data_type])} objects ***')
for key, value in data_set[data_type].items():
data_type_object = data_type_dict[data_type].from_dict(value)
... | provides methods to decoding json data | DecoderController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecoderController:
"""provides methods to decoding json data"""
def decoder_to_dict_objects(data_set: dict, data_type: str) -> None:
"""decodes a dict of json objects into BaseStations, Mecs, or VrHMD objects"""
<|body_0|>
def decoding_to_dict(data_directory: str, file_n... | stack_v2_sparse_classes_36k_train_011451 | 4,620 | no_license | [
{
"docstring": "decodes a dict of json objects into BaseStations, Mecs, or VrHMD objects",
"name": "decoder_to_dict_objects",
"signature": "def decoder_to_dict_objects(data_set: dict, data_type: str) -> None"
},
{
"docstring": "decodes a file of json objects into dict of BaseStations, Mecs, or V... | 5 | null | Implement the Python class `DecoderController` described below.
Class description:
provides methods to decoding json data
Method signatures and docstrings:
- def decoder_to_dict_objects(data_set: dict, data_type: str) -> None: decodes a dict of json objects into BaseStations, Mecs, or VrHMD objects
- def decoding_to_... | Implement the Python class `DecoderController` described below.
Class description:
provides methods to decoding json data
Method signatures and docstrings:
- def decoder_to_dict_objects(data_set: dict, data_type: str) -> None: decodes a dict of json objects into BaseStations, Mecs, or VrHMD objects
- def decoding_to_... | e3e022a14058936619f1d79d11dbbb4f6f48d531 | <|skeleton|>
class DecoderController:
"""provides methods to decoding json data"""
def decoder_to_dict_objects(data_set: dict, data_type: str) -> None:
"""decodes a dict of json objects into BaseStations, Mecs, or VrHMD objects"""
<|body_0|>
def decoding_to_dict(data_directory: str, file_n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DecoderController:
"""provides methods to decoding json data"""
def decoder_to_dict_objects(data_set: dict, data_type: str) -> None:
"""decodes a dict of json objects into BaseStations, Mecs, or VrHMD objects"""
data_type_dict = {'base_station_set': BaseStation, 'mec_set': Mec, 'hmds_set'... | the_stack_v2_python_sparse | controllers/json_controller.py | alissonpmedeiros/scg | train | 0 |
d23782d0b5b95b2ad4e09096f9230f5cd3449ae8 | [
"self.ans = len(nums)\nfor i in range(len(nums)):\n for j in range(i, len(nums) + 1):\n min_ = 1000000000.0\n max_ = prev_ = -1000000000.0\n for k in range(i, j):\n min_ = min(min_, nums[k])\n max_ = max(max_, nums[k])\n if i > 0 and nums[i - 1] > min_ or (j < le... | <|body_start_0|>
self.ans = len(nums)
for i in range(len(nums)):
for j in range(i, len(nums) + 1):
min_ = 1000000000.0
max_ = prev_ = -1000000000.0
for k in range(i, j):
min_ = min(min_, nums[k])
max_ = m... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def BrutalSearch(self, nums: [int]) -> int:
"""暴力求解,设最短无序子串为nums[i:j],则整个数组满足 1. nums[0:i-1] < min(nums[i:j]) 且 nums[j:n-1] > max(nums[i:j]) 2. nums[0:i-1] 和 nums[j:n-1] 都是升序的"""
<|body_0|>
def BrutalWizSelectSort(self, nums: [int]) -> int:
"""借鉴选择排序的思想,对nu... | stack_v2_sparse_classes_36k_train_011452 | 2,287 | no_license | [
{
"docstring": "暴力求解,设最短无序子串为nums[i:j],则整个数组满足 1. nums[0:i-1] < min(nums[i:j]) 且 nums[j:n-1] > max(nums[i:j]) 2. nums[0:i-1] 和 nums[j:n-1] 都是升序的",
"name": "BrutalSearch",
"signature": "def BrutalSearch(self, nums: [int]) -> int"
},
{
"docstring": "借鉴选择排序的思想,对nums中的每个nums[i],寻找到他的正确位置, 即如果nums[i]... | 3 | stack_v2_sparse_classes_30k_train_009787 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def BrutalSearch(self, nums: [int]) -> int: 暴力求解,设最短无序子串为nums[i:j],则整个数组满足 1. nums[0:i-1] < min(nums[i:j]) 且 nums[j:n-1] > max(nums[i:j]) 2. nums[0:i-1] 和 nums[j:n-1] 都是升序的
- def... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def BrutalSearch(self, nums: [int]) -> int: 暴力求解,设最短无序子串为nums[i:j],则整个数组满足 1. nums[0:i-1] < min(nums[i:j]) 且 nums[j:n-1] > max(nums[i:j]) 2. nums[0:i-1] 和 nums[j:n-1] 都是升序的
- def... | 9a749ea81b353ed41993bd03dae4bceb46d795a2 | <|skeleton|>
class Solution:
def BrutalSearch(self, nums: [int]) -> int:
"""暴力求解,设最短无序子串为nums[i:j],则整个数组满足 1. nums[0:i-1] < min(nums[i:j]) 且 nums[j:n-1] > max(nums[i:j]) 2. nums[0:i-1] 和 nums[j:n-1] 都是升序的"""
<|body_0|>
def BrutalWizSelectSort(self, nums: [int]) -> int:
"""借鉴选择排序的思想,对nu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def BrutalSearch(self, nums: [int]) -> int:
"""暴力求解,设最短无序子串为nums[i:j],则整个数组满足 1. nums[0:i-1] < min(nums[i:j]) 且 nums[j:n-1] > max(nums[i:j]) 2. nums[0:i-1] 和 nums[j:n-1] 都是升序的"""
self.ans = len(nums)
for i in range(len(nums)):
for j in range(i, len(nums) + 1):
... | the_stack_v2_python_sparse | top100/python/easy/581_Shortest_Unsorted_Continuous_Subarray.py | zbw0034/coding-practise | train | 0 | |
2afd2f4bf803f1c7b94b4dfeaea99c6b90f336a1 | [
"p = super().Params()\np.Define('input_dims', 0, 'Depth of the input to the network.')\np.Define('epsilon', 1e-06, 'Tiny value to guard rsqrt.')\np.Define('direct_scale', True, 'Whether to apply scale directly without a +1.0. Var is initialized to 1.0 instead when true. This makes the weight compatible with the imp... | <|body_start_0|>
p = super().Params()
p.Define('input_dims', 0, 'Depth of the input to the network.')
p.Define('epsilon', 1e-06, 'Tiny value to guard rsqrt.')
p.Define('direct_scale', True, 'Whether to apply scale directly without a +1.0. Var is initialized to 1.0 instead when true. This... | RMS normalization: https://arxiv.org/abs/1910.07467. | RmsNorm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RmsNorm:
"""RMS normalization: https://arxiv.org/abs/1910.07467."""
def Params(cls) -> InstantiableParams:
"""Returns the layer params with RMS Norm specific params."""
<|body_0|>
def create_layer_variables(self) -> None:
"""Creates RMS normalization variables.""... | stack_v2_sparse_classes_36k_train_011453 | 17,959 | permissive | [
{
"docstring": "Returns the layer params with RMS Norm specific params.",
"name": "Params",
"signature": "def Params(cls) -> InstantiableParams"
},
{
"docstring": "Creates RMS normalization variables.",
"name": "create_layer_variables",
"signature": "def create_layer_variables(self) -> N... | 3 | null | Implement the Python class `RmsNorm` described below.
Class description:
RMS normalization: https://arxiv.org/abs/1910.07467.
Method signatures and docstrings:
- def Params(cls) -> InstantiableParams: Returns the layer params with RMS Norm specific params.
- def create_layer_variables(self) -> None: Creates RMS norma... | Implement the Python class `RmsNorm` described below.
Class description:
RMS normalization: https://arxiv.org/abs/1910.07467.
Method signatures and docstrings:
- def Params(cls) -> InstantiableParams: Returns the layer params with RMS Norm specific params.
- def create_layer_variables(self) -> None: Creates RMS norma... | c00a74b260fcf6ba11199cc4a340c127d6616479 | <|skeleton|>
class RmsNorm:
"""RMS normalization: https://arxiv.org/abs/1910.07467."""
def Params(cls) -> InstantiableParams:
"""Returns the layer params with RMS Norm specific params."""
<|body_0|>
def create_layer_variables(self) -> None:
"""Creates RMS normalization variables.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RmsNorm:
"""RMS normalization: https://arxiv.org/abs/1910.07467."""
def Params(cls) -> InstantiableParams:
"""Returns the layer params with RMS Norm specific params."""
p = super().Params()
p.Define('input_dims', 0, 'Depth of the input to the network.')
p.Define('epsilon',... | the_stack_v2_python_sparse | lingvo/jax/layers/normalizations.py | tensorflow/lingvo | train | 2,963 |
29be655c552af3053a04b4cd5b8b6ff9090ed901 | [
"self.periodic_boundaries = periodic_boundaries\nself.axes = numpy.array(Space.AXES[axes])\nself.scale_factor = scale_factor\nself.offset = offset",
"if len(A.shape) == 1:\n A = A.reshape(3, 1)\nif len(B.shape) == 1:\n B = B.reshape(3, 1)\nB = self.scale_factor * (B + self.offset)\nd = numpy.zeros((len(self... | <|body_start_0|>
self.periodic_boundaries = periodic_boundaries
self.axes = numpy.array(Space.AXES[axes])
self.scale_factor = scale_factor
self.offset = offset
<|end_body_0|>
<|body_start_1|>
if len(A.shape) == 1:
A = A.reshape(3, 1)
if len(B.shape) == 1:
... | Class representing a space within distances can be calculated. The space is Cartesian, may be 1-, 2- or 3-dimensional, and may have periodic boundaries in any of the dimensions. | Space | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Space:
"""Class representing a space within distances can be calculated. The space is Cartesian, may be 1-, 2- or 3-dimensional, and may have periodic boundaries in any of the dimensions."""
def __init__(self, axes=None, scale_factor=1.0, offset=0.0, periodic_boundaries=None):
"""axe... | stack_v2_sparse_classes_36k_train_011454 | 11,343 | permissive | [
{
"docstring": "axes -- if not supplied, then the 3D distance is calculated. If supplied, axes should be a string containing the axes to be used, e.g. 'x', or 'yz'. axes='xyz' is the same as axes=None. scale_factor -- it may be that the pre and post populations use different units for position, e.g. degrees and... | 3 | stack_v2_sparse_classes_30k_train_005639 | Implement the Python class `Space` described below.
Class description:
Class representing a space within distances can be calculated. The space is Cartesian, may be 1-, 2- or 3-dimensional, and may have periodic boundaries in any of the dimensions.
Method signatures and docstrings:
- def __init__(self, axes=None, sca... | Implement the Python class `Space` described below.
Class description:
Class representing a space within distances can be calculated. The space is Cartesian, may be 1-, 2- or 3-dimensional, and may have periodic boundaries in any of the dimensions.
Method signatures and docstrings:
- def __init__(self, axes=None, sca... | 04fa1eaf78778edea3ba3afa4c527d20c491718e | <|skeleton|>
class Space:
"""Class representing a space within distances can be calculated. The space is Cartesian, may be 1-, 2- or 3-dimensional, and may have periodic boundaries in any of the dimensions."""
def __init__(self, axes=None, scale_factor=1.0, offset=0.0, periodic_boundaries=None):
"""axe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Space:
"""Class representing a space within distances can be calculated. The space is Cartesian, may be 1-, 2- or 3-dimensional, and may have periodic boundaries in any of the dimensions."""
def __init__(self, axes=None, scale_factor=1.0, offset=0.0, periodic_boundaries=None):
"""axes -- if not s... | the_stack_v2_python_sparse | src/spinnaker_ros_lsm/venv/lib/python2.7/site-packages/pyNN/space.py | Roboy/LSM_SpiNNaker_MyoArm | train | 2 |
e296f1f95e06fdb88e65f859e27c27d7ebaf782e | [
"cnt = Counter(nums)\nkeys = sorted(cnt.keys(), key=lambda x: x * cnt[x], reverse=True)\nfor k in keys:\n print(k, cnt[k])\nret = 0\nvisited = set()\nfor k in keys:\n if k in visited:\n continue\n ret += k * cnt[k]\n visited.add(k - 1)\n visited.add(k + 1)\nreturn ret",
"cnt = Counter(nums)\... | <|body_start_0|>
cnt = Counter(nums)
keys = sorted(cnt.keys(), key=lambda x: x * cnt[x], reverse=True)
for k in keys:
print(k, cnt[k])
ret = 0
visited = set()
for k in keys:
if k in visited:
continue
ret += k * cnt[k]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
"""Wrong"""
<|body_0|>
def deleteAndEarn(self, nums: List[int]) -> int:
"""09/05/2020 13:01"""
<|body_1|>
def deleteAndEarn(self, nums: List[int]) -> int:
"""TLE"""
<|body_2|>
... | stack_v2_sparse_classes_36k_train_011455 | 6,670 | no_license | [
{
"docstring": "Wrong",
"name": "deleteAndEarn",
"signature": "def deleteAndEarn(self, nums: List[int]) -> int"
},
{
"docstring": "09/05/2020 13:01",
"name": "deleteAndEarn",
"signature": "def deleteAndEarn(self, nums: List[int]) -> int"
},
{
"docstring": "TLE",
"name": "dele... | 6 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteAndEarn(self, nums: List[int]) -> int: Wrong
- def deleteAndEarn(self, nums: List[int]) -> int: 09/05/2020 13:01
- def deleteAndEarn(self, nums: List[int]) -> int: TLE
... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteAndEarn(self, nums: List[int]) -> int: Wrong
- def deleteAndEarn(self, nums: List[int]) -> int: 09/05/2020 13:01
- def deleteAndEarn(self, nums: List[int]) -> int: TLE
... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
"""Wrong"""
<|body_0|>
def deleteAndEarn(self, nums: List[int]) -> int:
"""09/05/2020 13:01"""
<|body_1|>
def deleteAndEarn(self, nums: List[int]) -> int:
"""TLE"""
<|body_2|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
"""Wrong"""
cnt = Counter(nums)
keys = sorted(cnt.keys(), key=lambda x: x * cnt[x], reverse=True)
for k in keys:
print(k, cnt[k])
ret = 0
visited = set()
for k in keys:
if... | the_stack_v2_python_sparse | leetcode/solved/740_Delete_and_Earn/solution.py | sungminoh/algorithms | train | 0 | |
3426ce021077b9f136c04fb2e0254e26b2bcce31 | [
"container = self\nparent_item = None\nfor item_name in item_names:\n item = ui.Block(By.XPATH, self._item_selector.format(item_name))\n item.container = container\n if not item.webelement.is_displayed() and parent_item:\n parent_item.click()\n wait(item.webelement.is_displayed, timeout_secon... | <|body_start_0|>
container = self
parent_item = None
for item_name in item_names:
item = ui.Block(By.XPATH, self._item_selector.format(item_name))
item.container = container
if not item.webelement.is_displayed() and parent_item:
parent_item.cli... | Navigate menu. | NavigateMenu | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NavigateMenu:
"""Navigate menu."""
def go_to(self, item_names):
"""Go to page via navigate menu. Arguments: - item_names: list of items of navigate menu."""
<|body_0|>
def has_item(self, item_names):
"""Check that navigate menu has item. Args: item_names (list): ... | stack_v2_sparse_classes_36k_train_011456 | 2,545 | no_license | [
{
"docstring": "Go to page via navigate menu. Arguments: - item_names: list of items of navigate menu.",
"name": "go_to",
"signature": "def go_to(self, item_names)"
},
{
"docstring": "Check that navigate menu has item. Args: item_names (list): list of items of navigate menu. Returns: bool: is it... | 2 | stack_v2_sparse_classes_30k_test_000026 | Implement the Python class `NavigateMenu` described below.
Class description:
Navigate menu.
Method signatures and docstrings:
- def go_to(self, item_names): Go to page via navigate menu. Arguments: - item_names: list of items of navigate menu.
- def has_item(self, item_names): Check that navigate menu has item. Args... | Implement the Python class `NavigateMenu` described below.
Class description:
Navigate menu.
Method signatures and docstrings:
- def go_to(self, item_names): Go to page via navigate menu. Arguments: - item_names: list of items of navigate menu.
- def has_item(self, item_names): Check that navigate menu has item. Args... | e7583444cd24893ec6ae237b47db7c605b99b0c5 | <|skeleton|>
class NavigateMenu:
"""Navigate menu."""
def go_to(self, item_names):
"""Go to page via navigate menu. Arguments: - item_names: list of items of navigate menu."""
<|body_0|>
def has_item(self, item_names):
"""Check that navigate menu has item. Args: item_names (list): ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NavigateMenu:
"""Navigate menu."""
def go_to(self, item_names):
"""Go to page via navigate menu. Arguments: - item_names: list of items of navigate menu."""
container = self
parent_item = None
for item_name in item_names:
item = ui.Block(By.XPATH, self._item_se... | the_stack_v2_python_sparse | stepler/horizon/app/ui/navigate_menu.py | Mirantis/stepler | train | 16 |
e26234a67f3341844e1e1f056f8a5ca1b9d66456 | [
"question = 'Jaki jest Twoj ojczysty język?'\nmy_survey = AnonymousSurvey(question)\nmy_survey.store_response('angielski')\nself.assertIn('angielski', my_survey.responses)",
"question = 'Jaki jest Twoj ojczysty język?'\nmy_survey = AnonymousSurvey(question)\nresponses = ['angielski', 'hiszpański', 'polski']\nfor ... | <|body_start_0|>
question = 'Jaki jest Twoj ojczysty język?'
my_survey = AnonymousSurvey(question)
my_survey.store_response('angielski')
self.assertIn('angielski', my_survey.responses)
<|end_body_0|>
<|body_start_1|>
question = 'Jaki jest Twoj ojczysty język?'
my_survey ... | Testy dla klasy AnonymousSurvey. | TestAnonymousSurvey | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAnonymousSurvey:
"""Testy dla klasy AnonymousSurvey."""
def test_store_single_response(self):
"""Sprawdzenie, czy pojedyncza odpowiedź jest prawidłowo przechowywana."""
<|body_0|>
def test_store_three_responses(self):
"""Sprawdzenie, czy trzy pojedyncze odpow... | stack_v2_sparse_classes_36k_train_011457 | 1,128 | no_license | [
{
"docstring": "Sprawdzenie, czy pojedyncza odpowiedź jest prawidłowo przechowywana.",
"name": "test_store_single_response",
"signature": "def test_store_single_response(self)"
},
{
"docstring": "Sprawdzenie, czy trzy pojedyncze odpowiedzi są prawidłowo przechowywane.",
"name": "test_store_t... | 2 | null | Implement the Python class `TestAnonymousSurvey` described below.
Class description:
Testy dla klasy AnonymousSurvey.
Method signatures and docstrings:
- def test_store_single_response(self): Sprawdzenie, czy pojedyncza odpowiedź jest prawidłowo przechowywana.
- def test_store_three_responses(self): Sprawdzenie, czy ... | Implement the Python class `TestAnonymousSurvey` described below.
Class description:
Testy dla klasy AnonymousSurvey.
Method signatures and docstrings:
- def test_store_single_response(self): Sprawdzenie, czy pojedyncza odpowiedź jest prawidłowo przechowywana.
- def test_store_three_responses(self): Sprawdzenie, czy ... | 969f95132822d8bd21c30403d8e0bf6aadb9914f | <|skeleton|>
class TestAnonymousSurvey:
"""Testy dla klasy AnonymousSurvey."""
def test_store_single_response(self):
"""Sprawdzenie, czy pojedyncza odpowiedź jest prawidłowo przechowywana."""
<|body_0|>
def test_store_three_responses(self):
"""Sprawdzenie, czy trzy pojedyncze odpow... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestAnonymousSurvey:
"""Testy dla klasy AnonymousSurvey."""
def test_store_single_response(self):
"""Sprawdzenie, czy pojedyncza odpowiedź jest prawidłowo przechowywana."""
question = 'Jaki jest Twoj ojczysty język?'
my_survey = AnonymousSurvey(question)
my_survey.store_re... | the_stack_v2_python_sparse | ksiazka_zrob_to_sam/test_survey.py | Licho59/learning_python_eric_matthes_book | train | 0 |
97bad25f3aa902e1c20af54c10181736dfe96e8a | [
"min_price = float('int')\nmax_profit = 0\nfor price in prices:\n min_price = min(price, min_price)\n max_profit = max(price - min_price, max_profit)\nreturn max_profit",
"profit = 0\nmax_profit = 0\nfor idx in range(1, len(prices)):\n profit = max(profit, 0) + prices[idx] - prices[idx - 1]\n max_prof... | <|body_start_0|>
min_price = float('int')
max_profit = 0
for price in prices:
min_price = min(price, min_price)
max_profit = max(price - min_price, max_profit)
return max_profit
<|end_body_0|>
<|body_start_1|>
profit = 0
max_profit = 0
for... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""遍历数组"""
<|body_0|>
def maxProfitDP(self, prices: List[int]) -> int:
"""动态规划"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
min_price = float('int')
max_profit = 0
for price... | stack_v2_sparse_classes_36k_train_011458 | 1,140 | no_license | [
{
"docstring": "遍历数组",
"name": "maxProfit",
"signature": "def maxProfit(self, prices: List[int]) -> int"
},
{
"docstring": "动态规划",
"name": "maxProfitDP",
"signature": "def maxProfitDP(self, prices: List[int]) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices: List[int]) -> int: 遍历数组
- def maxProfitDP(self, prices: List[int]) -> int: 动态规划 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices: List[int]) -> int: 遍历数组
- def maxProfitDP(self, prices: List[int]) -> int: 动态规划
<|skeleton|>
class Solution:
def maxProfit(self, prices: List[in... | 52756b30e9d51794591aca030bc918e707f473f1 | <|skeleton|>
class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""遍历数组"""
<|body_0|>
def maxProfitDP(self, prices: List[int]) -> int:
"""动态规划"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""遍历数组"""
min_price = float('int')
max_profit = 0
for price in prices:
min_price = min(price, min_price)
max_profit = max(price - min_price, max_profit)
return max_profit
def maxProfi... | the_stack_v2_python_sparse | 121.买卖股票的最佳时机/solution.py | QtTao/daily_leetcode | train | 0 | |
f977ba1bab53dec232d62c2e52731d2bf6ee8451 | [
"self.path_params = {'ver': self.version[release]}\nself.summary_file = self.get_path('mangagz3dmetadata', path_params=self.path_params)\nself.center_summary_file = self.get_path('mangagz3dcenters', path_params=self.path_params)\nself.stars_summary_file = self.get_path('mangagz3dstars', path_params=self.path_params... | <|body_start_0|>
self.path_params = {'ver': self.version[release]}
self.summary_file = self.get_path('mangagz3dmetadata', path_params=self.path_params)
self.center_summary_file = self.get_path('mangagz3dcenters', path_params=self.path_params)
self.stars_summary_file = self.get_path('mang... | Provides access to the Galaxy Zoo 3D spaxel masks. VAC name: Galaxy Zoo: 3D URL: https://www.sdss.org/dr17/data_access/value-added-catalogs/?vac_id=galaxy-zoo-3d Description: Galaxy Zoo: 3D (GZ: 3D) made use of a project on the Zooniverse platform to crowdsource spaxel masks locating galaxy centers, foreground stars, b... | GZ3DVAC | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GZ3DVAC:
"""Provides access to the Galaxy Zoo 3D spaxel masks. VAC name: Galaxy Zoo: 3D URL: https://www.sdss.org/dr17/data_access/value-added-catalogs/?vac_id=galaxy-zoo-3d Description: Galaxy Zoo: 3D (GZ: 3D) made use of a project on the Zooniverse platform to crowdsource spaxel masks locating ... | stack_v2_sparse_classes_36k_train_011459 | 47,753 | permissive | [
{
"docstring": "Sets the path to the GalaxyZoo3D summary file",
"name": "set_summary_file",
"signature": "def set_summary_file(self, release)"
},
{
"docstring": "Find the GZ3D data based on the manga ID",
"name": "get_target",
"signature": "def get_target(self, parent_object)"
}
] | 2 | null | Implement the Python class `GZ3DVAC` described below.
Class description:
Provides access to the Galaxy Zoo 3D spaxel masks. VAC name: Galaxy Zoo: 3D URL: https://www.sdss.org/dr17/data_access/value-added-catalogs/?vac_id=galaxy-zoo-3d Description: Galaxy Zoo: 3D (GZ: 3D) made use of a project on the Zooniverse platfor... | Implement the Python class `GZ3DVAC` described below.
Class description:
Provides access to the Galaxy Zoo 3D spaxel masks. VAC name: Galaxy Zoo: 3D URL: https://www.sdss.org/dr17/data_access/value-added-catalogs/?vac_id=galaxy-zoo-3d Description: Galaxy Zoo: 3D (GZ: 3D) made use of a project on the Zooniverse platfor... | db4c536a65fb2f16fee05a4f34996a7fd35f0527 | <|skeleton|>
class GZ3DVAC:
"""Provides access to the Galaxy Zoo 3D spaxel masks. VAC name: Galaxy Zoo: 3D URL: https://www.sdss.org/dr17/data_access/value-added-catalogs/?vac_id=galaxy-zoo-3d Description: Galaxy Zoo: 3D (GZ: 3D) made use of a project on the Zooniverse platform to crowdsource spaxel masks locating ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GZ3DVAC:
"""Provides access to the Galaxy Zoo 3D spaxel masks. VAC name: Galaxy Zoo: 3D URL: https://www.sdss.org/dr17/data_access/value-added-catalogs/?vac_id=galaxy-zoo-3d Description: Galaxy Zoo: 3D (GZ: 3D) made use of a project on the Zooniverse platform to crowdsource spaxel masks locating galaxy center... | the_stack_v2_python_sparse | python/marvin/contrib/vacs/galaxyzoo3d.py | sdss/marvin | train | 56 |
7d06735b8c2590eaadf87b85ff9e4b6db86fb396 | [
"commander_parser = argparse.ArgumentParser(description=cls.HELP, add_help=False)\ncommander_options = commander_parser.add_argument_group('commander options')\ncommander_options.add_argument('-H', '--halt', action='store_true', default=None, help='Halt core upon connect. (Deprecated, see --connect.)')\ncommander_o... | <|body_start_0|>
commander_parser = argparse.ArgumentParser(description=cls.HELP, add_help=False)
commander_options = commander_parser.add_argument_group('commander options')
commander_options.add_argument('-H', '--halt', action='store_true', default=None, help='Halt core upon connect. (Deprecat... | @brief `pyocd commander` subcommand. | CommanderSubcommand | [
"CC-BY-4.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommanderSubcommand:
"""@brief `pyocd commander` subcommand."""
def get_args(cls) -> List[argparse.ArgumentParser]:
"""@brief Add this subcommand to the subparsers object."""
<|body_0|>
def invoke(self) -> int:
"""@brief Handle 'commander' subcommand."""
... | stack_v2_sparse_classes_36k_train_011460 | 3,430 | permissive | [
{
"docstring": "@brief Add this subcommand to the subparsers object.",
"name": "get_args",
"signature": "def get_args(cls) -> List[argparse.ArgumentParser]"
},
{
"docstring": "@brief Handle 'commander' subcommand.",
"name": "invoke",
"signature": "def invoke(self) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_012999 | Implement the Python class `CommanderSubcommand` described below.
Class description:
@brief `pyocd commander` subcommand.
Method signatures and docstrings:
- def get_args(cls) -> List[argparse.ArgumentParser]: @brief Add this subcommand to the subparsers object.
- def invoke(self) -> int: @brief Handle 'commander' su... | Implement the Python class `CommanderSubcommand` described below.
Class description:
@brief `pyocd commander` subcommand.
Method signatures and docstrings:
- def get_args(cls) -> List[argparse.ArgumentParser]: @brief Add this subcommand to the subparsers object.
- def invoke(self) -> int: @brief Handle 'commander' su... | 9253740baf46ebf4eacbce6bf3369150c5fb8ee0 | <|skeleton|>
class CommanderSubcommand:
"""@brief `pyocd commander` subcommand."""
def get_args(cls) -> List[argparse.ArgumentParser]:
"""@brief Add this subcommand to the subparsers object."""
<|body_0|>
def invoke(self) -> int:
"""@brief Handle 'commander' subcommand."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommanderSubcommand:
"""@brief `pyocd commander` subcommand."""
def get_args(cls) -> List[argparse.ArgumentParser]:
"""@brief Add this subcommand to the subparsers object."""
commander_parser = argparse.ArgumentParser(description=cls.HELP, add_help=False)
commander_options = comma... | the_stack_v2_python_sparse | pyocd/subcommands/commander_cmd.py | pyocd/pyOCD | train | 507 |
ea65b0fa61ad121090ee49530386d49d2a4ae9d5 | [
"self.serial = minimalmodbus.Instrument(serial_port, address)\ntime.sleep(1)\nself.serial.serial.baudrate = baudrate\ntime.sleep(1)\nself._initialize_read()",
"self.parameters = []\nfor register_parameter_type in self.REGISTER_PARAMETER_TYPE:\n parameter = self.serial.read_register(register_parameter_type, num... | <|body_start_0|>
self.serial = minimalmodbus.Instrument(serial_port, address)
time.sleep(1)
self.serial.serial.baudrate = baudrate
time.sleep(1)
self._initialize_read()
<|end_body_0|>
<|body_start_1|>
self.parameters = []
for register_parameter_type in self.REGIS... | Interface with the DCP through serial. Attributes: serial (minimalmodbus.Instrument): serial port object. parameters (list): Order of how parameters are interpreted. data (list): array with data. parameter_status (list): array with data status. | Dcp1 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dcp1:
"""Interface with the DCP through serial. Attributes: serial (minimalmodbus.Instrument): serial port object. parameters (list): Order of how parameters are interpreted. data (list): array with data. parameter_status (list): array with data status."""
def __init__(self, serial_port=SERI... | stack_v2_sparse_classes_36k_train_011461 | 2,993 | permissive | [
{
"docstring": "Initialization of the serial port and parameters.",
"name": "__init__",
"signature": "def __init__(self, serial_port=SERIAL_PORT, baudrate=BAUDRATE, address=ADDRESS)"
},
{
"docstring": "Read parameters that are returned when reading data. Read parameters from the registers. When ... | 4 | stack_v2_sparse_classes_30k_train_004929 | Implement the Python class `Dcp1` described below.
Class description:
Interface with the DCP through serial. Attributes: serial (minimalmodbus.Instrument): serial port object. parameters (list): Order of how parameters are interpreted. data (list): array with data. parameter_status (list): array with data status.
Met... | Implement the Python class `Dcp1` described below.
Class description:
Interface with the DCP through serial. Attributes: serial (minimalmodbus.Instrument): serial port object. parameters (list): Order of how parameters are interpreted. data (list): array with data. parameter_status (list): array with data status.
Met... | a7f126c0151d6491e3ed22653561f131b2b0f658 | <|skeleton|>
class Dcp1:
"""Interface with the DCP through serial. Attributes: serial (minimalmodbus.Instrument): serial port object. parameters (list): Order of how parameters are interpreted. data (list): array with data. parameter_status (list): array with data status."""
def __init__(self, serial_port=SERI... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dcp1:
"""Interface with the DCP through serial. Attributes: serial (minimalmodbus.Instrument): serial port object. parameters (list): Order of how parameters are interpreted. data (list): array with data. parameter_status (list): array with data status."""
def __init__(self, serial_port=SERIAL_PORT, baud... | the_stack_v2_python_sparse | src/ysi_exo/dcp1.py | dartmouthrobotics/ysi_exo | train | 4 |
512bc44045c9ba17c996b53087f81e1f6d970ec3 | [
"EasyFrame.__init__(self)\nself.addLabel(text='Input', row=0, column=0)\nself.inputField = self.addTextField(text='', row=0, column=1)\nself.addLabel(text='Output', row=1, column=0)\nself.outputField = self.addTextField(text='', row=1, column=1, state='readonly')\nself.button = self.addButton(text='Convert', row=2,... | <|body_start_0|>
EasyFrame.__init__(self)
self.addLabel(text='Input', row=0, column=0)
self.inputField = self.addTextField(text='', row=0, column=1)
self.addLabel(text='Output', row=1, column=0)
self.outputField = self.addTextField(text='', row=1, column=1, state='readonly')
... | Converts an input string to uppercase and displays the result. | TextFieldDemo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextFieldDemo:
"""Converts an input string to uppercase and displays the result."""
def __init__(self):
"""Sets up the window and widgets."""
<|body_0|>
def convert(self):
"""Inputs the string, converts it to uppercase, and outputs the result."""
<|body_1... | stack_v2_sparse_classes_36k_train_011462 | 1,579 | no_license | [
{
"docstring": "Sets up the window and widgets.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inputs the string, converts it to uppercase, and outputs the result.",
"name": "convert",
"signature": "def convert(self)"
}
] | 2 | null | Implement the Python class `TextFieldDemo` described below.
Class description:
Converts an input string to uppercase and displays the result.
Method signatures and docstrings:
- def __init__(self): Sets up the window and widgets.
- def convert(self): Inputs the string, converts it to uppercase, and outputs the result... | Implement the Python class `TextFieldDemo` described below.
Class description:
Converts an input string to uppercase and displays the result.
Method signatures and docstrings:
- def __init__(self): Sets up the window and widgets.
- def convert(self): Inputs the string, converts it to uppercase, and outputs the result... | eca69d000dc77681a30734b073b2383c97ccc02e | <|skeleton|>
class TextFieldDemo:
"""Converts an input string to uppercase and displays the result."""
def __init__(self):
"""Sets up the window and widgets."""
<|body_0|>
def convert(self):
"""Inputs the string, converts it to uppercase, and outputs the result."""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TextFieldDemo:
"""Converts an input string to uppercase and displays the result."""
def __init__(self):
"""Sets up the window and widgets."""
EasyFrame.__init__(self)
self.addLabel(text='Input', row=0, column=0)
self.inputField = self.addTextField(text='', row=0, column=1)... | the_stack_v2_python_sparse | gui/breezy/textfielddemo.py | lforet/robomow | train | 11 |
353a6ff0d796c054bc92a5c446de5b0439b6bfe8 | [
"if filter_root and (not filter_root.endswith('__')):\n filter_root += '__'\nreturn {'%srepository_id' % filter_root: self.repository.id, '%snumber' % filter_root: self.kwargs['issue_number']}",
"if not hasattr(self, '_issue'):\n self._issue = get_object_or_404(Issue.objects.select_related('repository__owne... | <|body_start_0|>
if filter_root and (not filter_root.endswith('__')):
filter_root += '__'
return {'%srepository_id' % filter_root: self.repository.id, '%snumber' % filter_root: self.kwargs['issue_number']}
<|end_body_0|>
<|body_start_1|>
if not hasattr(self, '_issue'):
s... | A mixin that is meant to be used when a view depends on a issue. Provides stuff provided by WithSubscribedRepositoryViewMixin, plus: - a "issue" property that'll get the issue depending on the repository and the "number" url params - a "get_issue_filter_args" to use to filter a model on a repository's name, its owner's... | WithIssueViewMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WithIssueViewMixin:
"""A mixin that is meant to be used when a view depends on a issue. Provides stuff provided by WithSubscribedRepositoryViewMixin, plus: - a "issue" property that'll get the issue depending on the repository and the "number" url params - a "get_issue_filter_args" to use to filt... | stack_v2_sparse_classes_36k_train_011463 | 15,489 | no_license | [
{
"docstring": "Return a dict with attribute to filter a model for a given repository's name, its owner's username and an issue number as given in the url. Use the \"filter_root\" to prefix the filter.",
"name": "get_issue_filter_args",
"signature": "def get_issue_filter_args(self, filter_root='')"
},... | 3 | stack_v2_sparse_classes_30k_val_000185 | Implement the Python class `WithIssueViewMixin` described below.
Class description:
A mixin that is meant to be used when a view depends on a issue. Provides stuff provided by WithSubscribedRepositoryViewMixin, plus: - a "issue" property that'll get the issue depending on the repository and the "number" url params - a... | Implement the Python class `WithIssueViewMixin` described below.
Class description:
A mixin that is meant to be used when a view depends on a issue. Provides stuff provided by WithSubscribedRepositoryViewMixin, plus: - a "issue" property that'll get the issue depending on the repository and the "number" url params - a... | 63a405b993e77f10b9c2b6d9790aae7576d9d84f | <|skeleton|>
class WithIssueViewMixin:
"""A mixin that is meant to be used when a view depends on a issue. Provides stuff provided by WithSubscribedRepositoryViewMixin, plus: - a "issue" property that'll get the issue depending on the repository and the "number" url params - a "get_issue_filter_args" to use to filt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WithIssueViewMixin:
"""A mixin that is meant to be used when a view depends on a issue. Provides stuff provided by WithSubscribedRepositoryViewMixin, plus: - a "issue" property that'll get the issue depending on the repository and the "number" url params - a "get_issue_filter_args" to use to filter a model on... | the_stack_v2_python_sparse | gim/front/mixins/views.py | derekey/github-issues-manager | train | 1 |
09a089b1c3f6edc8db0d096423abffad342094aa | [
"self.total = total\nself.c = c\nself.block_size = total // c",
"assert len(data) == self.c\nresult = [0] * self.total\nfor i in range(self.c):\n result[self.block_size * i:self.block_size * (i + 1)] = [data[i]] * self.block_size\nreturn result",
"assert len(data) == self.total\nresult = [0] * self.c\nfor i ... | <|body_start_0|>
self.total = total
self.c = c
self.block_size = total // c
<|end_body_0|>
<|body_start_1|>
assert len(data) == self.c
result = [0] * self.total
for i in range(self.c):
result[self.block_size * i:self.block_size * (i + 1)] = [data[i]] * self.b... | MyVote | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyVote:
def __init__(self, c=4, total=144):
""":param c: c表示编码c bits 信息 默认 4 :param total: 总共的编码长度 默认 144"""
<|body_0|>
def encode(self, data: list) -> list:
""":param data: data 就是长为self.c (4) 的待编码数据 :return: 长为 self.total (144) 的编码结果"""
<|body_1|>
def ... | stack_v2_sparse_classes_36k_train_011464 | 6,388 | no_license | [
{
"docstring": ":param c: c表示编码c bits 信息 默认 4 :param total: 总共的编码长度 默认 144",
"name": "__init__",
"signature": "def __init__(self, c=4, total=144)"
},
{
"docstring": ":param data: data 就是长为self.c (4) 的待编码数据 :return: 长为 self.total (144) 的编码结果",
"name": "encode",
"signature": "def encode(se... | 3 | stack_v2_sparse_classes_30k_train_006567 | Implement the Python class `MyVote` described below.
Class description:
Implement the MyVote class.
Method signatures and docstrings:
- def __init__(self, c=4, total=144): :param c: c表示编码c bits 信息 默认 4 :param total: 总共的编码长度 默认 144
- def encode(self, data: list) -> list: :param data: data 就是长为self.c (4) 的待编码数据 :return... | Implement the Python class `MyVote` described below.
Class description:
Implement the MyVote class.
Method signatures and docstrings:
- def __init__(self, c=4, total=144): :param c: c表示编码c bits 信息 默认 4 :param total: 总共的编码长度 默认 144
- def encode(self, data: list) -> list: :param data: data 就是长为self.c (4) 的待编码数据 :return... | d3fff41817526553d71548c76489c188af7eccc5 | <|skeleton|>
class MyVote:
def __init__(self, c=4, total=144):
""":param c: c表示编码c bits 信息 默认 4 :param total: 总共的编码长度 默认 144"""
<|body_0|>
def encode(self, data: list) -> list:
""":param data: data 就是长为self.c (4) 的待编码数据 :return: 长为 self.total (144) 的编码结果"""
<|body_1|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyVote:
def __init__(self, c=4, total=144):
""":param c: c表示编码c bits 信息 默认 4 :param total: 总共的编码长度 默认 144"""
self.total = total
self.c = c
self.block_size = total // c
def encode(self, data: list) -> list:
""":param data: data 就是长为self.c (4) 的待编码数据 :return: 长为 self... | the_stack_v2_python_sparse | coder/Coder.py | charygao/Backend | train | 0 | |
bd13d23a0aea1121fbc6f95c17ecb054b8edb012 | [
"self.size = 0\nself.val2index = dict()\nself.index2val = dict()",
"if val not in self.val2index:\n self.size += 1\n self.index2val[self.size] = val\n self.val2index[val] = {self.size}\n return True\nelse:\n self.size += 1\n self.val2index[val].add(self.size)\n self.index2val[self.size] = val... | <|body_start_0|>
self.size = 0
self.val2index = dict()
self.index2val = dict()
<|end_body_0|>
<|body_start_1|>
if val not in self.val2index:
self.size += 1
self.index2val[self.size] = val
self.val2index[val] = {self.size}
return True
... | RandomizedCollection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomizedCollection:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val):
"""Inserts a value to the collection. Returns true if the collection did not already contain the specified element. :type val: int :rtype: bool"""
... | stack_v2_sparse_classes_36k_train_011465 | 2,441 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a value to the collection. Returns true if the collection did not already contain the specified element. :type val: int :rtype: bool",
"name": "insert",
... | 4 | null | Implement the Python class `RandomizedCollection` described below.
Class description:
Implement the RandomizedCollection class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val): Inserts a value to the collection. Returns true if the collection did no... | Implement the Python class `RandomizedCollection` described below.
Class description:
Implement the RandomizedCollection class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val): Inserts a value to the collection. Returns true if the collection did no... | 2c3dbcbcb20cfdb276c0886e0193ef42551c5747 | <|skeleton|>
class RandomizedCollection:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val):
"""Inserts a value to the collection. Returns true if the collection did not already contain the specified element. :type val: int :rtype: bool"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomizedCollection:
def __init__(self):
"""Initialize your data structure here."""
self.size = 0
self.val2index = dict()
self.index2val = dict()
def insert(self, val):
"""Inserts a value to the collection. Returns true if the collection did not already contain th... | the_stack_v2_python_sparse | 381-Insert-Delete-GetRandom-O(1)---Duplicates-allowed/solution.py | Lucces/leetcode | train | 0 | |
594f253eadf5775d70fc88558aaf3ed584f45560 | [
"t0 = time.time()\nextract_vect = EigenValueVectorizeFeatureExtractor()\neigvals_vect = extract_vect.extract(self.point_cloud, self.neigh, None, None, None)\nprint('Timing Vectorize : {}'.format(time.time() - t0))\neigvals_vect = np.vstack(eigvals_vect[:3]).T\neigvals = []\nt0 = time.time()\nfor n in self.neigh:\n ... | <|body_start_0|>
t0 = time.time()
extract_vect = EigenValueVectorizeFeatureExtractor()
eigvals_vect = extract_vect.extract(self.point_cloud, self.neigh, None, None, None)
print('Timing Vectorize : {}'.format(time.time() - t0))
eigvals_vect = np.vstack(eigvals_vect[:3]).T
... | TestExtractEigenvaluesComparison | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestExtractEigenvaluesComparison:
def test_eigen_multiple_neighborhoods(self):
"""Test and compare the serial and vectorized eigenvalues. Eigenvalues are computed for a list of neighborhoods in real data. A vectorized implementation and a serial implementation are compared and timed. Any... | stack_v2_sparse_classes_36k_train_011466 | 11,643 | permissive | [
{
"docstring": "Test and compare the serial and vectorized eigenvalues. Eigenvalues are computed for a list of neighborhoods in real data. A vectorized implementation and a serial implementation are compared and timed. Any difference in result between the two methods is definitely unexpected (except maybe in or... | 2 | stack_v2_sparse_classes_30k_train_006913 | Implement the Python class `TestExtractEigenvaluesComparison` described below.
Class description:
Implement the TestExtractEigenvaluesComparison class.
Method signatures and docstrings:
- def test_eigen_multiple_neighborhoods(self): Test and compare the serial and vectorized eigenvalues. Eigenvalues are computed for ... | Implement the Python class `TestExtractEigenvaluesComparison` described below.
Class description:
Implement the TestExtractEigenvaluesComparison class.
Method signatures and docstrings:
- def test_eigen_multiple_neighborhoods(self): Test and compare the serial and vectorized eigenvalues. Eigenvalues are computed for ... | f6c22841dcbd375639c7f7aecec70f2602b91ee4 | <|skeleton|>
class TestExtractEigenvaluesComparison:
def test_eigen_multiple_neighborhoods(self):
"""Test and compare the serial and vectorized eigenvalues. Eigenvalues are computed for a list of neighborhoods in real data. A vectorized implementation and a serial implementation are compared and timed. Any... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestExtractEigenvaluesComparison:
def test_eigen_multiple_neighborhoods(self):
"""Test and compare the serial and vectorized eigenvalues. Eigenvalues are computed for a list of neighborhoods in real data. A vectorized implementation and a serial implementation are compared and timed. Any difference in... | the_stack_v2_python_sparse | laserchicken/feature_extractor/test_eigenvals_feature_extractor.py | eEcoLiDAR/laserchicken | train | 28 | |
d177b7651982ec05e6d12cc2bb899d3f6663a8b0 | [
"result = self.versions_client.list_versions()\nversions = result['versions']\nself.assertEqual(versions[0]['id'], 'v2.0', 'The first listed version should be v2.0')",
"result = self.versions_client.list_versions()\nversions = result['versions']\nfor version in versions:\n links = [x for x in version['links'] ... | <|body_start_0|>
result = self.versions_client.list_versions()
versions = result['versions']
self.assertEqual(versions[0]['id'], 'v2.0', 'The first listed version should be v2.0')
<|end_body_0|>
<|body_start_1|>
result = self.versions_client.list_versions()
versions = result['ve... | TestVersions | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestVersions:
def test_list_api_versions(self):
"""Test that a get of the unversioned url returns the choices doc. A key feature in OpenStack services is the idea that you can GET / on the service and get a list of the versioned endpoints that you can access. This comes back as a status ... | stack_v2_sparse_classes_36k_train_011467 | 3,232 | permissive | [
{
"docstring": "Test that a get of the unversioned url returns the choices doc. A key feature in OpenStack services is the idea that you can GET / on the service and get a list of the versioned endpoints that you can access. This comes back as a status 300 request. It's important that this is available to API c... | 2 | stack_v2_sparse_classes_30k_train_016215 | Implement the Python class `TestVersions` described below.
Class description:
Implement the TestVersions class.
Method signatures and docstrings:
- def test_list_api_versions(self): Test that a get of the unversioned url returns the choices doc. A key feature in OpenStack services is the idea that you can GET / on th... | Implement the Python class `TestVersions` described below.
Class description:
Implement the TestVersions class.
Method signatures and docstrings:
- def test_list_api_versions(self): Test that a get of the unversioned url returns the choices doc. A key feature in OpenStack services is the idea that you can GET / on th... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class TestVersions:
def test_list_api_versions(self):
"""Test that a get of the unversioned url returns the choices doc. A key feature in OpenStack services is the idea that you can GET / on the service and get a list of the versioned endpoints that you can access. This comes back as a status ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestVersions:
def test_list_api_versions(self):
"""Test that a get of the unversioned url returns the choices doc. A key feature in OpenStack services is the idea that you can GET / on the service and get a list of the versioned endpoints that you can access. This comes back as a status 300 request. I... | the_stack_v2_python_sparse | tempest/api/compute/test_versions.py | openstack/tempest | train | 270 | |
62f2e3555a08a9233e79638ad61e7e08be4ea68c | [
"if not data_kinds:\n data_kinds = [DataKind.WEIGHT_DIFF, DataKind.WEIGHTS]\nsuper().__init__(supported_data_kinds=[DataKind.WEIGHTS, DataKind.WEIGHT_DIFF], data_kinds_to_filter=data_kinds)\nself.exclude_vars = exclude_vars\nself.skip = False\nif self.exclude_vars is not None:\n if not (isinstance(self.exclud... | <|body_start_0|>
if not data_kinds:
data_kinds = [DataKind.WEIGHT_DIFF, DataKind.WEIGHTS]
super().__init__(supported_data_kinds=[DataKind.WEIGHTS, DataKind.WEIGHT_DIFF], data_kinds_to_filter=data_kinds)
self.exclude_vars = exclude_vars
self.skip = False
if self.exclud... | ExcludeVars | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExcludeVars:
def __init__(self, exclude_vars: Union[List[str], str, None]=None, data_kinds: List[str]=None):
"""Exclude/Remove variables from Shareable. Args: exclude_vars (Union[List[str], str, None] , optional): variables/layer names to be excluded. data_kinds: kinds of DXO object to f... | stack_v2_sparse_classes_36k_train_011468 | 4,804 | permissive | [
{
"docstring": "Exclude/Remove variables from Shareable. Args: exclude_vars (Union[List[str], str, None] , optional): variables/layer names to be excluded. data_kinds: kinds of DXO object to filter Notes: Based on different types of exclude_vars, this filter has different behavior: if a list of variable/layer n... | 2 | stack_v2_sparse_classes_30k_train_016417 | Implement the Python class `ExcludeVars` described below.
Class description:
Implement the ExcludeVars class.
Method signatures and docstrings:
- def __init__(self, exclude_vars: Union[List[str], str, None]=None, data_kinds: List[str]=None): Exclude/Remove variables from Shareable. Args: exclude_vars (Union[List[str]... | Implement the Python class `ExcludeVars` described below.
Class description:
Implement the ExcludeVars class.
Method signatures and docstrings:
- def __init__(self, exclude_vars: Union[List[str], str, None]=None, data_kinds: List[str]=None): Exclude/Remove variables from Shareable. Args: exclude_vars (Union[List[str]... | 1433290c203bd23f34c29e11795ce592bc067888 | <|skeleton|>
class ExcludeVars:
def __init__(self, exclude_vars: Union[List[str], str, None]=None, data_kinds: List[str]=None):
"""Exclude/Remove variables from Shareable. Args: exclude_vars (Union[List[str], str, None] , optional): variables/layer names to be excluded. data_kinds: kinds of DXO object to f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExcludeVars:
def __init__(self, exclude_vars: Union[List[str], str, None]=None, data_kinds: List[str]=None):
"""Exclude/Remove variables from Shareable. Args: exclude_vars (Union[List[str], str, None] , optional): variables/layer names to be excluded. data_kinds: kinds of DXO object to filter Notes: B... | the_stack_v2_python_sparse | nvflare/app_common/filters/exclude_vars.py | NVIDIA/NVFlare | train | 442 | |
da6c2f446b4a1c5c3f42c5f73254b5a697cf057d | [
"body = json.loads(request.body.decode(encoding='utf-8', errors='replace'))\nlogger.debug('Callback {}: {}'.format(request.META['QUERY_STRING'], body))\nfields = {'entity_id': body['ID'], 'action': body['Action'], 'callback_type': body['Type']}\nform = CallBackForm(fields)\nif not form.is_valid():\n fields = ', ... | <|body_start_0|>
body = json.loads(request.body.decode(encoding='utf-8', errors='replace'))
logger.debug('Callback {}: {}'.format(request.META['QUERY_STRING'], body))
fields = {'entity_id': body['ID'], 'action': body['Action'], 'callback_type': body['Type']}
form = CallBackForm(fields)
... | CallBackView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CallBackView:
def post(self, request, *args, **kwargs):
"""Add, update or delete entity by fetching it from CW again. We mostly ignore the JSON that CW sends to us, because their method of verifying the request requires us to make a request back to them for a signing key, so we may as we... | stack_v2_sparse_classes_36k_train_011469 | 4,714 | permissive | [
{
"docstring": "Add, update or delete entity by fetching it from CW again. We mostly ignore the JSON that CW sends to us, because their method of verifying the request requires us to make a request back to them for a signing key, so we may as well just make a request for the whole object. ConnectWise docs for c... | 2 | null | Implement the Python class `CallBackView` described below.
Class description:
Implement the CallBackView class.
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): Add, update or delete entity by fetching it from CW again. We mostly ignore the JSON that CW sends to us, because their method o... | Implement the Python class `CallBackView` described below.
Class description:
Implement the CallBackView class.
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): Add, update or delete entity by fetching it from CW again. We mostly ignore the JSON that CW sends to us, because their method o... | cd42f640cff55bce93a6f1ebdabd8f2ad13c4a54 | <|skeleton|>
class CallBackView:
def post(self, request, *args, **kwargs):
"""Add, update or delete entity by fetching it from CW again. We mostly ignore the JSON that CW sends to us, because their method of verifying the request requires us to make a request back to them for a signing key, so we may as we... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CallBackView:
def post(self, request, *args, **kwargs):
"""Add, update or delete entity by fetching it from CW again. We mostly ignore the JSON that CW sends to us, because their method of verifying the request requires us to make a request back to them for a signing key, so we may as well just make a... | the_stack_v2_python_sparse | djconnectwise/views.py | KerkhoffTechnologies/django-connectwise | train | 15 | |
9bfd21922c3c30710c3687aad5795b1d2bf9c9ee | [
"self.name = None\nself.TP = None\nself.FP = None\nself.FN = None\nself.ignored_ground_truth_ids = []\nself.ignored_performer_ids = []\nself.precision = None\nself.recall = None\nself.f1_score = None\nself.matched_gt_ids = []\nself.unmatched_gt_ids = []\nself.matched_performer_ids = []\nself.unmatched_performer_ids... | <|body_start_0|>
self.name = None
self.TP = None
self.FP = None
self.FN = None
self.ignored_ground_truth_ids = []
self.ignored_performer_ids = []
self.precision = None
self.recall = None
self.f1_score = None
self.matched_gt_ids = []
... | MetricsContainer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetricsContainer:
def __init__(self):
"""Constructor for metrics container"""
<|body_0|>
def show_stoplight_chart(self):
"""Brings up a opencv window that displays the stoplight chart and waits for keypress to close :return:"""
<|body_1|>
def set_values(... | stack_v2_sparse_classes_36k_train_011470 | 4,626 | no_license | [
{
"docstring": "Constructor for metrics container",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Brings up a opencv window that displays the stoplight chart and waits for keypress to close :return:",
"name": "show_stoplight_chart",
"signature": "def show_stopl... | 4 | stack_v2_sparse_classes_30k_train_007929 | Implement the Python class `MetricsContainer` described below.
Class description:
Implement the MetricsContainer class.
Method signatures and docstrings:
- def __init__(self): Constructor for metrics container
- def show_stoplight_chart(self): Brings up a opencv window that displays the stoplight chart and waits for ... | Implement the Python class `MetricsContainer` described below.
Class description:
Implement the MetricsContainer class.
Method signatures and docstrings:
- def __init__(self): Constructor for metrics container
- def show_stoplight_chart(self): Brings up a opencv window that displays the stoplight chart and waits for ... | fcda0d56869f8b2b3c506a3b9601b2c6ab491617 | <|skeleton|>
class MetricsContainer:
def __init__(self):
"""Constructor for metrics container"""
<|body_0|>
def show_stoplight_chart(self):
"""Brings up a opencv window that displays the stoplight chart and waits for keypress to close :return:"""
<|body_1|>
def set_values(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MetricsContainer:
def __init__(self):
"""Constructor for metrics container"""
self.name = None
self.TP = None
self.FP = None
self.FN = None
self.ignored_ground_truth_ids = []
self.ignored_performer_ids = []
self.precision = None
self.reca... | the_stack_v2_python_sparse | core3dmetrics/instancemetrics/MetricsContainer.py | pubgeo/core3d-metrics | train | 14 | |
5e5557b6e6aaceed83b112f118ab210c5c1224a1 | [
"if len(grid) < 1 or len(grid[0]) < 1:\n return 0\nresult = 0\nrow, col = (len(grid), len(grid[0]))\nvisited = [[False] * col for x in range(row)]\nfor i in range(row):\n for j in range(col):\n if grid[i][j] == '1' and (not visited[i][j]):\n self.helper(grid, visited, i, j)\n resu... | <|body_start_0|>
if len(grid) < 1 or len(grid[0]) < 1:
return 0
result = 0
row, col = (len(grid), len(grid[0]))
visited = [[False] * col for x in range(row)]
for i in range(row):
for j in range(col):
if grid[i][j] == '1' and (not visited[i]... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def num_islands(self, grid: List[List[str]]) -> int:
"""计算岛屿个数 Args: grid: 二维数组 Returns: 岛屿个数"""
<|body_0|>
def helper(self, grid: List[List[int]], visited: List[List[int]], x: int, y: int) -> None:
"""帮助类函数 Args: grid: 二维数组 visited: 访问数组 x: 位置x y: 位置y"""
... | stack_v2_sparse_classes_36k_train_011471 | 3,619 | permissive | [
{
"docstring": "计算岛屿个数 Args: grid: 二维数组 Returns: 岛屿个数",
"name": "num_islands",
"signature": "def num_islands(self, grid: List[List[str]]) -> int"
},
{
"docstring": "帮助类函数 Args: grid: 二维数组 visited: 访问数组 x: 位置x y: 位置y",
"name": "helper",
"signature": "def helper(self, grid: List[List[int]]... | 3 | stack_v2_sparse_classes_30k_train_006445 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def num_islands(self, grid: List[List[str]]) -> int: 计算岛屿个数 Args: grid: 二维数组 Returns: 岛屿个数
- def helper(self, grid: List[List[int]], visited: List[List[int]], x: int, y: int) -> ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def num_islands(self, grid: List[List[str]]) -> int: 计算岛屿个数 Args: grid: 二维数组 Returns: 岛屿个数
- def helper(self, grid: List[List[int]], visited: List[List[int]], x: int, y: int) -> ... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def num_islands(self, grid: List[List[str]]) -> int:
"""计算岛屿个数 Args: grid: 二维数组 Returns: 岛屿个数"""
<|body_0|>
def helper(self, grid: List[List[int]], visited: List[List[int]], x: int, y: int) -> None:
"""帮助类函数 Args: grid: 二维数组 visited: 访问数组 x: 位置x y: 位置y"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def num_islands(self, grid: List[List[str]]) -> int:
"""计算岛屿个数 Args: grid: 二维数组 Returns: 岛屿个数"""
if len(grid) < 1 or len(grid[0]) < 1:
return 0
result = 0
row, col = (len(grid), len(grid[0]))
visited = [[False] * col for x in range(row)]
fo... | the_stack_v2_python_sparse | src/leetcodepython/top100likedquestions/number_islands_200.py | zhangyu345293721/leetcode | train | 101 | |
4a401be21cfc60bd1ec789745bab21848f25b039 | [
"global DataBase\njson_data = lottery_ns.payload\nif ticket_num not in DataBase:\n ticket_fields = json_data['fields']\n ticket_price = json_data['price']\n if len(ticket_fields) != 3:\n return ('Количество полей в билете должно быть равно 3', 400)\n new_ticket = Ticket(ticket_num, ticket_fields,... | <|body_start_0|>
global DataBase
json_data = lottery_ns.payload
if ticket_num not in DataBase:
ticket_fields = json_data['fields']
ticket_price = json_data['price']
if len(ticket_fields) != 3:
return ('Количество полей в билете должно быть равн... | TicketResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TicketResource:
def post(self, ticket_num):
"""Метод для внесения лотирейного билета в базу"""
<|body_0|>
def get(self, ticket_num):
"""Метод для получения информации о лотирейном билете"""
<|body_1|>
def patch(self, ticket_num):
"""Метод для изм... | stack_v2_sparse_classes_36k_train_011472 | 3,037 | no_license | [
{
"docstring": "Метод для внесения лотирейного билета в базу",
"name": "post",
"signature": "def post(self, ticket_num)"
},
{
"docstring": "Метод для получения информации о лотирейном билете",
"name": "get",
"signature": "def get(self, ticket_num)"
},
{
"docstring": "Метод для из... | 3 | stack_v2_sparse_classes_30k_train_000708 | Implement the Python class `TicketResource` described below.
Class description:
Implement the TicketResource class.
Method signatures and docstrings:
- def post(self, ticket_num): Метод для внесения лотирейного билета в базу
- def get(self, ticket_num): Метод для получения информации о лотирейном билете
- def patch(s... | Implement the Python class `TicketResource` described below.
Class description:
Implement the TicketResource class.
Method signatures and docstrings:
- def post(self, ticket_num): Метод для внесения лотирейного билета в базу
- def get(self, ticket_num): Метод для получения информации о лотирейном билете
- def patch(s... | c61442cf1c0fd383a959ed607c0bf6b39323fd06 | <|skeleton|>
class TicketResource:
def post(self, ticket_num):
"""Метод для внесения лотирейного билета в базу"""
<|body_0|>
def get(self, ticket_num):
"""Метод для получения информации о лотирейном билете"""
<|body_1|>
def patch(self, ticket_num):
"""Метод для изм... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TicketResource:
def post(self, ticket_num):
"""Метод для внесения лотирейного билета в базу"""
global DataBase
json_data = lottery_ns.payload
if ticket_num not in DataBase:
ticket_fields = json_data['fields']
ticket_price = json_data['price']
... | the_stack_v2_python_sparse | flaskapp/lottery/lottery.py | hisa-prog/lab4 | train | 0 | |
eaca7d8c573dc79f16ab2558b03a94e1d388a9e7 | [
"main_menu_element = yamlstr_to_tuple(data['main_menu_element'].replace('$main_menu', main_menu))\nself.wait_click(main_menu_element)\nreturn self._left_second_menu_click(second_menu)",
"second_menu_element = yamlstr_to_tuple(data['second_menu_element'].replace('$second_menu', second_menu))\nself.wait_click(secon... | <|body_start_0|>
main_menu_element = yamlstr_to_tuple(data['main_menu_element'].replace('$main_menu', main_menu))
self.wait_click(main_menu_element)
return self._left_second_menu_click(second_menu)
<|end_body_0|>
<|body_start_1|>
second_menu_element = yamlstr_to_tuple(data['second_menu_... | MainMenu | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MainMenu:
def left_menu_click(self, main_menu, second_menu):
"""点击左侧大菜单"""
<|body_0|>
def _left_second_menu_click(self, second_menu):
"""点击第二级菜单"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
main_menu_element = yamlstr_to_tuple(data['main_menu_ele... | stack_v2_sparse_classes_36k_train_011473 | 1,680 | no_license | [
{
"docstring": "点击左侧大菜单",
"name": "left_menu_click",
"signature": "def left_menu_click(self, main_menu, second_menu)"
},
{
"docstring": "点击第二级菜单",
"name": "_left_second_menu_click",
"signature": "def _left_second_menu_click(self, second_menu)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016028 | Implement the Python class `MainMenu` described below.
Class description:
Implement the MainMenu class.
Method signatures and docstrings:
- def left_menu_click(self, main_menu, second_menu): 点击左侧大菜单
- def _left_second_menu_click(self, second_menu): 点击第二级菜单 | Implement the Python class `MainMenu` described below.
Class description:
Implement the MainMenu class.
Method signatures and docstrings:
- def left_menu_click(self, main_menu, second_menu): 点击左侧大菜单
- def _left_second_menu_click(self, second_menu): 点击第二级菜单
<|skeleton|>
class MainMenu:
def left_menu_click(self, ... | 2658c98c61f7cedaefc2f8b97b17d8a754fa9967 | <|skeleton|>
class MainMenu:
def left_menu_click(self, main_menu, second_menu):
"""点击左侧大菜单"""
<|body_0|>
def _left_second_menu_click(self, second_menu):
"""点击第二级菜单"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MainMenu:
def left_menu_click(self, main_menu, second_menu):
"""点击左侧大菜单"""
main_menu_element = yamlstr_to_tuple(data['main_menu_element'].replace('$main_menu', main_menu))
self.wait_click(main_menu_element)
return self._left_second_menu_click(second_menu)
def _left_second_... | the_stack_v2_python_sparse | iflying_manage/page/main_menu.py | luwenying/auto_test | train | 0 | |
3295da8adcad1c18b6201143cde6e5d11513b40d | [
"self.check_parameters(params)\nsq2 = np.sqrt(2) / 2\neip = np.exp(1j * params[0])\neil = np.exp(1j * params[1])\nreturn UnitaryMatrix([[sq2, -eil * sq2], [eip * sq2, eip * eil * sq2]])",
"self.check_parameters(params)\nsq2 = np.sqrt(2) / 2\neip = np.exp(1j * params[0])\neil = np.exp(1j * params[1])\ndeip = 1j * ... | <|body_start_0|>
self.check_parameters(params)
sq2 = np.sqrt(2) / 2
eip = np.exp(1j * params[0])
eil = np.exp(1j * params[1])
return UnitaryMatrix([[sq2, -eil * sq2], [eip * sq2, eip * eil * sq2]])
<|end_body_0|>
<|body_start_1|>
self.check_parameters(params)
sq2... | The U2 single qubit gate. | U2Gate | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class U2Gate:
"""The U2 single qubit gate."""
def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix:
"""Returns the unitary for this gate, see Unitary for more info."""
<|body_0|>
def get_grad(self, params: Sequence[float]=[]) -> np.ndarray:
"""Returns the... | stack_v2_sparse_classes_36k_train_011474 | 1,612 | permissive | [
{
"docstring": "Returns the unitary for this gate, see Unitary for more info.",
"name": "get_unitary",
"signature": "def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix"
},
{
"docstring": "Returns the gradient for this gate, see Gate for more info.",
"name": "get_grad",
"s... | 2 | null | Implement the Python class `U2Gate` described below.
Class description:
The U2 single qubit gate.
Method signatures and docstrings:
- def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix: Returns the unitary for this gate, see Unitary for more info.
- def get_grad(self, params: Sequence[float]=[]) -> np... | Implement the Python class `U2Gate` described below.
Class description:
The U2 single qubit gate.
Method signatures and docstrings:
- def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix: Returns the unitary for this gate, see Unitary for more info.
- def get_grad(self, params: Sequence[float]=[]) -> np... | 3083218c2f4e3c3ce4ba027d12caa30c384d7665 | <|skeleton|>
class U2Gate:
"""The U2 single qubit gate."""
def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix:
"""Returns the unitary for this gate, see Unitary for more info."""
<|body_0|>
def get_grad(self, params: Sequence[float]=[]) -> np.ndarray:
"""Returns the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class U2Gate:
"""The U2 single qubit gate."""
def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix:
"""Returns the unitary for this gate, see Unitary for more info."""
self.check_parameters(params)
sq2 = np.sqrt(2) / 2
eip = np.exp(1j * params[0])
eil = np.... | the_stack_v2_python_sparse | bqskit/ir/gates/parameterized/u2.py | mtreinish/bqskit | train | 0 |
56f3f1a528636554d40f0dce2d62d55f2677005b | [
"try:\n data = request.get_json()\n name = data['name']\n description = data['description']\nexcept KeyError:\n return jsonify(responses.missing_parameters)\nuser_group = UserGroup.objects(name=name).first()\nif user_group:\n return jsonify(responses.usergroup_exists)\nUserGroup(name=xstr(name), desc... | <|body_start_0|>
try:
data = request.get_json()
name = data['name']
description = data['description']
except KeyError:
return jsonify(responses.missing_parameters)
user_group = UserGroup.objects(name=name).first()
if user_group:
... | UserGroupService | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserGroupService:
def post(self):
"""Args as data: name = <name of user group> description = <description for group> Returns (JSON) : { "success" : <True or False> "error" : <If False then error will be returned> }"""
<|body_0|>
def get(self, name):
"""Args as data: ... | stack_v2_sparse_classes_36k_train_011475 | 2,205 | permissive | [
{
"docstring": "Args as data: name = <name of user group> description = <description for group> Returns (JSON) : { \"success\" : <True or False> \"error\" : <If False then error will be returned> }",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Args as data: name = <name of u... | 2 | stack_v2_sparse_classes_30k_train_018360 | Implement the Python class `UserGroupService` described below.
Class description:
Implement the UserGroupService class.
Method signatures and docstrings:
- def post(self): Args as data: name = <name of user group> description = <description for group> Returns (JSON) : { "success" : <True or False> "error" : <If False... | Implement the Python class `UserGroupService` described below.
Class description:
Implement the UserGroupService class.
Method signatures and docstrings:
- def post(self): Args as data: name = <name of user group> description = <description for group> Returns (JSON) : { "success" : <True or False> "error" : <If False... | 53ba7519c56d46af1e32a77aab5cf1c5cd8143fc | <|skeleton|>
class UserGroupService:
def post(self):
"""Args as data: name = <name of user group> description = <description for group> Returns (JSON) : { "success" : <True or False> "error" : <If False then error will be returned> }"""
<|body_0|>
def get(self, name):
"""Args as data: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserGroupService:
def post(self):
"""Args as data: name = <name of user group> description = <description for group> Returns (JSON) : { "success" : <True or False> "error" : <If False then error will be returned> }"""
try:
data = request.get_json()
name = data['name']
... | the_stack_v2_python_sparse | BuildingDepot-v3.2.8/buildingdepot/CentralService/app/rest_api/usergroups/usergroup.py | Entromorgan/GIoTTo | train | 0 | |
bef298edc4cf06b65034e1c5ebe679830590578f | [
"super().__init__()\nself.sh1_pattern = (re.compile('git\\\\s+:\\\\s+(.*)'), 1)\nself.cam_sn_pattern = (re.compile('Camera Serial Number\\\\s+:\\\\s+(.*)'), 1)\nself.cam_id_pattern = (re.compile('Id\\\\s+:\\\\s+(.*)'), 1)\nself.frw_ver_pattern = (re.compile('version\\\\s+:\\\\s+(.*)'), 1)\nself.cam_name = (re.compi... | <|body_start_0|>
super().__init__()
self.sh1_pattern = (re.compile('git\\s+:\\s+(.*)'), 1)
self.cam_sn_pattern = (re.compile('Camera Serial Number\\s+:\\s+(.*)'), 1)
self.cam_id_pattern = (re.compile('Id\\s+:\\s+(.*)'), 1)
self.frw_ver_pattern = (re.compile('version\\s+:\\s+(.*)'... | ParserForCamera | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParserForCamera:
def __init__(self):
"""each pattern is made of a tuple ( pattern,group) where pattern is the string we look for and the group is the exact return value example: pattern : 'Name : Gopro proto 2.0' group = 'Gopro proto 2.0'"""
<|body_0|>
def search_pattern(sel... | stack_v2_sparse_classes_36k_train_011476 | 1,975 | no_license | [
{
"docstring": "each pattern is made of a tuple ( pattern,group) where pattern is the string we look for and the group is the exact return value example: pattern : 'Name : Gopro proto 2.0' group = 'Gopro proto 2.0'",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":param... | 2 | stack_v2_sparse_classes_30k_train_004129 | Implement the Python class `ParserForCamera` described below.
Class description:
Implement the ParserForCamera class.
Method signatures and docstrings:
- def __init__(self): each pattern is made of a tuple ( pattern,group) where pattern is the string we look for and the group is the exact return value example: patter... | Implement the Python class `ParserForCamera` described below.
Class description:
Implement the ParserForCamera class.
Method signatures and docstrings:
- def __init__(self): each pattern is made of a tuple ( pattern,group) where pattern is the string we look for and the group is the exact return value example: patter... | a283a41c8a66c65bd8eb426deb05818a696a7fd0 | <|skeleton|>
class ParserForCamera:
def __init__(self):
"""each pattern is made of a tuple ( pattern,group) where pattern is the string we look for and the group is the exact return value example: pattern : 'Name : Gopro proto 2.0' group = 'Gopro proto 2.0'"""
<|body_0|>
def search_pattern(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParserForCamera:
def __init__(self):
"""each pattern is made of a tuple ( pattern,group) where pattern is the string we look for and the group is the exact return value example: pattern : 'Name : Gopro proto 2.0' group = 'Gopro proto 2.0'"""
super().__init__()
self.sh1_pattern = (re.co... | the_stack_v2_python_sparse | parserForCamera.py | faidi-saif/testerv3 | train | 0 | |
f5583083a3c3cec400b7c5689b140822ca889d5f | [
"result = []\nfor model in cls.model_list:\n result += list(model.objects.filter(*args, **kwargs))\nreturn result",
"try:\n ls = cls.filter(*args, **kwargs)\n if len(ls) > 1:\n raise MultipleObjectsReturned()\n return cls.filter(*args, **kwargs)[0]\nexcept IndexError:\n raise ObjectDoesNotEx... | <|body_start_0|>
result = []
for model in cls.model_list:
result += list(model.objects.filter(*args, **kwargs))
return result
<|end_body_0|>
<|body_start_1|>
try:
ls = cls.filter(*args, **kwargs)
if len(ls) > 1:
raise MultipleObjectsRe... | This is a class made for querying abstract models. This class is itself abstract. create subclasses to query your own abstract models. | AbstractModelQuery | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbstractModelQuery:
"""This is a class made for querying abstract models. This class is itself abstract. create subclasses to query your own abstract models."""
def filter(cls, *args, **kwargs):
"""Query all concrete model classes. Iterates over the model list and returns a list of a... | stack_v2_sparse_classes_36k_train_011477 | 1,753 | permissive | [
{
"docstring": "Query all concrete model classes. Iterates over the model list and returns a list of all matching models from the classes given. Filter queries are given here as normal and are passed into the Django ORM for each concrete model",
"name": "filter",
"signature": "def filter(cls, *args, **k... | 2 | stack_v2_sparse_classes_30k_train_004964 | Implement the Python class `AbstractModelQuery` described below.
Class description:
This is a class made for querying abstract models. This class is itself abstract. create subclasses to query your own abstract models.
Method signatures and docstrings:
- def filter(cls, *args, **kwargs): Query all concrete model clas... | Implement the Python class `AbstractModelQuery` described below.
Class description:
This is a class made for querying abstract models. This class is itself abstract. create subclasses to query your own abstract models.
Method signatures and docstrings:
- def filter(cls, *args, **kwargs): Query all concrete model clas... | 886a644432ff53f97babccbae4eee555338caec1 | <|skeleton|>
class AbstractModelQuery:
"""This is a class made for querying abstract models. This class is itself abstract. create subclasses to query your own abstract models."""
def filter(cls, *args, **kwargs):
"""Query all concrete model classes. Iterates over the model list and returns a list of a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AbstractModelQuery:
"""This is a class made for querying abstract models. This class is itself abstract. create subclasses to query your own abstract models."""
def filter(cls, *args, **kwargs):
"""Query all concrete model classes. Iterates over the model list and returns a list of all matching m... | the_stack_v2_python_sparse | src/dashboard/utils.py | opnfv/laas | train | 3 |
ef67cb7ddd6a739eaf553b30cf2bfe82fc573c92 | [
"total_n = factorial(len(nums))\nresult = []\nperm_idxs = list(range(len(nums)))\nfor i in range(total_n):\n next_perm = [nums[i] for i in perm_idxs]\n result.append(next_perm)\n perm_idxs = self.next_permute(perm_idxs)\nreturn result",
"first_idx = len(nums) - 2\nsecond_idx = len(nums) - 1\nwhile first_... | <|body_start_0|>
total_n = factorial(len(nums))
result = []
perm_idxs = list(range(len(nums)))
for i in range(total_n):
next_perm = [nums[i] for i in perm_idxs]
result.append(next_perm)
perm_idxs = self.next_permute(perm_idxs)
return result
<|e... | Solution_B1 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution_B1:
def permute(self, nums: List[int]) -> List[List[int]]:
"""Version B1 Proxy-version, convert to permutation of indexes, then replace with nums[idx]"""
<|body_0|>
def next_permute(self, nums: List[int]) -> List[int]:
"""Herlper for B1, B2 From Leetcode LC0... | stack_v2_sparse_classes_36k_train_011478 | 5,911 | permissive | [
{
"docstring": "Version B1 Proxy-version, convert to permutation of indexes, then replace with nums[idx]",
"name": "permute",
"signature": "def permute(self, nums: List[int]) -> List[List[int]]"
},
{
"docstring": "Herlper for B1, B2 From Leetcode LC031: next permutation, modified to return a new... | 2 | stack_v2_sparse_classes_30k_train_017492 | Implement the Python class `Solution_B1` described below.
Class description:
Implement the Solution_B1 class.
Method signatures and docstrings:
- def permute(self, nums: List[int]) -> List[List[int]]: Version B1 Proxy-version, convert to permutation of indexes, then replace with nums[idx]
- def next_permute(self, num... | Implement the Python class `Solution_B1` described below.
Class description:
Implement the Solution_B1 class.
Method signatures and docstrings:
- def permute(self, nums: List[int]) -> List[List[int]]: Version B1 Proxy-version, convert to permutation of indexes, then replace with nums[idx]
- def next_permute(self, num... | 143422321cbc3715ca08f6c3af8f960a55887ced | <|skeleton|>
class Solution_B1:
def permute(self, nums: List[int]) -> List[List[int]]:
"""Version B1 Proxy-version, convert to permutation of indexes, then replace with nums[idx]"""
<|body_0|>
def next_permute(self, nums: List[int]) -> List[int]:
"""Herlper for B1, B2 From Leetcode LC0... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution_B1:
def permute(self, nums: List[int]) -> List[List[int]]:
"""Version B1 Proxy-version, convert to permutation of indexes, then replace with nums[idx]"""
total_n = factorial(len(nums))
result = []
perm_idxs = list(range(len(nums)))
for i in range(total_n):
... | the_stack_v2_python_sparse | LeetCode/LC046_permutations.py | jxie0755/Learning_Python | train | 0 | |
03f438eafa7b90e0e524fcb3ec1af999b6a823c0 | [
"raw_colors = [c.hex for c in list(Color(start_color).range_to(Color(end_color), quantity))]\ncolors = []\nfor color in raw_colors:\n if len(color) == 4:\n fixed_color = '#'\n for c in color[1:]:\n fixed_color += c * 2\n colors.append(fixed_color)\n else:\n colors.append... | <|body_start_0|>
raw_colors = [c.hex for c in list(Color(start_color).range_to(Color(end_color), quantity))]
colors = []
for color in raw_colors:
if len(color) == 4:
fixed_color = '#'
for c in color[1:]:
fixed_color += c * 2
... | Class to dynamically generate and select colors. Requires the PyPI package `colour` | ColorRangeModule | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColorRangeModule:
"""Class to dynamically generate and select colors. Requires the PyPI package `colour`"""
def get_hex_color_range(start_color, end_color, quantity):
"""Generates a list of quantity Hex colors from start_color to end_color. :param start_color: Hex or plain English co... | stack_v2_sparse_classes_36k_train_011479 | 1,863 | permissive | [
{
"docstring": "Generates a list of quantity Hex colors from start_color to end_color. :param start_color: Hex or plain English color for start of range :param end_color: Hex or plain English color for end of range :param quantity: Number of colours to return :return: A list of Hex color values",
"name": "g... | 3 | null | Implement the Python class `ColorRangeModule` described below.
Class description:
Class to dynamically generate and select colors. Requires the PyPI package `colour`
Method signatures and docstrings:
- def get_hex_color_range(start_color, end_color, quantity): Generates a list of quantity Hex colors from start_color ... | Implement the Python class `ColorRangeModule` described below.
Class description:
Class to dynamically generate and select colors. Requires the PyPI package `colour`
Method signatures and docstrings:
- def get_hex_color_range(start_color, end_color, quantity): Generates a list of quantity Hex colors from start_color ... | 0820dd4e3d479dddec7797b2ea9a83da0f62b7cf | <|skeleton|>
class ColorRangeModule:
"""Class to dynamically generate and select colors. Requires the PyPI package `colour`"""
def get_hex_color_range(start_color, end_color, quantity):
"""Generates a list of quantity Hex colors from start_color to end_color. :param start_color: Hex or plain English co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ColorRangeModule:
"""Class to dynamically generate and select colors. Requires the PyPI package `colour`"""
def get_hex_color_range(start_color, end_color, quantity):
"""Generates a list of quantity Hex colors from start_color to end_color. :param start_color: Hex or plain English color for start... | the_stack_v2_python_sparse | i3pystatus/core/color.py | enkore/i3pystatus | train | 438 |
855359077d0f2e6676ee38707ad9f0b4a4cf36fb | [
"super().__init__()\nself.multioutputWrapper = True\nimport sklearn\nimport sklearn.ensemble\nself.model = sklearn.ensemble.StackingRegressor",
"specs = super().getInputSpecification()\nspecs.description = 'The \\\\xmlNode{StackingRegressor} consists in stacking the output of individual estimator and\\n ... | <|body_start_0|>
super().__init__()
self.multioutputWrapper = True
import sklearn
import sklearn.ensemble
self.model = sklearn.ensemble.StackingRegressor
<|end_body_0|>
<|body_start_1|>
specs = super().getInputSpecification()
specs.description = 'The \\xmlNode{St... | Stack of estimators with a final regressor. | StackingRegressor | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StackingRegressor:
"""Stack of estimators with a final regressor."""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputSpecification(cls):
"""Method to get a referen... | stack_v2_sparse_classes_36k_train_011480 | 5,877 | permissive | [
{
"docstring": "Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for... | 4 | null | Implement the Python class `StackingRegressor` described below.
Class description:
Stack of estimators with a final regressor.
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None
- def getInputSpecification(cls): Me... | Implement the Python class `StackingRegressor` described below.
Class description:
Stack of estimators with a final regressor.
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None
- def getInputSpecification(cls): Me... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class StackingRegressor:
"""Stack of estimators with a final regressor."""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputSpecification(cls):
"""Method to get a referen... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StackingRegressor:
"""Stack of estimators with a final regressor."""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
super().__init__()
self.multioutputWrapper = True
import sklearn
import... | the_stack_v2_python_sparse | ravenframework/SupervisedLearning/ScikitLearn/Ensemble/StackingRegressor.py | idaholab/raven | train | 201 |
098e483da95d13d2ebe99bd4da1def90324f1f66 | [
"if not isinstance(min_length, int):\n raise TypeError('min_length must be Integer')\nif min_length < 0:\n raise ValueError('min_length must be lager 0')\nif not isinstance(max_length, int):\n raise TypeError('max_length must be Integer')\nif min_length > max_length:\n raise ValueError('must (min_length... | <|body_start_0|>
if not isinstance(min_length, int):
raise TypeError('min_length must be Integer')
if min_length < 0:
raise ValueError('min_length must be lager 0')
if not isinstance(max_length, int):
raise TypeError('max_length must be Integer')
if mi... | 字符串类型的数据描述符 | CharField | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CharField:
"""字符串类型的数据描述符"""
def __init__(self, *args, min_length=0, max_length=256, regx='', **kwargs):
""":param args: :param min_length: :param max_length: :param regx: 用于验证value是否匹配规则 :param kwargs:"""
<|body_0|>
def _validate(self, value):
"""value必须是字符串,同时长... | stack_v2_sparse_classes_36k_train_011481 | 3,660 | no_license | [
{
"docstring": ":param args: :param min_length: :param max_length: :param regx: 用于验证value是否匹配规则 :param kwargs:",
"name": "__init__",
"signature": "def __init__(self, *args, min_length=0, max_length=256, regx='', **kwargs)"
},
{
"docstring": "value必须是字符串,同时长度在min_length和max_length之间,能和regx完全匹配 :p... | 2 | stack_v2_sparse_classes_30k_train_000779 | Implement the Python class `CharField` described below.
Class description:
字符串类型的数据描述符
Method signatures and docstrings:
- def __init__(self, *args, min_length=0, max_length=256, regx='', **kwargs): :param args: :param min_length: :param max_length: :param regx: 用于验证value是否匹配规则 :param kwargs:
- def _validate(self, va... | Implement the Python class `CharField` described below.
Class description:
字符串类型的数据描述符
Method signatures and docstrings:
- def __init__(self, *args, min_length=0, max_length=256, regx='', **kwargs): :param args: :param min_length: :param max_length: :param regx: 用于验证value是否匹配规则 :param kwargs:
- def _validate(self, va... | 5e28d5db63ebe23d5004fff19104f2ef7fdbd327 | <|skeleton|>
class CharField:
"""字符串类型的数据描述符"""
def __init__(self, *args, min_length=0, max_length=256, regx='', **kwargs):
""":param args: :param min_length: :param max_length: :param regx: 用于验证value是否匹配规则 :param kwargs:"""
<|body_0|>
def _validate(self, value):
"""value必须是字符串,同时长... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CharField:
"""字符串类型的数据描述符"""
def __init__(self, *args, min_length=0, max_length=256, regx='', **kwargs):
""":param args: :param min_length: :param max_length: :param regx: 用于验证value是否匹配规则 :param kwargs:"""
if not isinstance(min_length, int):
raise TypeError('min_length must be... | the_stack_v2_python_sparse | FluentPython/20属性描述符/03属性描述符.py | cpfyjjs/python | train | 0 |
dd8266505d6a1a0b4ec503befb0b2c23012c70ea | [
"if kernel_initializer is None:\n kernel_initializer = functools.partial(variance_scaling_init, gain=math.sqrt(1.0 / 3), mode='fan_in', distribution='uniform')\nobservation_spec, action_spec = input_tensor_spec\nobs_encoder = EncodingNetwork(observation_spec, input_preprocessors=observation_input_processors, pre... | <|body_start_0|>
if kernel_initializer is None:
kernel_initializer = functools.partial(variance_scaling_init, gain=math.sqrt(1.0 / 3), mode='fan_in', distribution='uniform')
observation_spec, action_spec = input_tensor_spec
obs_encoder = EncodingNetwork(observation_spec, input_prepro... | Creates an instance of ``CriticNetwork`` for estimating action-value of continuous or discrete actions. The action-value is defined as the expected return starting from the given input observation and taking the given action. This module takes observation as input and action as input and outputs an action-value tensor ... | CriticNetwork | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CriticNetwork:
"""Creates an instance of ``CriticNetwork`` for estimating action-value of continuous or discrete actions. The action-value is defined as the expected return starting from the given input observation and taking the given action. This module takes observation as input and action as ... | stack_v2_sparse_classes_36k_train_011482 | 14,681 | permissive | [
{
"docstring": "Args: input_tensor_spec: A tuple of ``TensorSpec``s ``(observation_spec, action_spec)`` representing the inputs. output_tensor_spec (TensorSpec): spec for the output observation_input_preprocessors (nested Network|nn.Module|None): a nest of input preprocessors, each of which will be applied to t... | 2 | stack_v2_sparse_classes_30k_train_002013 | Implement the Python class `CriticNetwork` described below.
Class description:
Creates an instance of ``CriticNetwork`` for estimating action-value of continuous or discrete actions. The action-value is defined as the expected return starting from the given input observation and taking the given action. This module ta... | Implement the Python class `CriticNetwork` described below.
Class description:
Creates an instance of ``CriticNetwork`` for estimating action-value of continuous or discrete actions. The action-value is defined as the expected return starting from the given input observation and taking the given action. This module ta... | b00ff2fa5e660de31020338ba340263183fbeaa4 | <|skeleton|>
class CriticNetwork:
"""Creates an instance of ``CriticNetwork`` for estimating action-value of continuous or discrete actions. The action-value is defined as the expected return starting from the given input observation and taking the given action. This module takes observation as input and action as ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CriticNetwork:
"""Creates an instance of ``CriticNetwork`` for estimating action-value of continuous or discrete actions. The action-value is defined as the expected return starting from the given input observation and taking the given action. This module takes observation as input and action as input and out... | the_stack_v2_python_sparse | alf/networks/critic_networks.py | HorizonRobotics/alf | train | 288 |
6e7ecb404ee43b4f766ec93fee08b22db9ab9c8a | [
"from __builtin__ import xrange\ncnt = [0]\n\ndef count(ary):\n for i in xrange(len(ary)):\n if i == 0:\n cnt[0] = cnt[0] + sum(ary[i])\n continue\n for j in xrange(len(ary[0])):\n if ary[i][j] == 1:\n if ary[i - 1][j] != 1:\n cnt[0... | <|body_start_0|>
from __builtin__ import xrange
cnt = [0]
def count(ary):
for i in xrange(len(ary)):
if i == 0:
cnt[0] = cnt[0] + sum(ary[i])
continue
for j in xrange(len(ary[0])):
if ary[i][... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def islandPerimeter(self, grid):
""":type grid: List[List[int]] :rtype: int 翻轉四次 一次只處理單一方向. 即處理北面。"""
<|body_0|>
def rewrite(self, grid):
""":type grid: List[List[int]] :rtype: int [0, 1, 0, 0] [0, 0, 1, 0, 0] [0, 1, 0, 0, 0]"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_011483 | 2,201 | no_license | [
{
"docstring": ":type grid: List[List[int]] :rtype: int 翻轉四次 一次只處理單一方向. 即處理北面。",
"name": "islandPerimeter",
"signature": "def islandPerimeter(self, grid)"
},
{
"docstring": ":type grid: List[List[int]] :rtype: int [0, 1, 0, 0] [0, 0, 1, 0, 0] [0, 1, 0, 0, 0]",
"name": "rewrite",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_011271 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def islandPerimeter(self, grid): :type grid: List[List[int]] :rtype: int 翻轉四次 一次只處理單一方向. 即處理北面。
- def rewrite(self, grid): :type grid: List[List[int]] :rtype: int [0, 1, 0, 0] [0... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def islandPerimeter(self, grid): :type grid: List[List[int]] :rtype: int 翻轉四次 一次只處理單一方向. 即處理北面。
- def rewrite(self, grid): :type grid: List[List[int]] :rtype: int [0, 1, 0, 0] [0... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def islandPerimeter(self, grid):
""":type grid: List[List[int]] :rtype: int 翻轉四次 一次只處理單一方向. 即處理北面。"""
<|body_0|>
def rewrite(self, grid):
""":type grid: List[List[int]] :rtype: int [0, 1, 0, 0] [0, 0, 1, 0, 0] [0, 1, 0, 0, 0]"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def islandPerimeter(self, grid):
""":type grid: List[List[int]] :rtype: int 翻轉四次 一次只處理單一方向. 即處理北面。"""
from __builtin__ import xrange
cnt = [0]
def count(ary):
for i in xrange(len(ary)):
if i == 0:
cnt[0] = cnt[0] + sum(... | the_stack_v2_python_sparse | co_fb/463_Island_Perimeter.py | vsdrun/lc_public | train | 6 | |
6c332649851f1ee551eedb5b8daac3639cb1395b | [
"super().__init__(coordinator, description)\nenpower = self.data.enpower\nassert enpower is not None\nself._attr_unique_id = f'{enpower.serial_number}_{description.key}'\nself._attr_device_info = DeviceInfo(identifiers={(DOMAIN, enpower.serial_number)}, manufacturer='Enphase', model='Enpower', name=f'Enpower {enpow... | <|body_start_0|>
super().__init__(coordinator, description)
enpower = self.data.enpower
assert enpower is not None
self._attr_unique_id = f'{enpower.serial_number}_{description.key}'
self._attr_device_info = DeviceInfo(identifiers={(DOMAIN, enpower.serial_number)}, manufacturer='... | Defines an Enpower binary_sensor entity. | EnvoyEnpowerBinarySensorEntity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnvoyEnpowerBinarySensorEntity:
"""Defines an Enpower binary_sensor entity."""
def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EnvoyEnpowerBinarySensorEntityDescription) -> None:
"""Init the Enpower base entity."""
<|body_0|>
def is_on(self) -> boo... | stack_v2_sparse_classes_36k_train_011484 | 5,991 | permissive | [
{
"docstring": "Init the Enpower base entity.",
"name": "__init__",
"signature": "def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EnvoyEnpowerBinarySensorEntityDescription) -> None"
},
{
"docstring": "Return the state of the Enpower binary_sensor.",
"name": "is_on",
... | 2 | null | Implement the Python class `EnvoyEnpowerBinarySensorEntity` described below.
Class description:
Defines an Enpower binary_sensor entity.
Method signatures and docstrings:
- def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EnvoyEnpowerBinarySensorEntityDescription) -> None: Init the Enpower base ... | Implement the Python class `EnvoyEnpowerBinarySensorEntity` described below.
Class description:
Defines an Enpower binary_sensor entity.
Method signatures and docstrings:
- def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EnvoyEnpowerBinarySensorEntityDescription) -> None: Init the Enpower base ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class EnvoyEnpowerBinarySensorEntity:
"""Defines an Enpower binary_sensor entity."""
def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EnvoyEnpowerBinarySensorEntityDescription) -> None:
"""Init the Enpower base entity."""
<|body_0|>
def is_on(self) -> boo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EnvoyEnpowerBinarySensorEntity:
"""Defines an Enpower binary_sensor entity."""
def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EnvoyEnpowerBinarySensorEntityDescription) -> None:
"""Init the Enpower base entity."""
super().__init__(coordinator, description)
... | the_stack_v2_python_sparse | homeassistant/components/enphase_envoy/binary_sensor.py | home-assistant/core | train | 35,501 |
9875779c98a5b505aa1a0d194a4af1e55f3450ed | [
"self.wins = np.zeros(2)\nself.m1, self.m2 = (m1, m2)\nself.mcst1, self.mcst2 = (MCST(args), MCST(args))\nself.game_setup = game\nself.num_duels = args.num_duels\nself.num_sims = args.num_sims_duel\nself.terminal = False\nself.args = args",
"if self.terminal:\n raise Exception('This pit has already been played... | <|body_start_0|>
self.wins = np.zeros(2)
self.m1, self.m2 = (m1, m2)
self.mcst1, self.mcst2 = (MCST(args), MCST(args))
self.game_setup = game
self.num_duels = args.num_duels
self.num_sims = args.num_sims_duel
self.terminal = False
self.args = args
<|end_bo... | Two models enter the pit to play a number of games to see which model is better | Pit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pit:
"""Two models enter the pit to play a number of games to see which model is better"""
def __init__(self, m1: Model, m2: Model, game: callable, args: argparse.Namespace):
"""Create a new pit :param m1: Model 1 :param m2: Model 2 :param game: Function that returns the initial game... | stack_v2_sparse_classes_36k_train_011485 | 3,233 | no_license | [
{
"docstring": "Create a new pit :param m1: Model 1 :param m2: Model 2 :param game: Function that returns the initial game state of the game to be played (typically its constructor) Takes 1 argument. Namely the argparse.Namespace used to pass parameters :param args: Parsed arguments containing hyperparameters -... | 2 | stack_v2_sparse_classes_30k_train_007007 | Implement the Python class `Pit` described below.
Class description:
Two models enter the pit to play a number of games to see which model is better
Method signatures and docstrings:
- def __init__(self, m1: Model, m2: Model, game: callable, args: argparse.Namespace): Create a new pit :param m1: Model 1 :param m2: Mo... | Implement the Python class `Pit` described below.
Class description:
Two models enter the pit to play a number of games to see which model is better
Method signatures and docstrings:
- def __init__(self, m1: Model, m2: Model, game: callable, args: argparse.Namespace): Create a new pit :param m1: Model 1 :param m2: Mo... | 2a01e61dc6e64341c3dda204990f1ffce828b957 | <|skeleton|>
class Pit:
"""Two models enter the pit to play a number of games to see which model is better"""
def __init__(self, m1: Model, m2: Model, game: callable, args: argparse.Namespace):
"""Create a new pit :param m1: Model 1 :param m2: Model 2 :param game: Function that returns the initial game... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pit:
"""Two models enter the pit to play a number of games to see which model is better"""
def __init__(self, m1: Model, m2: Model, game: callable, args: argparse.Namespace):
"""Create a new pit :param m1: Model 1 :param m2: Model 2 :param game: Function that returns the initial game state of the... | the_stack_v2_python_sparse | alphazero/duel.py | ronvree/AlphaZero | train | 0 |
5ab29d17aea4b30ae1bbbb68e0cf723a555c5e36 | [
"super(CheckMainPage, cls).setUpClass()\ncls.pagelogin = CBSLogin(cls.browserclass.get_driver())\ncls.pageindex = PageIndex(cls.browserclass.get_driver())",
"self.log.info('--------- Start Login ---------')\nself.browserclass.get_driver().get(self.loginurl)\nself.pagelogin.userlogin('admin', '!000000als')\ncheck ... | <|body_start_0|>
super(CheckMainPage, cls).setUpClass()
cls.pagelogin = CBSLogin(cls.browserclass.get_driver())
cls.pageindex = PageIndex(cls.browserclass.get_driver())
<|end_body_0|>
<|body_start_1|>
self.log.info('--------- Start Login ---------')
self.browserclass.get_driver(... | CheckMainPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckMainPage:
def setUpClass(cls):
"""测试类中所有测试方法执行前执行的方法"""
<|body_0|>
def test_a_weblogin(self):
"""登录测试,并为后面的菜单页面check测试,提供登录后的系统操作 :return:"""
<|body_1|>
def test_b_pagecheck(self, menu1, menu2, menu3, check_a):
"""数据驱动,左侧菜单点击及页面显示check 三个参数依... | stack_v2_sparse_classes_36k_train_011486 | 10,766 | no_license | [
{
"docstring": "测试类中所有测试方法执行前执行的方法",
"name": "setUpClass",
"signature": "def setUpClass(cls)"
},
{
"docstring": "登录测试,并为后面的菜单页面check测试,提供登录后的系统操作 :return:",
"name": "test_a_weblogin",
"signature": "def test_a_weblogin(self)"
},
{
"docstring": "数据驱动,左侧菜单点击及页面显示check 三个参数依次是 一级菜单 二... | 3 | stack_v2_sparse_classes_30k_train_003343 | Implement the Python class `CheckMainPage` described below.
Class description:
Implement the CheckMainPage class.
Method signatures and docstrings:
- def setUpClass(cls): 测试类中所有测试方法执行前执行的方法
- def test_a_weblogin(self): 登录测试,并为后面的菜单页面check测试,提供登录后的系统操作 :return:
- def test_b_pagecheck(self, menu1, menu2, menu3, check_a... | Implement the Python class `CheckMainPage` described below.
Class description:
Implement the CheckMainPage class.
Method signatures and docstrings:
- def setUpClass(cls): 测试类中所有测试方法执行前执行的方法
- def test_a_weblogin(self): 登录测试,并为后面的菜单页面check测试,提供登录后的系统操作 :return:
- def test_b_pagecheck(self, menu1, menu2, menu3, check_a... | 08b98e08b76ed2a4984efb7f543ed63eabe30757 | <|skeleton|>
class CheckMainPage:
def setUpClass(cls):
"""测试类中所有测试方法执行前执行的方法"""
<|body_0|>
def test_a_weblogin(self):
"""登录测试,并为后面的菜单页面check测试,提供登录后的系统操作 :return:"""
<|body_1|>
def test_b_pagecheck(self, menu1, menu2, menu3, check_a):
"""数据驱动,左侧菜单点击及页面显示check 三个参数依... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CheckMainPage:
def setUpClass(cls):
"""测试类中所有测试方法执行前执行的方法"""
super(CheckMainPage, cls).setUpClass()
cls.pagelogin = CBSLogin(cls.browserclass.get_driver())
cls.pageindex = PageIndex(cls.browserclass.get_driver())
def test_a_weblogin(self):
"""登录测试,并为后面的菜单页面check测试,... | the_stack_v2_python_sparse | Sys_CBS/TestClass/CBScheckMainPage.py | duozi/webUITestLight | train | 0 | |
02c5921e5aa04f23f0ccb1ba8fdac60265fd5789 | [
"self.factory = factory\nself.args = args\nself.kwargs = kwargs",
"factory = self.factory\nif factory is None:\n return []\ncns = []\nfor cn in factory(component, *self.args, **self.kwargs):\n if isinstance(cn, ConstraintHelper):\n cns.extend(cn.create_constraints(component))\n elif cn is not None... | <|body_start_0|>
self.factory = factory
self.args = args
self.kwargs = kwargs
<|end_body_0|>
<|body_start_1|>
factory = self.factory
if factory is None:
return []
cns = []
for cn in factory(component, *self.args, **self.kwargs):
if isinsta... | A constraint helper which delegates to a factory callable. | FactoryHelper | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FactoryHelper:
"""A constraint helper which delegates to a factory callable."""
def __init__(self, factory, *args, **kwargs):
"""Initialize a FactoryHelper. Parameters ---------- factory : callable The callable object which generates the constraints. *args Additional positional argum... | stack_v2_sparse_classes_36k_train_011487 | 2,063 | permissive | [
{
"docstring": "Initialize a FactoryHelper. Parameters ---------- factory : callable The callable object which generates the constraints. *args Additional positional arguments to pass to the factory. **kwargs Additional keyword arguments to pass to the factory.",
"name": "__init__",
"signature": "def __... | 2 | stack_v2_sparse_classes_30k_train_021392 | Implement the Python class `FactoryHelper` described below.
Class description:
A constraint helper which delegates to a factory callable.
Method signatures and docstrings:
- def __init__(self, factory, *args, **kwargs): Initialize a FactoryHelper. Parameters ---------- factory : callable The callable object which gen... | Implement the Python class `FactoryHelper` described below.
Class description:
A constraint helper which delegates to a factory callable.
Method signatures and docstrings:
- def __init__(self, factory, *args, **kwargs): Initialize a FactoryHelper. Parameters ---------- factory : callable The callable object which gen... | b54467b48941ce20d0ffadb7385483d2e51963f5 | <|skeleton|>
class FactoryHelper:
"""A constraint helper which delegates to a factory callable."""
def __init__(self, factory, *args, **kwargs):
"""Initialize a FactoryHelper. Parameters ---------- factory : callable The callable object which generates the constraints. *args Additional positional argum... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FactoryHelper:
"""A constraint helper which delegates to a factory callable."""
def __init__(self, factory, *args, **kwargs):
"""Initialize a FactoryHelper. Parameters ---------- factory : callable The callable object which generates the constraints. *args Additional positional arguments to pass ... | the_stack_v2_python_sparse | enaml/layout/factory_helper.py | bburan/enaml | train | 0 |
9442ac5241fd80e47a98b0f6a38a5b52536c1832 | [
"username = self.cleaned_data.get('username').lower()\nif username == 'anonymous':\n raise forms.ValidationError(_('This username is already taken'), code='invalid', params={'username': username})\nreturn username",
"email = self.cleaned_data.get('email').lower()\nif not validators.is_email_valid(email):\n ... | <|body_start_0|>
username = self.cleaned_data.get('username').lower()
if username == 'anonymous':
raise forms.ValidationError(_('This username is already taken'), code='invalid', params={'username': username})
return username
<|end_body_0|>
<|body_start_1|>
email = self.clea... | A mixin to clean the fields used for user registration | CleanUserDetailsMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CleanUserDetailsMixin:
"""A mixin to clean the fields used for user registration"""
def clean_username(self):
"""Return username in lower case, invalidates `anonymous` as username"""
<|body_0|>
def clean_email(self):
"""Returns email address in lower case if emai... | stack_v2_sparse_classes_36k_train_011488 | 2,460 | permissive | [
{
"docstring": "Return username in lower case, invalidates `anonymous` as username",
"name": "clean_username",
"signature": "def clean_username(self)"
},
{
"docstring": "Returns email address in lower case if email is valid and unique error message in case it isn't.",
"name": "clean_email",
... | 4 | stack_v2_sparse_classes_30k_train_012134 | Implement the Python class `CleanUserDetailsMixin` described below.
Class description:
A mixin to clean the fields used for user registration
Method signatures and docstrings:
- def clean_username(self): Return username in lower case, invalidates `anonymous` as username
- def clean_email(self): Returns email address ... | Implement the Python class `CleanUserDetailsMixin` described below.
Class description:
A mixin to clean the fields used for user registration
Method signatures and docstrings:
- def clean_username(self): Return username in lower case, invalidates `anonymous` as username
- def clean_email(self): Returns email address ... | 9b0819fc999c6f923346b4ac0399bafe58207ab1 | <|skeleton|>
class CleanUserDetailsMixin:
"""A mixin to clean the fields used for user registration"""
def clean_username(self):
"""Return username in lower case, invalidates `anonymous` as username"""
<|body_0|>
def clean_email(self):
"""Returns email address in lower case if emai... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CleanUserDetailsMixin:
"""A mixin to clean the fields used for user registration"""
def clean_username(self):
"""Return username in lower case, invalidates `anonymous` as username"""
username = self.cleaned_data.get('username').lower()
if username == 'anonymous':
raise... | the_stack_v2_python_sparse | ideas/mixins.py | abhiabhi94/idea-fare | train | 0 |
32d143d07062c9fe2b828ae50efc8697cb18b37b | [
"from promptlayer.utils import get_api_key, promptlayer_api_request\nrequest_start_time = datetime.datetime.now().timestamp()\ngenerated_responses = super()._generate(messages, stop)\nrequest_end_time = datetime.datetime.now().timestamp()\nmessage_dicts, params = super()._create_message_dicts(messages, stop)\nfor i... | <|body_start_0|>
from promptlayer.utils import get_api_key, promptlayer_api_request
request_start_time = datetime.datetime.now().timestamp()
generated_responses = super()._generate(messages, stop)
request_end_time = datetime.datetime.now().timestamp()
message_dicts, params = supe... | Wrapper around OpenAI Chat large language models and PromptLayer. To use, you should have the ``openai`` and ``promptlayer`` python package installed, and the environment variable ``OPENAI_API_KEY`` and ``PROMPTLAYER_API_KEY`` set with your openAI API key and promptlayer key respectively. All parameters that can be pas... | PromptLayerChatOpenAI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PromptLayerChatOpenAI:
"""Wrapper around OpenAI Chat large language models and PromptLayer. To use, you should have the ``openai`` and ``promptlayer`` python package installed, and the environment variable ``OPENAI_API_KEY`` and ``PROMPTLAYER_API_KEY`` set with your openAI API key and promptlayer... | stack_v2_sparse_classes_36k_train_011489 | 4,203 | no_license | [
{
"docstring": "Call ChatOpenAI generate and then call PromptLayer API to log the request.",
"name": "_generate",
"signature": "def _generate(self, messages: List[BaseMessage], stop: Optional[List[str]]=None) -> ChatResult"
},
{
"docstring": "Call ChatOpenAI agenerate and then call PromptLayer t... | 2 | stack_v2_sparse_classes_30k_train_000511 | Implement the Python class `PromptLayerChatOpenAI` described below.
Class description:
Wrapper around OpenAI Chat large language models and PromptLayer. To use, you should have the ``openai`` and ``promptlayer`` python package installed, and the environment variable ``OPENAI_API_KEY`` and ``PROMPTLAYER_API_KEY`` set w... | Implement the Python class `PromptLayerChatOpenAI` described below.
Class description:
Wrapper around OpenAI Chat large language models and PromptLayer. To use, you should have the ``openai`` and ``promptlayer`` python package installed, and the environment variable ``OPENAI_API_KEY`` and ``PROMPTLAYER_API_KEY`` set w... | b7aaa920a52613e3f1f04fa5cd7568ad37302d11 | <|skeleton|>
class PromptLayerChatOpenAI:
"""Wrapper around OpenAI Chat large language models and PromptLayer. To use, you should have the ``openai`` and ``promptlayer`` python package installed, and the environment variable ``OPENAI_API_KEY`` and ``PROMPTLAYER_API_KEY`` set with your openAI API key and promptlayer... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PromptLayerChatOpenAI:
"""Wrapper around OpenAI Chat large language models and PromptLayer. To use, you should have the ``openai`` and ``promptlayer`` python package installed, and the environment variable ``OPENAI_API_KEY`` and ``PROMPTLAYER_API_KEY`` set with your openAI API key and promptlayer key respecti... | the_stack_v2_python_sparse | openai/venv/lib/python3.10/site-packages/langchain/chat_models/promptlayer_openai.py | henrymendez/garage | train | 0 |
7020c10ae6df9a131d61ab910d907159c820a7ff | [
"if Ices.objects.filter(type=value.lower()):\n raise serializers.ValidationError('There already exist such type')\nreturn value",
"ret = super().to_representation(instance)\nret['type'] = ret['type'].lower()\nreturn ret"
] | <|body_start_0|>
if Ices.objects.filter(type=value.lower()):
raise serializers.ValidationError('There already exist such type')
return value
<|end_body_0|>
<|body_start_1|>
ret = super().to_representation(instance)
ret['type'] = ret['type'].lower()
return ret
<|end_b... | AddIcesSerializers | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddIcesSerializers:
def validate_type(self, value):
"""Check the duplicate"""
<|body_0|>
def to_representation(self, instance):
"""Convert `type` to lowercase."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if Ices.objects.filter(type=value.lower()... | stack_v2_sparse_classes_36k_train_011490 | 4,598 | permissive | [
{
"docstring": "Check the duplicate",
"name": "validate_type",
"signature": "def validate_type(self, value)"
},
{
"docstring": "Convert `type` to lowercase.",
"name": "to_representation",
"signature": "def to_representation(self, instance)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019934 | Implement the Python class `AddIcesSerializers` described below.
Class description:
Implement the AddIcesSerializers class.
Method signatures and docstrings:
- def validate_type(self, value): Check the duplicate
- def to_representation(self, instance): Convert `type` to lowercase. | Implement the Python class `AddIcesSerializers` described below.
Class description:
Implement the AddIcesSerializers class.
Method signatures and docstrings:
- def validate_type(self, value): Check the duplicate
- def to_representation(self, instance): Convert `type` to lowercase.
<|skeleton|>
class AddIcesSerialize... | 6a935bb77db3996dcf14b71deed8d7ca5c8f0fa3 | <|skeleton|>
class AddIcesSerializers:
def validate_type(self, value):
"""Check the duplicate"""
<|body_0|>
def to_representation(self, instance):
"""Convert `type` to lowercase."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddIcesSerializers:
def validate_type(self, value):
"""Check the duplicate"""
if Ices.objects.filter(type=value.lower()):
raise serializers.ValidationError('There already exist such type')
return value
def to_representation(self, instance):
"""Convert `type` to... | the_stack_v2_python_sparse | drf_api/serializers.py | destro6984/LynxWasp | train | 0 | |
32ea750195306db37630f9fa0e016895da71ca59 | [
"super(PointPillars, self).__init__()\nself.conf = conf\nself.training = training\nself.use_boxmatch = use_boxmatch\nself.featurenet = FeatureNet(conf['featurenet'], conf['pillars'])\nself.backbone = Backbone(conf['featurenet'])\nself.head = Head(conf['head'])\nself.boxmatch = BoxMatch(conf['pillars'], conf['head']... | <|body_start_0|>
super(PointPillars, self).__init__()
self.conf = conf
self.training = training
self.use_boxmatch = use_boxmatch
self.featurenet = FeatureNet(conf['featurenet'], conf['pillars'])
self.backbone = Backbone(conf['featurenet'])
self.head = Head(conf['h... | PointPillars | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointPillars:
def __init__(self, conf, training: bool=True, use_boxmatch: bool=False):
"""A wrapper which combines all of the individual pointpillar modules. :param conf: :param training: If used in training or prediction mode. :returns: Depending on training or prediction mode"""
... | stack_v2_sparse_classes_36k_train_011491 | 3,281 | no_license | [
{
"docstring": "A wrapper which combines all of the individual pointpillar modules. :param conf: :param training: If used in training or prediction mode. :returns: Depending on training or prediction mode",
"name": "__init__",
"signature": "def __init__(self, conf, training: bool=True, use_boxmatch: boo... | 2 | stack_v2_sparse_classes_30k_train_010530 | Implement the Python class `PointPillars` described below.
Class description:
Implement the PointPillars class.
Method signatures and docstrings:
- def __init__(self, conf, training: bool=True, use_boxmatch: bool=False): A wrapper which combines all of the individual pointpillar modules. :param conf: :param training:... | Implement the Python class `PointPillars` described below.
Class description:
Implement the PointPillars class.
Method signatures and docstrings:
- def __init__(self, conf, training: bool=True, use_boxmatch: bool=False): A wrapper which combines all of the individual pointpillar modules. :param conf: :param training:... | 019144896551fc590bf2fa03d29424ca27ca6e9f | <|skeleton|>
class PointPillars:
def __init__(self, conf, training: bool=True, use_boxmatch: bool=False):
"""A wrapper which combines all of the individual pointpillar modules. :param conf: :param training: If used in training or prediction mode. :returns: Depending on training or prediction mode"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PointPillars:
def __init__(self, conf, training: bool=True, use_boxmatch: bool=False):
"""A wrapper which combines all of the individual pointpillar modules. :param conf: :param training: If used in training or prediction mode. :returns: Depending on training or prediction mode"""
super(PointP... | the_stack_v2_python_sparse | pointpillars/modules/pointpillars.py | Riwaly/pointpillars | train | 0 | |
503c72178d8d2931ae0e3700e7ee3a0b5478a821 | [
"result = {'result': 'NG'}\ndata = request.get_json(force=True)\nif data:\n succsee, message = CtrlQuotations().add_quotation(data)\n if succsee:\n result = {'result': 'OK', 'content': message}\n else:\n result['error'] = message\nelse:\n result['error'] = '请不要传空数据'\nreturn result",
"res... | <|body_start_0|>
result = {'result': 'NG'}
data = request.get_json(force=True)
if data:
succsee, message = CtrlQuotations().add_quotation(data)
if succsee:
result = {'result': 'OK', 'content': message}
else:
result['error'] = me... | ApiQuotationInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApiQuotationInfo:
def post(self):
"""发起报价 :return:"""
<|body_0|>
def get(self, pro_id):
"""获取所有base版本 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = {'result': 'NG'}
data = request.get_json(force=True)
if data:
... | stack_v2_sparse_classes_36k_train_011492 | 10,406 | no_license | [
{
"docstring": "发起报价 :return:",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "获取所有base版本 :return:",
"name": "get",
"signature": "def get(self, pro_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006790 | Implement the Python class `ApiQuotationInfo` described below.
Class description:
Implement the ApiQuotationInfo class.
Method signatures and docstrings:
- def post(self): 发起报价 :return:
- def get(self, pro_id): 获取所有base版本 :return: | Implement the Python class `ApiQuotationInfo` described below.
Class description:
Implement the ApiQuotationInfo class.
Method signatures and docstrings:
- def post(self): 发起报价 :return:
- def get(self, pro_id): 获取所有base版本 :return:
<|skeleton|>
class ApiQuotationInfo:
def post(self):
"""发起报价 :return:"""
... | 64b31e7bdfcb8a4c95f0a8a607f0bcff576cec11 | <|skeleton|>
class ApiQuotationInfo:
def post(self):
"""发起报价 :return:"""
<|body_0|>
def get(self, pro_id):
"""获取所有base版本 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ApiQuotationInfo:
def post(self):
"""发起报价 :return:"""
result = {'result': 'NG'}
data = request.get_json(force=True)
if data:
succsee, message = CtrlQuotations().add_quotation(data)
if succsee:
result = {'result': 'OK', 'content': message}... | the_stack_v2_python_sparse | koala/koala_server/app/api_1_0/api_quotations.py | lsn1183/web_project | train | 0 | |
6f5dd294ad55df4bafaf58136d7f79820b3dca5a | [
"if graph.is_directed():\n raise ValueError('the graph is directed')\nself.graph = graph\nself.mst = None\nself.distance = dict(((node, float('inf')) for node in self.graph.iternodes()))\nself.parent = dict(((node, None) for node in self.graph.iternodes()))\nself._in_queue = dict(((node, True) for node in self.g... | <|body_start_0|>
if graph.is_directed():
raise ValueError('the graph is directed')
self.graph = graph
self.mst = None
self.distance = dict(((node, float('inf')) for node in self.graph.iternodes()))
self.parent = dict(((node, None) for node in self.graph.iternodes()))
... | Prim's algorithm for finding a minimum spanning tree. The algorithm runs in O(E log V) time. Attributes ---------- graph : input undirected weighted graph or multigraph mst : graph (MST) distance : dict with nodes parent : dict with nodes (MST) _in_queue : dict, private _pq : priority queue, private Examples -------- >... | PrimMST | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrimMST:
"""Prim's algorithm for finding a minimum spanning tree. The algorithm runs in O(E log V) time. Attributes ---------- graph : input undirected weighted graph or multigraph mst : graph (MST) distance : dict with nodes parent : dict with nodes (MST) _in_queue : dict, private _pq : priority... | stack_v2_sparse_classes_36k_train_011493 | 14,685 | permissive | [
{
"docstring": "The algorithm initialization. Parameters ---------- graph : undirected weighted graph or multigraph",
"name": "__init__",
"signature": "def __init__(self, graph)"
},
{
"docstring": "Finding MST.",
"name": "run",
"signature": "def run(self, source=None)"
},
{
"docs... | 3 | stack_v2_sparse_classes_30k_train_002654 | Implement the Python class `PrimMST` described below.
Class description:
Prim's algorithm for finding a minimum spanning tree. The algorithm runs in O(E log V) time. Attributes ---------- graph : input undirected weighted graph or multigraph mst : graph (MST) distance : dict with nodes parent : dict with nodes (MST) _... | Implement the Python class `PrimMST` described below.
Class description:
Prim's algorithm for finding a minimum spanning tree. The algorithm runs in O(E log V) time. Attributes ---------- graph : input undirected weighted graph or multigraph mst : graph (MST) distance : dict with nodes parent : dict with nodes (MST) _... | 0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60 | <|skeleton|>
class PrimMST:
"""Prim's algorithm for finding a minimum spanning tree. The algorithm runs in O(E log V) time. Attributes ---------- graph : input undirected weighted graph or multigraph mst : graph (MST) distance : dict with nodes parent : dict with nodes (MST) _in_queue : dict, private _pq : priority... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrimMST:
"""Prim's algorithm for finding a minimum spanning tree. The algorithm runs in O(E log V) time. Attributes ---------- graph : input undirected weighted graph or multigraph mst : graph (MST) distance : dict with nodes parent : dict with nodes (MST) _in_queue : dict, private _pq : priority queue, priva... | the_stack_v2_python_sparse | graphtheory/spanningtrees/prim.py | kgashok/graphs-dict | train | 0 |
a5abc7bda7e2f30fa9f455e2bdc96d404b3758e4 | [
"self.width = width\nself.height = height\nself.space = space\nself.setLines(lines)",
"if isinstance(lines, basestring):\n lines = lines.split('\\n')\nelif not isinstance(lines, list):\n raise Exception('Argument passed to lines parameter must be list, instead got: %s' % type(lines))\nif len(lines) > self.h... | <|body_start_0|>
self.width = width
self.height = height
self.space = space
self.setLines(lines)
<|end_body_0|>
<|body_start_1|>
if isinstance(lines, basestring):
lines = lines.split('\n')
elif not isinstance(lines, list):
raise Exception('Argumen... | Object designed to auto-scroll text on a LCD screen. Every time the scroll() method is called to, it will scroll the text from right to left by one character on any line that is greater than the provided with. If the lines ever need to be reset \\ updated, call to the setLines() method. | Scroller | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Scroller:
"""Object designed to auto-scroll text on a LCD screen. Every time the scroll() method is called to, it will scroll the text from right to left by one character on any line that is greater than the provided with. If the lines ever need to be reset \\ updated, call to the setLines() meth... | stack_v2_sparse_classes_36k_train_011494 | 3,892 | no_license | [
{
"docstring": "Instance a LCD scroller object. Parameters: lines : list / string : Default empty list : If a list is passed in, each entry in the list is a string that should be displayed on the LCD, one line after the next. If a string, it will be split by any embedded linefeed characers into a list of multip... | 3 | null | Implement the Python class `Scroller` described below.
Class description:
Object designed to auto-scroll text on a LCD screen. Every time the scroll() method is called to, it will scroll the text from right to left by one character on any line that is greater than the provided with. If the lines ever need to be reset ... | Implement the Python class `Scroller` described below.
Class description:
Object designed to auto-scroll text on a LCD screen. Every time the scroll() method is called to, it will scroll the text from right to left by one character on any line that is greater than the provided with. If the lines ever need to be reset ... | ccfbc1f4b687e1c7961e83c44a9f1f8ab7c9538c | <|skeleton|>
class Scroller:
"""Object designed to auto-scroll text on a LCD screen. Every time the scroll() method is called to, it will scroll the text from right to left by one character on any line that is greater than the provided with. If the lines ever need to be reset \\ updated, call to the setLines() meth... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Scroller:
"""Object designed to auto-scroll text on a LCD screen. Every time the scroll() method is called to, it will scroll the text from right to left by one character on any line that is greater than the provided with. If the lines ever need to be reset \\ updated, call to the setLines() method."""
d... | the_stack_v2_python_sparse | lcdscroll.py | slzatz/sonos-companion | train | 4 |
942f7e2ac06f33815a91e6f04e0527deb23a6d66 | [
"expected_result = np.array([[0.0125, 0.03125, 0.196875, 0.03125, 0.0125], [0.025, 0.0625, 0.29375, 0.0625, 0.025], [0.05, 0.125, 0.3375, 0.125, 0.05], [0.0, 0.0, 0.175, 0.0, 0.0], [0.0, 0.0, 0.1, 0.0, 0.0]])\nresult = RecursiveFilter(edge_width=1)._recurse_backward(self.cube.data[0, :], self.smoothing_coefficients... | <|body_start_0|>
expected_result = np.array([[0.0125, 0.03125, 0.196875, 0.03125, 0.0125], [0.025, 0.0625, 0.29375, 0.0625, 0.025], [0.05, 0.125, 0.3375, 0.125, 0.05], [0.0, 0.0, 0.175, 0.0, 0.0], [0.0, 0.0, 0.1, 0.0, 0.0]])
result = RecursiveFilter(edge_width=1)._recurse_backward(self.cube.data[0, :], ... | Test the _recurse_backward method | Test__recurse_backward | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__recurse_backward:
"""Test the _recurse_backward method"""
def test_first_axis(self):
"""Test that the returned _recurse_backward array has the expected type and result."""
<|body_0|>
def test_second_axis(self):
"""Test that the returned _recurse_backward ar... | stack_v2_sparse_classes_36k_train_011495 | 22,857 | permissive | [
{
"docstring": "Test that the returned _recurse_backward array has the expected type and result.",
"name": "test_first_axis",
"signature": "def test_first_axis(self)"
},
{
"docstring": "Test that the returned _recurse_backward array has the expected type and result.",
"name": "test_second_ax... | 2 | null | Implement the Python class `Test__recurse_backward` described below.
Class description:
Test the _recurse_backward method
Method signatures and docstrings:
- def test_first_axis(self): Test that the returned _recurse_backward array has the expected type and result.
- def test_second_axis(self): Test that the returned... | Implement the Python class `Test__recurse_backward` described below.
Class description:
Test the _recurse_backward method
Method signatures and docstrings:
- def test_first_axis(self): Test that the returned _recurse_backward array has the expected type and result.
- def test_second_axis(self): Test that the returned... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test__recurse_backward:
"""Test the _recurse_backward method"""
def test_first_axis(self):
"""Test that the returned _recurse_backward array has the expected type and result."""
<|body_0|>
def test_second_axis(self):
"""Test that the returned _recurse_backward ar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test__recurse_backward:
"""Test the _recurse_backward method"""
def test_first_axis(self):
"""Test that the returned _recurse_backward array has the expected type and result."""
expected_result = np.array([[0.0125, 0.03125, 0.196875, 0.03125, 0.0125], [0.025, 0.0625, 0.29375, 0.0625, 0.02... | the_stack_v2_python_sparse | improver_tests/nbhood/recursive_filter/test_RecursiveFilter.py | metoppv/improver | train | 101 |
867cde4548ab2a8595c0fa28ad1f63721c758a9f | [
"self.cls = cls\nself.taskTimeout = taskTimeout\nself.desc = desc\nif maxProcess is None:\n maxProcess = multiprocessing.cpu_count()\nself.maxProcess = min(maxProcess, multiprocessing.cpu_count())\nself.processes = []\nself._isProgressBar = isProgressBar",
"size = min(len(arguments), self.maxProcess)\ncollecti... | <|body_start_0|>
self.cls = cls
self.taskTimeout = taskTimeout
self.desc = desc
if maxProcess is None:
maxProcess = multiprocessing.cpu_count()
self.maxProcess = min(maxProcess, multiprocessing.cpu_count())
self.processes = []
self._isProgressBar = isP... | Interface to running in parallel multiple instances of the same function. The user implements a class that inherits from AbstractRunner and provides this class to the constructor of ParallelRunner. | ParallelRunner | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParallelRunner:
"""Interface to running in parallel multiple instances of the same function. The user implements a class that inherits from AbstractRunner and provides this class to the constructor of ParallelRunner."""
def __init__(self, cls, maxProcess=None, taskTimeout=TASK_TIMEOUT, desc=... | stack_v2_sparse_classes_36k_train_011496 | 8,953 | permissive | [
{
"docstring": "Parameters ---------- cls: Inherits from AbstractRunner maxProcess: int maximum number of concurrent tasks taskTimeout: float maximum runtime for a task desc: str description of the work unit isProgressBar: bool display the progress bar",
"name": "__init__",
"signature": "def __init__(se... | 3 | stack_v2_sparse_classes_30k_train_014487 | Implement the Python class `ParallelRunner` described below.
Class description:
Interface to running in parallel multiple instances of the same function. The user implements a class that inherits from AbstractRunner and provides this class to the constructor of ParallelRunner.
Method signatures and docstrings:
- def ... | Implement the Python class `ParallelRunner` described below.
Class description:
Interface to running in parallel multiple instances of the same function. The user implements a class that inherits from AbstractRunner and provides this class to the constructor of ParallelRunner.
Method signatures and docstrings:
- def ... | 31b184176a7f19074c905db76e6e6ac8e4fc36a8 | <|skeleton|>
class ParallelRunner:
"""Interface to running in parallel multiple instances of the same function. The user implements a class that inherits from AbstractRunner and provides this class to the constructor of ParallelRunner."""
def __init__(self, cls, maxProcess=None, taskTimeout=TASK_TIMEOUT, desc=... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParallelRunner:
"""Interface to running in parallel multiple instances of the same function. The user implements a class that inherits from AbstractRunner and provides this class to the constructor of ParallelRunner."""
def __init__(self, cls, maxProcess=None, taskTimeout=TASK_TIMEOUT, desc=WORK_UNIT_DES... | the_stack_v2_python_sparse | SBstoat/_parallelRunner.py | YunjeongLee/SBstoat | train | 0 |
10d64dfbcaab5e952d4cdc069765b170fac4c7ba | [
"today = date.today()\nthis_monday = today - timedelta(days=today.weekday())\nnext_monday = this_monday + timedelta(weeks=1)\nprev_monday = this_monday - timedelta(weeks=1)\nthis_monday = this_monday.strftime('%Y-%m-%d')\nnext_monday = next_monday.strftime('%Y-%m-%d')\nprev_monday = prev_monday.strftime('%Y-%m-%d')... | <|body_start_0|>
today = date.today()
this_monday = today - timedelta(days=today.weekday())
next_monday = this_monday + timedelta(weeks=1)
prev_monday = this_monday - timedelta(weeks=1)
this_monday = this_monday.strftime('%Y-%m-%d')
next_monday = next_monday.strftime('%Y-... | DateRangeRangeFilter | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DateRangeRangeFilter:
def lookups(self, request, model_admin):
"""Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right side... | stack_v2_sparse_classes_36k_train_011497 | 4,919 | permissive | [
{
"docstring": "Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar.",
"name": "lookups",
"signature": "def lookups(self, request,... | 2 | null | Implement the Python class `DateRangeRangeFilter` described below.
Class description:
Implement the DateRangeRangeFilter class.
Method signatures and docstrings:
- def lookups(self, request, model_admin): Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in t... | Implement the Python class `DateRangeRangeFilter` described below.
Class description:
Implement the DateRangeRangeFilter class.
Method signatures and docstrings:
- def lookups(self, request, model_admin): Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in t... | cee983bfcfc90f581b18712d558bc9d8a83a400a | <|skeleton|>
class DateRangeRangeFilter:
def lookups(self, request, model_admin):
"""Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right side... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DateRangeRangeFilter:
def lookups(self, request, model_admin):
"""Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar."""
... | the_stack_v2_python_sparse | apps/common/list_filter.py | gis4dis/poster | train | 3 | |
4cee7a401b7bf864752d86b0923e2a281bd8afbd | [
"self.board = Board(self, width, height)\nself.board.place_mines(num_mines)\nself.start = time.time()",
"while True:\n try:\n move = input(\"Move (col row, like 'ab' - %d left) > \" % self.board.left)\n col = ord(move[0].upper()) - ord('A')\n row = ord(move[1].upper()) - ord('A')\n ... | <|body_start_0|>
self.board = Board(self, width, height)
self.board.place_mines(num_mines)
self.start = time.time()
<|end_body_0|>
<|body_start_1|>
while True:
try:
move = input("Move (col row, like 'ab' - %d left) > " % self.board.left)
col =... | Minesweeper. | Game | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Game:
"""Minesweeper."""
def __init__(self, width=11, height=11, num_mines=11):
"""Initialize game. - Set up bord - Place mines - Note time (so at game end the delta can be shown)"""
<|body_0|>
def get_move(self):
"""Get a move, looping until we get a legal move"... | stack_v2_sparse_classes_36k_train_011498 | 5,366 | no_license | [
{
"docstring": "Initialize game. - Set up bord - Place mines - Note time (so at game end the delta can be shown)",
"name": "__init__",
"signature": "def __init__(self, width=11, height=11, num_mines=11)"
},
{
"docstring": "Get a move, looping until we get a legal move",
"name": "get_move",
... | 3 | stack_v2_sparse_classes_30k_train_000319 | Implement the Python class `Game` described below.
Class description:
Minesweeper.
Method signatures and docstrings:
- def __init__(self, width=11, height=11, num_mines=11): Initialize game. - Set up bord - Place mines - Note time (so at game end the delta can be shown)
- def get_move(self): Get a move, looping until... | Implement the Python class `Game` described below.
Class description:
Minesweeper.
Method signatures and docstrings:
- def __init__(self, width=11, height=11, num_mines=11): Initialize game. - Set up bord - Place mines - Note time (so at game end the delta can be shown)
- def get_move(self): Get a move, looping until... | 2244d63607be13c70c531a6e3064f85074111ca7 | <|skeleton|>
class Game:
"""Minesweeper."""
def __init__(self, width=11, height=11, num_mines=11):
"""Initialize game. - Set up bord - Place mines - Note time (so at game end the delta can be shown)"""
<|body_0|>
def get_move(self):
"""Get a move, looping until we get a legal move"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Game:
"""Minesweeper."""
def __init__(self, width=11, height=11, num_mines=11):
"""Initialize game. - Set up bord - Place mines - Note time (so at game end the delta can be shown)"""
self.board = Board(self, width, height)
self.board.place_mines(num_mines)
self.start = tim... | the_stack_v2_python_sparse | HARD/minesweeper/minesweeper.py | jenihuang/hb_challenges | train | 2 |
0c1e793257ac820523adc3dbe0b649d972f5bf0b | [
"BaseFeature.__init__(self, f'{name}_displacement', model, faults, regions, builder)\nself.fault_frame = StructuralFrame(f'{fault_frame.name}_displacementframe', [fault_frame[0].copy(), fault_frame[1].copy(), fault_frame[2].copy()])\nself.displacement = displacement",
"fault_suface = self.fault_frame.features[0].... | <|body_start_0|>
BaseFeature.__init__(self, f'{name}_displacement', model, faults, regions, builder)
self.fault_frame = StructuralFrame(f'{fault_frame.name}_displacementframe', [fault_frame[0].copy(), fault_frame[1].copy(), fault_frame[2].copy()])
self.displacement = displacement
<|end_body_0|>
... | FaultDisplacementFeature | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FaultDisplacementFeature:
def __init__(self, fault_frame, displacement, name='fault_displacement', model=None, faults=[], regions=[], builder=None):
"""Geological feature representing the fault displacement Parameters ---------- fault_frame - geometry of the fault displacement - function... | stack_v2_sparse_classes_36k_train_011499 | 2,390 | permissive | [
{
"docstring": "Geological feature representing the fault displacement Parameters ---------- fault_frame - geometry of the fault displacement - function defining fault displacement",
"name": "__init__",
"signature": "def __init__(self, fault_frame, displacement, name='fault_displacement', model=None, fa... | 4 | stack_v2_sparse_classes_30k_train_007861 | Implement the Python class `FaultDisplacementFeature` described below.
Class description:
Implement the FaultDisplacementFeature class.
Method signatures and docstrings:
- def __init__(self, fault_frame, displacement, name='fault_displacement', model=None, faults=[], regions=[], builder=None): Geological feature repr... | Implement the Python class `FaultDisplacementFeature` described below.
Class description:
Implement the FaultDisplacementFeature class.
Method signatures and docstrings:
- def __init__(self, fault_frame, displacement, name='fault_displacement', model=None, faults=[], regions=[], builder=None): Geological feature repr... | c6175623450dbc79ed06ed8d8bbff21b63fc8b4c | <|skeleton|>
class FaultDisplacementFeature:
def __init__(self, fault_frame, displacement, name='fault_displacement', model=None, faults=[], regions=[], builder=None):
"""Geological feature representing the fault displacement Parameters ---------- fault_frame - geometry of the fault displacement - function... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FaultDisplacementFeature:
def __init__(self, fault_frame, displacement, name='fault_displacement', model=None, faults=[], regions=[], builder=None):
"""Geological feature representing the fault displacement Parameters ---------- fault_frame - geometry of the fault displacement - function defining faul... | the_stack_v2_python_sparse | LoopStructural/modelling/features/fault/_fault_function_feature.py | Loop3D/LoopStructural | train | 123 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.