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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4a8bf5a3e5510e9685ce3886dd08cb4d3296ba1f | [
"if type(dm) is not int:\n raise TypeError('dm must be int representing dimensionality of model')\nif type(h) is not int:\n raise TypeError('h must be int representing number of heads')\nif type(hidden) is not int:\n raise TypeError('hidden must be int representing number of hidden units')\nif type(drop_ra... | <|body_start_0|>
if type(dm) is not int:
raise TypeError('dm must be int representing dimensionality of model')
if type(h) is not int:
raise TypeError('h must be int representing number of heads')
if type(hidden) is not int:
raise TypeError('hidden must be int... | Class to create an encoder block for a transformer class constructor: def __init__(self, dm, h, hidden, drop_rate=0.1) public instance attribute: mha: MultiHeadAttention layer dense_hidden: the hidden dense layer with hidden units, relu activation dense_output: the output dense layer with dm units layernorm1: the first... | EncoderBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderBlock:
"""Class to create an encoder block for a transformer class constructor: def __init__(self, dm, h, hidden, drop_rate=0.1) public instance attribute: mha: MultiHeadAttention layer dense_hidden: the hidden dense layer with hidden units, relu activation dense_output: the output dense l... | stack_v2_sparse_classes_36k_train_004200 | 3,990 | no_license | [
{
"docstring": "Class constructor parameters: dm [int]: represents the dimensionality of the model h [int]: represents the number of heads hidden [int]: represents the number of hidden units in fully connected layer drop_rate [float]: the dropout rate sets the public instance attributes: mha: MultiHeadAttention... | 2 | null | Implement the Python class `EncoderBlock` described below.
Class description:
Class to create an encoder block for a transformer class constructor: def __init__(self, dm, h, hidden, drop_rate=0.1) public instance attribute: mha: MultiHeadAttention layer dense_hidden: the hidden dense layer with hidden units, relu acti... | Implement the Python class `EncoderBlock` described below.
Class description:
Class to create an encoder block for a transformer class constructor: def __init__(self, dm, h, hidden, drop_rate=0.1) public instance attribute: mha: MultiHeadAttention layer dense_hidden: the hidden dense layer with hidden units, relu acti... | 8834b201ca84937365e4dcc0fac978656cdf5293 | <|skeleton|>
class EncoderBlock:
"""Class to create an encoder block for a transformer class constructor: def __init__(self, dm, h, hidden, drop_rate=0.1) public instance attribute: mha: MultiHeadAttention layer dense_hidden: the hidden dense layer with hidden units, relu activation dense_output: the output dense l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EncoderBlock:
"""Class to create an encoder block for a transformer class constructor: def __init__(self, dm, h, hidden, drop_rate=0.1) public instance attribute: mha: MultiHeadAttention layer dense_hidden: the hidden dense layer with hidden units, relu activation dense_output: the output dense layer with dm ... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/7-transformer_encoder_block.py | ejonakodra/holbertonschool-machine_learning-1 | train | 0 |
64fe7e624a47662c42b5c6cd7c74b4a4671cf300 | [
"d_collected_int = math.floor(days_collected)\nend_time = end_time or datetime.utcnow()\nearliest = end_time - timedelta(days=days_collected)\nself.avg_calculatable: bool = d_collected_int > HourlyResult.DAYS_NONE\nself.denom: List[float] = []\nif self.avg_calculatable:\n add_one_end = end_time.hour\n if earl... | <|body_start_0|>
d_collected_int = math.floor(days_collected)
end_time = end_time or datetime.utcnow()
earliest = end_time - timedelta(days=days_collected)
self.avg_calculatable: bool = d_collected_int > HourlyResult.DAYS_NONE
self.denom: List[float] = []
if self.avg_calc... | Base hourly result object. **Fields** ``avg_calculatable`` If this result can be used to calculate daily average. ``denom`` Denominators to divide the accumulated result number. Will be an empty list if ``avg_calculatable`` is ``False``. | HourlyResult | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HourlyResult:
"""Base hourly result object. **Fields** ``avg_calculatable`` If this result can be used to calculate daily average. ``denom`` Denominators to divide the accumulated result number. Will be an empty list if ``avg_calculatable`` is ``False``."""
def __init__(self, days_collected:... | stack_v2_sparse_classes_36k_train_004201 | 6,459 | permissive | [
{
"docstring": "Initalizing method of :class:`HourlyResult`. :param days_collected: \"claimed\" days collected of the data :param end_time: end time of the data. current time in UTC if not given",
"name": "__init__",
"signature": "def __init__(self, days_collected: float, *, end_time: Optional[datetime]... | 2 | stack_v2_sparse_classes_30k_train_009395 | Implement the Python class `HourlyResult` described below.
Class description:
Base hourly result object. **Fields** ``avg_calculatable`` If this result can be used to calculate daily average. ``denom`` Denominators to divide the accumulated result number. Will be an empty list if ``avg_calculatable`` is ``False``.
Me... | Implement the Python class `HourlyResult` described below.
Class description:
Base hourly result object. **Fields** ``avg_calculatable`` If this result can be used to calculate daily average. ``denom`` Denominators to divide the accumulated result number. Will be an empty list if ``avg_calculatable`` is ``False``.
Me... | c7da1e91783dce3a2b71b955b3a22b68db9056cf | <|skeleton|>
class HourlyResult:
"""Base hourly result object. **Fields** ``avg_calculatable`` If this result can be used to calculate daily average. ``denom`` Denominators to divide the accumulated result number. Will be an empty list if ``avg_calculatable`` is ``False``."""
def __init__(self, days_collected:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HourlyResult:
"""Base hourly result object. **Fields** ``avg_calculatable`` If this result can be used to calculate daily average. ``denom`` Denominators to divide the accumulated result number. Will be an empty list if ``avg_calculatable`` is ``False``."""
def __init__(self, days_collected: float, *, en... | the_stack_v2_python_sparse | models/stats/base.py | RxJellyBot/Jelly-Bot | train | 5 |
b4257887b8d6a5bb94094278fca578872485c976 | [
"if target.access(self, 'invisible'):\n self.msg(f\"Could not find '{target.key}'\")\n return\nif not target.access(self, 'view'):\n try:\n return \"Could not view '%s'.\" % target.get_display_name(self, **kwargs)\n except AttributeError:\n return \"Could not view '%s'.\" % target.key\ndes... | <|body_start_0|>
if target.access(self, 'invisible'):
self.msg(f"Could not find '{target.key}'")
return
if not target.access(self, 'view'):
try:
return "Could not view '%s'." % target.get_display_name(self, **kwargs)
except AttributeError:
... | A mixin to put on Character objects. This will allow | RespectInvisibilityMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RespectInvisibilityMixin:
"""A mixin to put on Character objects. This will allow"""
def at_look(self, target, **kwargs):
"""Called when this object performs a look. It allows to customize just what this means. It will not itself send any data. Args: target (Object): The target being... | stack_v2_sparse_classes_36k_train_004202 | 3,538 | no_license | [
{
"docstring": "Called when this object performs a look. It allows to customize just what this means. It will not itself send any data. Args: target (Object): The target being looked at. This is commonly an object or the current location. It will be checked for the \"view\" type access. **kwargs (dict): Arbitra... | 2 | stack_v2_sparse_classes_30k_train_008216 | Implement the Python class `RespectInvisibilityMixin` described below.
Class description:
A mixin to put on Character objects. This will allow
Method signatures and docstrings:
- def at_look(self, target, **kwargs): Called when this object performs a look. It allows to customize just what this means. It will not itse... | Implement the Python class `RespectInvisibilityMixin` described below.
Class description:
A mixin to put on Character objects. This will allow
Method signatures and docstrings:
- def at_look(self, target, **kwargs): Called when this object performs a look. It allows to customize just what this means. It will not itse... | f6a0cd4962680c7ee16df86cd9950c964748362f | <|skeleton|>
class RespectInvisibilityMixin:
"""A mixin to put on Character objects. This will allow"""
def at_look(self, target, **kwargs):
"""Called when this object performs a look. It allows to customize just what this means. It will not itself send any data. Args: target (Object): The target being... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RespectInvisibilityMixin:
"""A mixin to put on Character objects. This will allow"""
def at_look(self, target, **kwargs):
"""Called when this object performs a look. It allows to customize just what this means. It will not itself send any data. Args: target (Object): The target being looked at. T... | the_stack_v2_python_sparse | features/invisible_objects.py | CloudKeeper/develop | train | 2 |
a563fd25d30cabf2a6e1370d06f5cc5d674a82a0 | [
"if isinstance(image, ImageForPeopleEstimation):\n detectArea = image.detectArea.coreRectI\n image = image.image\nelse:\n detectArea = image.coreImage.getRect()\nvalidateInputByBatchEstimator(self._coreEstimator, [image.coreImage], [detectArea])\nif asyncEstimate:\n task = self._coreEstimator.asyncEstim... | <|body_start_0|>
if isinstance(image, ImageForPeopleEstimation):
detectArea = image.detectArea.coreRectI
image = image.image
else:
detectArea = image.coreImage.getRect()
validateInputByBatchEstimator(self._coreEstimator, [image.coreImage], [detectArea])
... | PeopleCountEstimator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PeopleCountEstimator:
def estimate(self, image: Union[VLImage, ImageForPeopleEstimation, Tuple[VLImage, Rect]], asyncEstimate: bool=False):
"""Estimate people count from single image Args: image: vl image asyncEstimate: estimate or run estimation in background Returns: estimated people c... | stack_v2_sparse_classes_36k_train_004203 | 4,506 | permissive | [
{
"docstring": "Estimate people count from single image Args: image: vl image asyncEstimate: estimate or run estimation in background Returns: estimated people count or async task if asyncEstimate is true Raises: LunaSDKException: if estimation is failed",
"name": "estimate",
"signature": "def estimate(... | 2 | stack_v2_sparse_classes_30k_train_012373 | Implement the Python class `PeopleCountEstimator` described below.
Class description:
Implement the PeopleCountEstimator class.
Method signatures and docstrings:
- def estimate(self, image: Union[VLImage, ImageForPeopleEstimation, Tuple[VLImage, Rect]], asyncEstimate: bool=False): Estimate people count from single im... | Implement the Python class `PeopleCountEstimator` described below.
Class description:
Implement the PeopleCountEstimator class.
Method signatures and docstrings:
- def estimate(self, image: Union[VLImage, ImageForPeopleEstimation, Tuple[VLImage, Rect]], asyncEstimate: bool=False): Estimate people count from single im... | 7a4bebc92ae7a96d8d9c18a024208308942f90cd | <|skeleton|>
class PeopleCountEstimator:
def estimate(self, image: Union[VLImage, ImageForPeopleEstimation, Tuple[VLImage, Rect]], asyncEstimate: bool=False):
"""Estimate people count from single image Args: image: vl image asyncEstimate: estimate or run estimation in background Returns: estimated people c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PeopleCountEstimator:
def estimate(self, image: Union[VLImage, ImageForPeopleEstimation, Tuple[VLImage, Rect]], asyncEstimate: bool=False):
"""Estimate people count from single image Args: image: vl image asyncEstimate: estimate or run estimation in background Returns: estimated people count or async ... | the_stack_v2_python_sparse | lunavl/sdk/estimators/image_estimators/people_count.py | matemax/lunasdk | train | 16 | |
aa5942db03b1a25adf77ccc02ad110ce76df3fd6 | [
"department = models.Department.query.get_or_404(department_id)\nschema = schemas.DepartmentSchema()\nresponse = schema.dump(department)\nreturn (response, 200)",
"department = models.Department.query.get_or_404(department_id)\nnew_name = request.json.get('name')\nif new_name is None:\n return ({'message': 'Na... | <|body_start_0|>
department = models.Department.query.get_or_404(department_id)
schema = schemas.DepartmentSchema()
response = schema.dump(department)
return (response, 200)
<|end_body_0|>
<|body_start_1|>
department = models.Department.query.get_or_404(department_id)
ne... | Rest class with methods GET, PUT, DELETE department. | Department | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Department:
"""Rest class with methods GET, PUT, DELETE department."""
def get(self, department_id):
"""Gets department by id. :param department_id: Id of the department being fetched. On success returns department data. On failure returns the status code 404. :rtype json"""
... | stack_v2_sparse_classes_36k_train_004204 | 4,247 | no_license | [
{
"docstring": "Gets department by id. :param department_id: Id of the department being fetched. On success returns department data. On failure returns the status code 404. :rtype json",
"name": "get",
"signature": "def get(self, department_id)"
},
{
"docstring": "Updates a department. :param de... | 3 | stack_v2_sparse_classes_30k_train_010274 | Implement the Python class `Department` described below.
Class description:
Rest class with methods GET, PUT, DELETE department.
Method signatures and docstrings:
- def get(self, department_id): Gets department by id. :param department_id: Id of the department being fetched. On success returns department data. On fai... | Implement the Python class `Department` described below.
Class description:
Rest class with methods GET, PUT, DELETE department.
Method signatures and docstrings:
- def get(self, department_id): Gets department by id. :param department_id: Id of the department being fetched. On success returns department data. On fai... | 45239501036921577e823e42959d2fa70e307f49 | <|skeleton|>
class Department:
"""Rest class with methods GET, PUT, DELETE department."""
def get(self, department_id):
"""Gets department by id. :param department_id: Id of the department being fetched. On success returns department data. On failure returns the status code 404. :rtype json"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Department:
"""Rest class with methods GET, PUT, DELETE department."""
def get(self, department_id):
"""Gets department by id. :param department_id: Id of the department being fetched. On success returns department data. On failure returns the status code 404. :rtype json"""
department = ... | the_stack_v2_python_sparse | department_app/rest/department.py | eewig/department_app | train | 0 |
bd06bad255a2b08ec7786dc1613d94c7874d2793 | [
"self._episode_length = episode_length\nself._use_actions_for_distance = use_actions_for_distance\nself._vectorized_demonstrations = self._vectorize(demonstrations_it)\natom_dims = self._vectorized_demonstrations.shape[1]\nself._reward_sigma = beta * self._episode_length / np.sqrt(atom_dims)\nself._reward_scale = a... | <|body_start_0|>
self._episode_length = episode_length
self._use_actions_for_distance = use_actions_for_distance
self._vectorized_demonstrations = self._vectorize(demonstrations_it)
atom_dims = self._vectorized_demonstrations.shape[1]
self._reward_sigma = beta * self._episode_len... | Computes PWIL rewards along a trajectory. The rewards measure similarity to the demonstration transitions and are based on a greedy approximation to the Wasserstein distance between trajectories. | WassersteinDistanceRewarder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WassersteinDistanceRewarder:
"""Computes PWIL rewards along a trajectory. The rewards measure similarity to the demonstration transitions and are based on a greedy approximation to the Wasserstein distance between trajectories."""
def __init__(self, demonstrations_it: Iterator[types.Transiti... | stack_v2_sparse_classes_36k_train_004205 | 6,140 | permissive | [
{
"docstring": "Initializes the rewarder. Args: demonstrations_it: An iterator over acme.types.Transition. episode_length: a target episode length (policies will be encouraged by the imitation reward to have that length). use_actions_for_distance: whether to use action to compute reward. alpha: float scaling th... | 4 | stack_v2_sparse_classes_30k_train_001527 | Implement the Python class `WassersteinDistanceRewarder` described below.
Class description:
Computes PWIL rewards along a trajectory. The rewards measure similarity to the demonstration transitions and are based on a greedy approximation to the Wasserstein distance between trajectories.
Method signatures and docstri... | Implement the Python class `WassersteinDistanceRewarder` described below.
Class description:
Computes PWIL rewards along a trajectory. The rewards measure similarity to the demonstration transitions and are based on a greedy approximation to the Wasserstein distance between trajectories.
Method signatures and docstri... | 97c50eaa62c039d8f4b9efa3e80c4d80e6f40c4c | <|skeleton|>
class WassersteinDistanceRewarder:
"""Computes PWIL rewards along a trajectory. The rewards measure similarity to the demonstration transitions and are based on a greedy approximation to the Wasserstein distance between trajectories."""
def __init__(self, demonstrations_it: Iterator[types.Transiti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WassersteinDistanceRewarder:
"""Computes PWIL rewards along a trajectory. The rewards measure similarity to the demonstration transitions and are based on a greedy approximation to the Wasserstein distance between trajectories."""
def __init__(self, demonstrations_it: Iterator[types.Transition], episode_... | the_stack_v2_python_sparse | acme/agents/jax/pwil/rewarder.py | RaoulDrake/acme | train | 0 |
fd176af4e044d456229c045478e012a5c20eb654 | [
"url = base_url.format(query)\nasync with ctx.bot.session.request('GET', url, headers=HEADERS) as response:\n if response.status == 200:\n data = await response.text()\n soup = BeautifulSoup(data)\n if base_url == BASE_URL_GOOGLE:\n links = soup.find_all('cite', class_='_Rm')\n ... | <|body_start_0|>
url = base_url.format(query)
async with ctx.bot.session.request('GET', url, headers=HEADERS) as response:
if response.status == 200:
data = await response.text()
soup = BeautifulSoup(data)
if base_url == BASE_URL_GOOGLE:
... | Google | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Google:
async def _google(self, ctx, *, query: str, base_url=BASE_URL_GOOGLE):
"""Helper function for Google. * query - The search query desired. * base_url - The Google base URL we want."""
<|body_0|>
async def google(self, ctx, *, query: str):
"""Search Google. Opt... | stack_v2_sparse_classes_36k_train_004206 | 4,909 | permissive | [
{
"docstring": "Helper function for Google. * query - The search query desired. * base_url - The Google base URL we want.",
"name": "_google",
"signature": "async def _google(self, ctx, *, query: str, base_url=BASE_URL_GOOGLE)"
},
{
"docstring": "Search Google. Optional image argument. Example q... | 5 | stack_v2_sparse_classes_30k_val_000517 | Implement the Python class `Google` described below.
Class description:
Implement the Google class.
Method signatures and docstrings:
- async def _google(self, ctx, *, query: str, base_url=BASE_URL_GOOGLE): Helper function for Google. * query - The search query desired. * base_url - The Google base URL we want.
- asy... | Implement the Python class `Google` described below.
Class description:
Implement the Google class.
Method signatures and docstrings:
- async def _google(self, ctx, *, query: str, base_url=BASE_URL_GOOGLE): Helper function for Google. * query - The search query desired. * base_url - The Google base URL we want.
- asy... | 3a456ad06814181d13d4aabefc151756c55444f4 | <|skeleton|>
class Google:
async def _google(self, ctx, *, query: str, base_url=BASE_URL_GOOGLE):
"""Helper function for Google. * query - The search query desired. * base_url - The Google base URL we want."""
<|body_0|>
async def google(self, ctx, *, query: str):
"""Search Google. Opt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Google:
async def _google(self, ctx, *, query: str, base_url=BASE_URL_GOOGLE):
"""Helper function for Google. * query - The search query desired. * base_url - The Google base URL we want."""
url = base_url.format(query)
async with ctx.bot.session.request('GET', url, headers=HEADERS) as... | the_stack_v2_python_sparse | cogs/google.py | sokcheng/Kitsuchan-NG | train | 1 | |
70cd8bfedc35afc1d79db5e2748d10e634c70261 | [
"if self.get_argument('type', None) == 'city':\n ret = {'status': True, 'rows': [], 'summary': ''}\n try:\n city_id = self.get_argument('city_id', None)\n if not city_id:\n ret['summary'] = '请指定市ID'\n ret['status'] = False\n else:\n region_service = Region... | <|body_start_0|>
if self.get_argument('type', None) == 'city':
ret = {'status': True, 'rows': [], 'summary': ''}
try:
city_id = self.get_argument('city_id', None)
if not city_id:
ret['summary'] = '请指定市ID'
ret['status... | CountyHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CountyHandler:
def get(self, *args, **kwargs):
"""获取 :param args: :param kwargs: :return:"""
<|body_0|>
def post(self, *args, **kwargs):
"""添加 :param args: :param kwargs: :return:"""
<|body_1|>
def put(self, *args, **kwargs):
"""更新 :param args: :... | stack_v2_sparse_classes_36k_train_004207 | 13,334 | no_license | [
{
"docstring": "获取 :param args: :param kwargs: :return:",
"name": "get",
"signature": "def get(self, *args, **kwargs)"
},
{
"docstring": "添加 :param args: :param kwargs: :return:",
"name": "post",
"signature": "def post(self, *args, **kwargs)"
},
{
"docstring": "更新 :param args: :p... | 4 | stack_v2_sparse_classes_30k_train_006389 | Implement the Python class `CountyHandler` described below.
Class description:
Implement the CountyHandler class.
Method signatures and docstrings:
- def get(self, *args, **kwargs): 获取 :param args: :param kwargs: :return:
- def post(self, *args, **kwargs): 添加 :param args: :param kwargs: :return:
- def put(self, *args... | Implement the Python class `CountyHandler` described below.
Class description:
Implement the CountyHandler class.
Method signatures and docstrings:
- def get(self, *args, **kwargs): 获取 :param args: :param kwargs: :return:
- def post(self, *args, **kwargs): 添加 :param args: :param kwargs: :return:
- def put(self, *args... | 0056d8edb9b8912e28b0332b3202e8a8d50f7157 | <|skeleton|>
class CountyHandler:
def get(self, *args, **kwargs):
"""获取 :param args: :param kwargs: :return:"""
<|body_0|>
def post(self, *args, **kwargs):
"""添加 :param args: :param kwargs: :return:"""
<|body_1|>
def put(self, *args, **kwargs):
"""更新 :param args: :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CountyHandler:
def get(self, *args, **kwargs):
"""获取 :param args: :param kwargs: :return:"""
if self.get_argument('type', None) == 'city':
ret = {'status': True, 'rows': [], 'summary': ''}
try:
city_id = self.get_argument('city_id', None)
... | the_stack_v2_python_sparse | UIAdmin/Controllers/Region.py | kevin-light/Jd-shop | train | 0 | |
8ee134eb1a352e68769346f3324b5c772d69229c | [
"new = sorted(nums)\nl, r = (0, len(nums) - 1)\nwhile l < r and nums[l] == new[l]:\n l += 1\nwhile l < r and nums[r] == new[r]:\n r -= 1\nreturn r - l + 1 if r > l else 0",
"l, r = (0, len(nums) - 1)\nwhile l < r and nums[l] <= nums[l + 1]:\n l += 1\nwhile l < r and nums[r] >= nums[r - 1]:\n r -= 1\ni... | <|body_start_0|>
new = sorted(nums)
l, r = (0, len(nums) - 1)
while l < r and nums[l] == new[l]:
l += 1
while l < r and nums[r] == new[r]:
r -= 1
return r - l + 1 if r > l else 0
<|end_body_0|>
<|body_start_1|>
l, r = (0, len(nums) - 1)
wh... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findUnsortedSubarray1(self, nums: List[int]) -> int:
"""原数组排序再比较,求出左右两边不满足要求的索引"""
<|body_0|>
def findUnsortedSubarray2(self, nums: List[int]) -> int:
"""1.从数组两端遍历找破坏升序顺序的索引,从而确定需要无序的连续子数组 2.在无序子数组中找出最大值和最小值 3.再次从两端遍历,找出最大值和最小值正确的索引,两者之差即为最短无序子数组"""
... | stack_v2_sparse_classes_36k_train_004208 | 1,656 | no_license | [
{
"docstring": "原数组排序再比较,求出左右两边不满足要求的索引",
"name": "findUnsortedSubarray1",
"signature": "def findUnsortedSubarray1(self, nums: List[int]) -> int"
},
{
"docstring": "1.从数组两端遍历找破坏升序顺序的索引,从而确定需要无序的连续子数组 2.在无序子数组中找出最大值和最小值 3.再次从两端遍历,找出最大值和最小值正确的索引,两者之差即为最短无序子数组",
"name": "findUnsortedSubarray2",... | 2 | stack_v2_sparse_classes_30k_train_017336 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findUnsortedSubarray1(self, nums: List[int]) -> int: 原数组排序再比较,求出左右两边不满足要求的索引
- def findUnsortedSubarray2(self, nums: List[int]) -> int: 1.从数组两端遍历找破坏升序顺序的索引,从而确定需要无序的连续子数组 2.在... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findUnsortedSubarray1(self, nums: List[int]) -> int: 原数组排序再比较,求出左右两边不满足要求的索引
- def findUnsortedSubarray2(self, nums: List[int]) -> int: 1.从数组两端遍历找破坏升序顺序的索引,从而确定需要无序的连续子数组 2.在... | 2bbb1640589aab34f2bc42489283033cc11fb885 | <|skeleton|>
class Solution:
def findUnsortedSubarray1(self, nums: List[int]) -> int:
"""原数组排序再比较,求出左右两边不满足要求的索引"""
<|body_0|>
def findUnsortedSubarray2(self, nums: List[int]) -> int:
"""1.从数组两端遍历找破坏升序顺序的索引,从而确定需要无序的连续子数组 2.在无序子数组中找出最大值和最小值 3.再次从两端遍历,找出最大值和最小值正确的索引,两者之差即为最短无序子数组"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findUnsortedSubarray1(self, nums: List[int]) -> int:
"""原数组排序再比较,求出左右两边不满足要求的索引"""
new = sorted(nums)
l, r = (0, len(nums) - 1)
while l < r and nums[l] == new[l]:
l += 1
while l < r and nums[r] == new[r]:
r -= 1
return r - l... | the_stack_v2_python_sparse | 581_shortest-unsorted-continuous-subarray.py | helloocc/algorithm | train | 1 | |
86eb73238503a9b1b4eecc65776c8dc0a9c9a2b7 | [
"self.active_opens = active_opens\nself.client_ip = client_ip\nself.domain = domain\nself.server_ip = server_ip\nself.session_id = session_id\nself.username = username",
"if dictionary is None:\n return None\nactive_opens = None\nif dictionary.get('activeOpens') != None:\n active_opens = list()\n for str... | <|body_start_0|>
self.active_opens = active_opens
self.client_ip = client_ip
self.domain = domain
self.server_ip = server_ip
self.session_id = session_id
self.username = username
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
... | Implementation of the 'SmbActiveSession' model. Specifies an active session and its opens. Attributes: active_opens (list of SmbActiveOpen): Specifies the list of active opens of the file in this session. client_ip (string): Specifies the IP address from which the file is still open. domain (string): Specifies the doma... | SmbActiveSession | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SmbActiveSession:
"""Implementation of the 'SmbActiveSession' model. Specifies an active session and its opens. Attributes: active_opens (list of SmbActiveOpen): Specifies the list of active opens of the file in this session. client_ip (string): Specifies the IP address from which the file is sti... | stack_v2_sparse_classes_36k_train_004209 | 2,939 | permissive | [
{
"docstring": "Constructor for the SmbActiveSession class",
"name": "__init__",
"signature": "def __init__(self, active_opens=None, client_ip=None, domain=None, server_ip=None, session_id=None, username=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictiona... | 2 | stack_v2_sparse_classes_30k_train_000256 | Implement the Python class `SmbActiveSession` described below.
Class description:
Implementation of the 'SmbActiveSession' model. Specifies an active session and its opens. Attributes: active_opens (list of SmbActiveOpen): Specifies the list of active opens of the file in this session. client_ip (string): Specifies th... | Implement the Python class `SmbActiveSession` described below.
Class description:
Implementation of the 'SmbActiveSession' model. Specifies an active session and its opens. Attributes: active_opens (list of SmbActiveOpen): Specifies the list of active opens of the file in this session. client_ip (string): Specifies th... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class SmbActiveSession:
"""Implementation of the 'SmbActiveSession' model. Specifies an active session and its opens. Attributes: active_opens (list of SmbActiveOpen): Specifies the list of active opens of the file in this session. client_ip (string): Specifies the IP address from which the file is sti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SmbActiveSession:
"""Implementation of the 'SmbActiveSession' model. Specifies an active session and its opens. Attributes: active_opens (list of SmbActiveOpen): Specifies the list of active opens of the file in this session. client_ip (string): Specifies the IP address from which the file is still open. doma... | the_stack_v2_python_sparse | cohesity_management_sdk/models/smb_active_session.py | cohesity/management-sdk-python | train | 24 |
3dfc79de16b0f3694142bda4657dff716ae1ecb1 | [
"if category == Category.Discovery and len(components) == 0:\n pass\nelif category == Category.Logs and len(components) == 0:\n log = factory.create(ComponentDescriptor(Category.Logs, None, 'null', None))\n log.configure(ComponentConfig())\n components.append(log)\nelif category == Category.Counters and... | <|body_start_0|>
if category == Category.Discovery and len(components) == 0:
pass
elif category == Category.Logs and len(components) == 0:
log = factory.create(ComponentDescriptor(Category.Logs, None, 'null', None))
log.configure(ComponentConfig())
compone... | Builds microservice components using configuration as a build recipe. | Builder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Builder:
"""Builds microservice components using configuration as a build recipe."""
def _build_section_defaults(factory, category, components):
"""Builds default components for specified configuration section. Args: factory: ComponentFactory that creates component instances. categor... | stack_v2_sparse_classes_36k_train_004210 | 5,133 | permissive | [
{
"docstring": "Builds default components for specified configuration section. Args: factory: ComponentFactory that creates component instances. category: a name of the section inside configuration. components: IComponent list with section components Returns: IComponent list with section components for chaining... | 3 | stack_v2_sparse_classes_30k_train_008781 | Implement the Python class `Builder` described below.
Class description:
Builds microservice components using configuration as a build recipe.
Method signatures and docstrings:
- def _build_section_defaults(factory, category, components): Builds default components for specified configuration section. Args: factory: C... | Implement the Python class `Builder` described below.
Class description:
Builds microservice components using configuration as a build recipe.
Method signatures and docstrings:
- def _build_section_defaults(factory, category, components): Builds default components for specified configuration section. Args: factory: C... | 70eca1ffc44bfdc45c9c65b0ee347fa578368849 | <|skeleton|>
class Builder:
"""Builds microservice components using configuration as a build recipe."""
def _build_section_defaults(factory, category, components):
"""Builds default components for specified configuration section. Args: factory: ComponentFactory that creates component instances. categor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Builder:
"""Builds microservice components using configuration as a build recipe."""
def _build_section_defaults(factory, category, components):
"""Builds default components for specified configuration section. Args: factory: ComponentFactory that creates component instances. category: a name of ... | the_stack_v2_python_sparse | pip_services_runtime/build/Builder.py | pip-services-archive/pip-services-runtime-python | train | 0 |
46d07e2d02b0f1f3caec381051a04537d03b5a00 | [
"modForTypeDict = Effectiveness.modByType[attackType]\nif pokeType in modForTypeDict:\n return modForTypeDict[pokeType]\nelse:\n return 1",
"mod = 1\nif not attackType == '':\n for type in target.getTypes():\n mod = mod * Effectiveness.getMod(attackType, type)\nreturn (mod, Effectiveness.respond(m... | <|body_start_0|>
modForTypeDict = Effectiveness.modByType[attackType]
if pokeType in modForTypeDict:
return modForTypeDict[pokeType]
else:
return 1
<|end_body_0|>
<|body_start_1|>
mod = 1
if not attackType == '':
for type in target.getTypes():... | Used to get effectiveness of attacks based on TYPE | Effectiveness | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Effectiveness:
"""Used to get effectiveness of attacks based on TYPE"""
def getMod(attackType, pokeType):
"""Returns the modifier bonus of the Effectiveness of an attack against a Pokemon's Type"""
<|body_0|>
def getEffectiveness(attackType, target):
"""Returns t... | stack_v2_sparse_classes_36k_train_004211 | 3,718 | no_license | [
{
"docstring": "Returns the modifier bonus of the Effectiveness of an attack against a Pokemon's Type",
"name": "getMod",
"signature": "def getMod(attackType, pokeType)"
},
{
"docstring": "Returns the effectiveness of an attack against a pokemon",
"name": "getEffectiveness",
"signature":... | 3 | stack_v2_sparse_classes_30k_train_006976 | Implement the Python class `Effectiveness` described below.
Class description:
Used to get effectiveness of attacks based on TYPE
Method signatures and docstrings:
- def getMod(attackType, pokeType): Returns the modifier bonus of the Effectiveness of an attack against a Pokemon's Type
- def getEffectiveness(attackTyp... | Implement the Python class `Effectiveness` described below.
Class description:
Used to get effectiveness of attacks based on TYPE
Method signatures and docstrings:
- def getMod(attackType, pokeType): Returns the modifier bonus of the Effectiveness of an attack against a Pokemon's Type
- def getEffectiveness(attackTyp... | 3931eee5fd04e18bb1738a0b27a4c6979dc4db01 | <|skeleton|>
class Effectiveness:
"""Used to get effectiveness of attacks based on TYPE"""
def getMod(attackType, pokeType):
"""Returns the modifier bonus of the Effectiveness of an attack against a Pokemon's Type"""
<|body_0|>
def getEffectiveness(attackType, target):
"""Returns t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Effectiveness:
"""Used to get effectiveness of attacks based on TYPE"""
def getMod(attackType, pokeType):
"""Returns the modifier bonus of the Effectiveness of an attack against a Pokemon's Type"""
modForTypeDict = Effectiveness.modByType[attackType]
if pokeType in modForTypeDict:... | the_stack_v2_python_sparse | src/Battle/Attack/DamageDelegates/effectiveness.py | sgtnourry/Pokemon-Project | train | 0 |
2cdf1cd40eb37da4cb5e9849beaabb1f2a35ea32 | [
"if max_subspace <= 2 or max_iterations <= 0 or eps <= 0:\n raise ValueError('Invalid values for max_subspace, max_iterations and/ or eps: ({}, {}, {}).'.format(max_subspace, max_iterations, eps))\nself.max_subspace = max_subspace\nself.max_iterations = max_iterations\nself.eps = eps\nself.real_only = real_only"... | <|body_start_0|>
if max_subspace <= 2 or max_iterations <= 0 or eps <= 0:
raise ValueError('Invalid values for max_subspace, max_iterations and/ or eps: ({}, {}, {}).'.format(max_subspace, max_iterations, eps))
self.max_subspace = max_subspace
self.max_iterations = max_iterations
... | Davidson algorithm iteration options. | DavidsonOptions | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DavidsonOptions:
"""Davidson algorithm iteration options."""
def __init__(self, max_subspace=100, max_iterations=300, eps=1e-06, real_only=False):
"""Args: max_subspace(int): Max number of vectors in the auxiliary subspace. max_iterations(int): Max number of iterations. eps(float): T... | stack_v2_sparse_classes_36k_train_004212 | 19,388 | permissive | [
{
"docstring": "Args: max_subspace(int): Max number of vectors in the auxiliary subspace. max_iterations(int): Max number of iterations. eps(float): The max error for eigen vector error's elements during iterations: linear_operator * v - v * lambda. real_only(bool): Desired eigenvectors are real only or not. Wh... | 2 | null | Implement the Python class `DavidsonOptions` described below.
Class description:
Davidson algorithm iteration options.
Method signatures and docstrings:
- def __init__(self, max_subspace=100, max_iterations=300, eps=1e-06, real_only=False): Args: max_subspace(int): Max number of vectors in the auxiliary subspace. max... | Implement the Python class `DavidsonOptions` described below.
Class description:
Davidson algorithm iteration options.
Method signatures and docstrings:
- def __init__(self, max_subspace=100, max_iterations=300, eps=1e-06, real_only=False): Args: max_subspace(int): Max number of vectors in the auxiliary subspace. max... | 788481753c798a72c5cb3aa9f2aa9da3ce3190b0 | <|skeleton|>
class DavidsonOptions:
"""Davidson algorithm iteration options."""
def __init__(self, max_subspace=100, max_iterations=300, eps=1e-06, real_only=False):
"""Args: max_subspace(int): Max number of vectors in the auxiliary subspace. max_iterations(int): Max number of iterations. eps(float): T... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DavidsonOptions:
"""Davidson algorithm iteration options."""
def __init__(self, max_subspace=100, max_iterations=300, eps=1e-06, real_only=False):
"""Args: max_subspace(int): Max number of vectors in the auxiliary subspace. max_iterations(int): Max number of iterations. eps(float): The max error ... | the_stack_v2_python_sparse | src/openfermion/linalg/davidson.py | quantumlib/OpenFermion | train | 1,481 |
19874c8ae19451bcdb278a9995044b10bce95a50 | [
"if (sha_arg := f.request.args.get('sha')):\n shas = sha_arg.split(',')\n runs = Run.search(filters=[Commit.sha.in_(shas)], joins=[Commit])\nelse:\n runs = Run.all(order_by=Run.timestamp.desc(), limit=1000)\nreturn self.serializer.many.dump(runs)",
"data = self.validate(self.schema.create)\ntry:\n run... | <|body_start_0|>
if (sha_arg := f.request.args.get('sha')):
shas = sha_arg.split(',')
runs = Run.search(filters=[Commit.sha.in_(shas)], joins=[Commit])
else:
runs = Run.all(order_by=Run.timestamp.desc(), limit=1000)
return self.serializer.many.dump(runs)
<|end... | RunListAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunListAPI:
def get(self):
"""--- description: Get a list of runs. responses: "200": "RunList" "401": "401" parameters: - in: query name: sha schema: type: string tags: - Runs"""
<|body_0|>
def post(self):
"""--- description: Create a run. responses: "201": "RunCreat... | stack_v2_sparse_classes_36k_train_004213 | 5,918 | permissive | [
{
"docstring": "--- description: Get a list of runs. responses: \"200\": \"RunList\" \"401\": \"401\" parameters: - in: query name: sha schema: type: string tags: - Runs",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "--- description: Create a run. responses: \"201\": \"RunCreat... | 2 | null | Implement the Python class `RunListAPI` described below.
Class description:
Implement the RunListAPI class.
Method signatures and docstrings:
- def get(self): --- description: Get a list of runs. responses: "200": "RunList" "401": "401" parameters: - in: query name: sha schema: type: string tags: - Runs
- def post(se... | Implement the Python class `RunListAPI` described below.
Class description:
Implement the RunListAPI class.
Method signatures and docstrings:
- def get(self): --- description: Get a list of runs. responses: "200": "RunList" "401": "401" parameters: - in: query name: sha schema: type: string tags: - Runs
- def post(se... | 534762befe9429ae1080e42056e9c681afab9801 | <|skeleton|>
class RunListAPI:
def get(self):
"""--- description: Get a list of runs. responses: "200": "RunList" "401": "401" parameters: - in: query name: sha schema: type: string tags: - Runs"""
<|body_0|>
def post(self):
"""--- description: Create a run. responses: "201": "RunCreat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RunListAPI:
def get(self):
"""--- description: Get a list of runs. responses: "200": "RunList" "401": "401" parameters: - in: query name: sha schema: type: string tags: - Runs"""
if (sha_arg := f.request.args.get('sha')):
shas = sha_arg.split(',')
runs = Run.search(filt... | the_stack_v2_python_sparse | conbench/api/runs.py | conbench/conbench | train | 50 | |
7c8441d86da1cf129006a3190c237b99dd5a6af8 | [
"super(ProteinCNN, self).__init__()\nself.activation = get_activation_func(activation)\nself.pooling_dim = pooling_dim\nself.lin_kernels = nn.ModuleList([nn.Linear(dim * window, dim * window) for _ in range(num_layers - 1)])\nself.lin_kernels.append(nn.Linear(dim * window, dim))",
"for kernel in self.lin_kernels:... | <|body_start_0|>
super(ProteinCNN, self).__init__()
self.activation = get_activation_func(activation)
self.pooling_dim = pooling_dim
self.lin_kernels = nn.ModuleList([nn.Linear(dim * window, dim * window) for _ in range(num_layers - 1)])
self.lin_kernels.append(nn.Linear(dim * wi... | Implements Protein CNN without Attention | ProteinCNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProteinCNN:
"""Implements Protein CNN without Attention"""
def __init__(self, dim, window, activation='relu', num_layers=2, pooling_dim=1):
""":param dim: int final dimension of the protein representation :param activation: non-linearity to apply to logits :param window: max size of ... | stack_v2_sparse_classes_36k_train_004214 | 27,873 | permissive | [
{
"docstring": ":param dim: int final dimension of the protein representation :param activation: non-linearity to apply to logits :param window: max size of grouped amino acids :param num_layers: int Number of convolution layers :param pooling_dim: int The dimension to be used in reducing protein segments to fo... | 2 | stack_v2_sparse_classes_30k_train_016647 | Implement the Python class `ProteinCNN` described below.
Class description:
Implements Protein CNN without Attention
Method signatures and docstrings:
- def __init__(self, dim, window, activation='relu', num_layers=2, pooling_dim=1): :param dim: int final dimension of the protein representation :param activation: non... | Implement the Python class `ProteinCNN` described below.
Class description:
Implements Protein CNN without Attention
Method signatures and docstrings:
- def __init__(self, dim, window, activation='relu', num_layers=2, pooling_dim=1): :param dim: int final dimension of the protein representation :param activation: non... | f1ddd11fd769c782c354425967c3cc326b9adf69 | <|skeleton|>
class ProteinCNN:
"""Implements Protein CNN without Attention"""
def __init__(self, dim, window, activation='relu', num_layers=2, pooling_dim=1):
""":param dim: int final dimension of the protein representation :param activation: non-linearity to apply to logits :param window: max size of ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProteinCNN:
"""Implements Protein CNN without Attention"""
def __init__(self, dim, window, activation='relu', num_layers=2, pooling_dim=1):
""":param dim: int final dimension of the protein representation :param activation: non-linearity to apply to logits :param window: max size of grouped amino... | the_stack_v2_python_sparse | jova/nn/models.py | bbrighttaer/jova_baselines | train | 2 |
0bea501802bf0993d8f862c039540dd5739cd24e | [
"self.head = None\nself.current = None\nself.temp = None",
"n = Node(number)\nif self.head == None:\n self.head = n\n self.current = self.head\nelse:\n self.current.next = n\n self.current = n",
"self.temp = self.head\nwhile self.temp != None:\n print(self.temp.data, end=' ')\n self.temp = sel... | <|body_start_0|>
self.head = None
self.current = None
self.temp = None
<|end_body_0|>
<|body_start_1|>
n = Node(number)
if self.head == None:
self.head = n
self.current = self.head
else:
self.current.next = n
self.current =... | This class contains all basic operations on linked list. For all further examples (1 - 23) this class will be extended in respective files. Attributes: head (Node) : Stores start of linked list. current (Node) : Stores last node added to linked list for easier insertion. temp (Node) : Temporary Reference can be used fo... | SLL | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SLL:
"""This class contains all basic operations on linked list. For all further examples (1 - 23) this class will be extended in respective files. Attributes: head (Node) : Stores start of linked list. current (Node) : Stores last node added to linked list for easier insertion. temp (Node) : Tem... | stack_v2_sparse_classes_36k_train_004215 | 2,091 | no_license | [
{
"docstring": "Costructor sets all the class members to None.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts new node to the linked list. Parameters: number (int) : Number to append to the linked list.",
"name": "insert",
"signature": "def insert(self... | 3 | stack_v2_sparse_classes_30k_train_014615 | Implement the Python class `SLL` described below.
Class description:
This class contains all basic operations on linked list. For all further examples (1 - 23) this class will be extended in respective files. Attributes: head (Node) : Stores start of linked list. current (Node) : Stores last node added to linked list ... | Implement the Python class `SLL` described below.
Class description:
This class contains all basic operations on linked list. For all further examples (1 - 23) this class will be extended in respective files. Attributes: head (Node) : Stores start of linked list. current (Node) : Stores last node added to linked list ... | 708431a78caf8d07c4f334f2ad91379a0de70868 | <|skeleton|>
class SLL:
"""This class contains all basic operations on linked list. For all further examples (1 - 23) this class will be extended in respective files. Attributes: head (Node) : Stores start of linked list. current (Node) : Stores last node added to linked list for easier insertion. temp (Node) : Tem... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SLL:
"""This class contains all basic operations on linked list. For all further examples (1 - 23) this class will be extended in respective files. Attributes: head (Node) : Stores start of linked list. current (Node) : Stores last node added to linked list for easier insertion. temp (Node) : Temporary Refere... | the_stack_v2_python_sparse | Python/SLL.py | paramSonawane/99Problems | train | 0 |
e7337b6e9dd27871838fb0bbd4b022abd2804d1c | [
"self.model_conf = model_conf\nself.inputs = inputs\nself.utils = utils\nself.layer = None",
"with tf.keras.backend.name_scope('LSTM'):\n self.layer = tf.keras.layers.CuDNNLSTM(units=self.model_conf.units_num * 2, return_sequences=True)\n outputs = self.layer(self.inputs, training=self.utils.is_training)\nr... | <|body_start_0|>
self.model_conf = model_conf
self.inputs = inputs
self.utils = utils
self.layer = None
<|end_body_0|>
<|body_start_1|>
with tf.keras.backend.name_scope('LSTM'):
self.layer = tf.keras.layers.CuDNNLSTM(units=self.model_conf.units_num * 2, return_sequen... | LSTMcuDNN | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LSTMcuDNN:
def __init__(self, model_conf: ModelConfig, inputs: tf.Tensor, utils: NetworkUtils):
"""同上"""
<|body_0|>
def build(self):
"""同上"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.model_conf = model_conf
self.inputs = inputs
... | stack_v2_sparse_classes_36k_train_004216 | 3,290 | permissive | [
{
"docstring": "同上",
"name": "__init__",
"signature": "def __init__(self, model_conf: ModelConfig, inputs: tf.Tensor, utils: NetworkUtils)"
},
{
"docstring": "同上",
"name": "build",
"signature": "def build(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_001098 | Implement the Python class `LSTMcuDNN` described below.
Class description:
Implement the LSTMcuDNN class.
Method signatures and docstrings:
- def __init__(self, model_conf: ModelConfig, inputs: tf.Tensor, utils: NetworkUtils): 同上
- def build(self): 同上 | Implement the Python class `LSTMcuDNN` described below.
Class description:
Implement the LSTMcuDNN class.
Method signatures and docstrings:
- def __init__(self, model_conf: ModelConfig, inputs: tf.Tensor, utils: NetworkUtils): 同上
- def build(self): 同上
<|skeleton|>
class LSTMcuDNN:
def __init__(self, model_conf:... | 6fd35c0c789aaa43130de46d4c04622ec2948052 | <|skeleton|>
class LSTMcuDNN:
def __init__(self, model_conf: ModelConfig, inputs: tf.Tensor, utils: NetworkUtils):
"""同上"""
<|body_0|>
def build(self):
"""同上"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LSTMcuDNN:
def __init__(self, model_conf: ModelConfig, inputs: tf.Tensor, utils: NetworkUtils):
"""同上"""
self.model_conf = model_conf
self.inputs = inputs
self.utils = utils
self.layer = None
def build(self):
"""同上"""
with tf.keras.backend.name_scop... | the_stack_v2_python_sparse | network/LSTM.py | kerlomz/captcha_trainer | train | 2,977 | |
d5a107d3f06b0f0ed33cda4810e159f50dcdee47 | [
"self.query_data = RequestData(request, is_query=True)\nself.shift_data = RequestData(request, is_query=False)\nself.query_data_fields = self.query_data.getlist('_fields')\nsuper(SVMixin, self).initial(request, *args, **kwargs)",
"serializer_class = self.get_serializer_class()\ncontext = self.get_serializer_conte... | <|body_start_0|>
self.query_data = RequestData(request, is_query=True)
self.shift_data = RequestData(request, is_query=False)
self.query_data_fields = self.query_data.getlist('_fields')
super(SVMixin, self).initial(request, *args, **kwargs)
<|end_body_0|>
<|body_start_1|>
serial... | 项目viewset公共继承类, 添加了请求字段过滤,合法数据过滤功能 | SVMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SVMixin:
"""项目viewset公共继承类, 添加了请求字段过滤,合法数据过滤功能"""
def initial(self, request, *args, **kwargs):
"""初始化viewset request :param request: 请求对象 :param args: 其他参数 :param kwargs: 其他参数"""
<|body_0|>
def get_serializer(self, *args, **kwargs):
"""获取rest序列化数据对象 :param args: ... | stack_v2_sparse_classes_36k_train_004217 | 11,301 | no_license | [
{
"docstring": "初始化viewset request :param request: 请求对象 :param args: 其他参数 :param kwargs: 其他参数",
"name": "initial",
"signature": "def initial(self, request, *args, **kwargs)"
},
{
"docstring": "获取rest序列化数据对象 :param args: 其他参数 :param kwargs: 其他参数 :return: rest序列化数据对象",
"name": "get_serializer"... | 2 | stack_v2_sparse_classes_30k_train_000642 | Implement the Python class `SVMixin` described below.
Class description:
项目viewset公共继承类, 添加了请求字段过滤,合法数据过滤功能
Method signatures and docstrings:
- def initial(self, request, *args, **kwargs): 初始化viewset request :param request: 请求对象 :param args: 其他参数 :param kwargs: 其他参数
- def get_serializer(self, *args, **kwargs): 获取rest... | Implement the Python class `SVMixin` described below.
Class description:
项目viewset公共继承类, 添加了请求字段过滤,合法数据过滤功能
Method signatures and docstrings:
- def initial(self, request, *args, **kwargs): 初始化viewset request :param request: 请求对象 :param args: 其他参数 :param kwargs: 其他参数
- def get_serializer(self, *args, **kwargs): 获取rest... | a4502d14652c6a926e74be6d0f53b2b50ada9c3c | <|skeleton|>
class SVMixin:
"""项目viewset公共继承类, 添加了请求字段过滤,合法数据过滤功能"""
def initial(self, request, *args, **kwargs):
"""初始化viewset request :param request: 请求对象 :param args: 其他参数 :param kwargs: 其他参数"""
<|body_0|>
def get_serializer(self, *args, **kwargs):
"""获取rest序列化数据对象 :param args: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SVMixin:
"""项目viewset公共继承类, 添加了请求字段过滤,合法数据过滤功能"""
def initial(self, request, *args, **kwargs):
"""初始化viewset request :param request: 请求对象 :param args: 其他参数 :param kwargs: 其他参数"""
self.query_data = RequestData(request, is_query=True)
self.shift_data = RequestData(request, is_query=... | the_stack_v2_python_sparse | sv/sv_base/extensions/rest/mixins.py | xianzhishenqie/project_template | train | 1 |
0988a6e211cfd507eaa61f54490f69a41abb7fb7 | [
"children = self.children\ninner = [e for e in children if e.tag != 'office:change-info']\nif no_header:\n new_inner = []\n for element in inner:\n if element.tag == 'text:h':\n children = element.children\n text = element.text\n para = Element.from_tag('text:p')\n ... | <|body_start_0|>
children = self.children
inner = [e for e in children if e.tag != 'office:change-info']
if no_header:
new_inner = []
for element in inner:
if element.tag == 'text:h':
children = element.children
text... | The TextDeletion "text:deletion" contains information that identifies the person responsible for a deletion and the date of that deletion. This information may also contain one or more Paragraph which contains a comment on the deletion. The TextDeletion element may also contain content that was deleted while change tra... | TextDeletion | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextDeletion:
"""The TextDeletion "text:deletion" contains information that identifies the person responsible for a deletion and the date of that deletion. This information may also contain one or more Paragraph which contains a comment on the deletion. The TextDeletion element may also contain c... | stack_v2_sparse_classes_36k_train_004218 | 21,593 | permissive | [
{
"docstring": "Get the deleted informations stored in the TextDeletion. If as_text is True: returns the text content. If no_header is True: existing Heading are changed in Paragraph Arguments: as_text -- boolean no_header -- boolean Return: Paragraph and Header list",
"name": "get_deleted",
"signature"... | 3 | null | Implement the Python class `TextDeletion` described below.
Class description:
The TextDeletion "text:deletion" contains information that identifies the person responsible for a deletion and the date of that deletion. This information may also contain one or more Paragraph which contains a comment on the deletion. The ... | Implement the Python class `TextDeletion` described below.
Class description:
The TextDeletion "text:deletion" contains information that identifies the person responsible for a deletion and the date of that deletion. This information may also contain one or more Paragraph which contains a comment on the deletion. The ... | 41554a07965af70cacc023a9a0a73c25b42d25a2 | <|skeleton|>
class TextDeletion:
"""The TextDeletion "text:deletion" contains information that identifies the person responsible for a deletion and the date of that deletion. This information may also contain one or more Paragraph which contains a comment on the deletion. The TextDeletion element may also contain c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TextDeletion:
"""The TextDeletion "text:deletion" contains information that identifies the person responsible for a deletion and the date of that deletion. This information may also contain one or more Paragraph which contains a comment on the deletion. The TextDeletion element may also contain content that w... | the_stack_v2_python_sparse | odfdo/tracked_changes.py | jdum/odfdo | train | 30 |
033bb7383df651ef12719da6fa9c1b1ed4c3cb70 | [
"self.mode = kwargs.pop('mode', 'markdown')\nself.addons = kwargs.pop('addons', [])\nself.theme = kwargs.pop('theme', 'default')\nself.theme_path = kwargs.pop('theme_path', 's_markdown/codemirror/theme/%s.css' % self.theme)\nself.keymap = kwargs.pop('keymap', None)\nself.options = kwargs.pop('options', {})\nself.ad... | <|body_start_0|>
self.mode = kwargs.pop('mode', 'markdown')
self.addons = kwargs.pop('addons', [])
self.theme = kwargs.pop('theme', 'default')
self.theme_path = kwargs.pop('theme_path', 's_markdown/codemirror/theme/%s.css' % self.theme)
self.keymap = kwargs.pop('keymap', None)
... | CodeMirror | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CodeMirror:
def __init__(self, *args, **kwargs):
"""Widget that uses the `CodeMirror` editor :param mode: Syntax mode name. :param addons: List of addons (each element is a relative path to the addon, without `.js` extension. Example: `mode/overlay`) :param theme: Theme name. :param them... | stack_v2_sparse_classes_36k_train_004219 | 3,381 | permissive | [
{
"docstring": "Widget that uses the `CodeMirror` editor :param mode: Syntax mode name. :param addons: List of addons (each element is a relative path to the addon, without `.js` extension. Example: `mode/overlay`) :param theme: Theme name. :param theme_path: Path to the theme file. Default is `s_markdown/codem... | 3 | stack_v2_sparse_classes_30k_train_013723 | Implement the Python class `CodeMirror` described below.
Class description:
Implement the CodeMirror class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Widget that uses the `CodeMirror` editor :param mode: Syntax mode name. :param addons: List of addons (each element is a relative path to... | Implement the Python class `CodeMirror` described below.
Class description:
Implement the CodeMirror class.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Widget that uses the `CodeMirror` editor :param mode: Syntax mode name. :param addons: List of addons (each element is a relative path to... | 9bf040faac43feae08b33900e30bf7d17b817ae4 | <|skeleton|>
class CodeMirror:
def __init__(self, *args, **kwargs):
"""Widget that uses the `CodeMirror` editor :param mode: Syntax mode name. :param addons: List of addons (each element is a relative path to the addon, without `.js` extension. Example: `mode/overlay`) :param theme: Theme name. :param them... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CodeMirror:
def __init__(self, *args, **kwargs):
"""Widget that uses the `CodeMirror` editor :param mode: Syntax mode name. :param addons: List of addons (each element is a relative path to the addon, without `.js` extension. Example: `mode/overlay`) :param theme: Theme name. :param theme_path: Path t... | the_stack_v2_python_sparse | s_markdown/widgets.py | AmatanHead/collective-blog | train | 0 | |
3ab424fb17684dd9da8400d1d75b742741a88a60 | [
"n, m = (n + m - 2, m - 1)\nS1 = 1\nfor i in range(n, n - m, -1):\n S1 *= i\nS2 = 1\nfor i in range(1, m + 1):\n S2 *= i\nreturn S1 // S2",
"P = [[0 for _ in range(n)] for _ in range(m)]\nfor i in range(m):\n P[i][0] = 1\nfor j in range(n):\n P[0][j] = 1\nfor i in range(1, m):\n for j in range(1, n... | <|body_start_0|>
n, m = (n + m - 2, m - 1)
S1 = 1
for i in range(n, n - m, -1):
S1 *= i
S2 = 1
for i in range(1, m + 1):
S2 *= i
return S1 // S2
<|end_body_0|>
<|body_start_1|>
P = [[0 for _ in range(n)] for _ in range(m)]
for i in... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
"""排列组合:C(m+n-1,m-1) :param m: :param n: :return:"""
<|body_0|>
def uniquePaths2(self, m: int, n: int) -> int:
"""动态规划 P(i,j)为到达(i,j)的最多路径走法 P(i,j)=P(i-1,j)+P(i,j-1) :param m: :param n: :return:"""
<|bod... | stack_v2_sparse_classes_36k_train_004220 | 1,770 | no_license | [
{
"docstring": "排列组合:C(m+n-1,m-1) :param m: :param n: :return:",
"name": "uniquePaths",
"signature": "def uniquePaths(self, m: int, n: int) -> int"
},
{
"docstring": "动态规划 P(i,j)为到达(i,j)的最多路径走法 P(i,j)=P(i-1,j)+P(i,j-1) :param m: :param n: :return:",
"name": "uniquePaths2",
"signature": "... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePaths(self, m: int, n: int) -> int: 排列组合:C(m+n-1,m-1) :param m: :param n: :return:
- def uniquePaths2(self, m: int, n: int) -> int: 动态规划 P(i,j)为到达(i,j)的最多路径走法 P(i,j)=P(... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePaths(self, m: int, n: int) -> int: 排列组合:C(m+n-1,m-1) :param m: :param n: :return:
- def uniquePaths2(self, m: int, n: int) -> int: 动态规划 P(i,j)为到达(i,j)的最多路径走法 P(i,j)=P(... | 837957ea22aa07ce28a6c23ea0419bd2011e1f88 | <|skeleton|>
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
"""排列组合:C(m+n-1,m-1) :param m: :param n: :return:"""
<|body_0|>
def uniquePaths2(self, m: int, n: int) -> int:
"""动态规划 P(i,j)为到达(i,j)的最多路径走法 P(i,j)=P(i-1,j)+P(i,j-1) :param m: :param n: :return:"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def uniquePaths(self, m: int, n: int) -> int:
"""排列组合:C(m+n-1,m-1) :param m: :param n: :return:"""
n, m = (n + m - 2, m - 1)
S1 = 1
for i in range(n, n - m, -1):
S1 *= i
S2 = 1
for i in range(1, m + 1):
S2 *= i
return S1... | the_stack_v2_python_sparse | 华为题库/不同路径.py | 2226171237/Algorithmpractice | train | 0 | |
8c3f1de78485545a004c062b585d964f85229e3f | [
"stack = []\ncount = 0\nstack.append((0, 0))\nwhile stack:\n popped = stack.pop()\n if popped == (m - 1, n - 1):\n count += 1\n row, col = popped\n if col < n:\n stack.append((row, col + 1))\n if row < m:\n stack.append((row + 1, col))\nreturn count",
"import math\nif m > n:\n ... | <|body_start_0|>
stack = []
count = 0
stack.append((0, 0))
while stack:
popped = stack.pop()
if popped == (m - 1, n - 1):
count += 1
row, col = popped
if col < n:
stack.append((row, col + 1))
if r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def uniquePaths(self, m, n):
"""DFS"""
<|body_0|>
def uniquePaths(self, m, n):
"""Math"""
<|body_1|>
def uniquePaths(self, m, n):
"""DP"""
<|body_2|>
def uniquePaths(self, m, n):
"""DP more optimized by init everyth... | stack_v2_sparse_classes_36k_train_004221 | 1,572 | no_license | [
{
"docstring": "DFS",
"name": "uniquePaths",
"signature": "def uniquePaths(self, m, n)"
},
{
"docstring": "Math",
"name": "uniquePaths",
"signature": "def uniquePaths(self, m, n)"
},
{
"docstring": "DP",
"name": "uniquePaths",
"signature": "def uniquePaths(self, m, n)"
... | 4 | stack_v2_sparse_classes_30k_train_011987 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePaths(self, m, n): DFS
- def uniquePaths(self, m, n): Math
- def uniquePaths(self, m, n): DP
- def uniquePaths(self, m, n): DP more optimized by init everything as 1 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePaths(self, m, n): DFS
- def uniquePaths(self, m, n): Math
- def uniquePaths(self, m, n): DP
- def uniquePaths(self, m, n): DP more optimized by init everything as 1
<... | 5714fdb2d8a89a68d68d07f7ffd3f6bcff5b2ccf | <|skeleton|>
class Solution:
def uniquePaths(self, m, n):
"""DFS"""
<|body_0|>
def uniquePaths(self, m, n):
"""Math"""
<|body_1|>
def uniquePaths(self, m, n):
"""DP"""
<|body_2|>
def uniquePaths(self, m, n):
"""DP more optimized by init everyth... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def uniquePaths(self, m, n):
"""DFS"""
stack = []
count = 0
stack.append((0, 0))
while stack:
popped = stack.pop()
if popped == (m - 1, n - 1):
count += 1
row, col = popped
if col < n:
... | the_stack_v2_python_sparse | Python/matrix/62_unique_path.py | 01-Jacky/PracticeProblems | train | 0 | |
4a09bdcdb775ad68af4537adcce2e2cc66a71e09 | [
"self.name = name\nself.rng = rng or random.Random()\nself.random_seed = random_seed",
"if self.random_seed is not None:\n flags_rng = random.Random(self.random_seed)\nelse:\n flags_rng = random.Random()\nextra_flags = []\nfor p, flag in ADDITIONAL_FLAGS:\n if flags_rng.random() < p:\n extra_flags... | <|body_start_0|>
self.name = name
self.rng = rng or random.Random()
self.random_seed = random_seed
<|end_body_0|>
<|body_start_1|>
if self.random_seed is not None:
flags_rng = random.Random(self.random_seed)
else:
flags_rng = random.Random()
extra... | Config | [
"bzip2-1.0.6",
"BSD-3-Clause",
"Apache-2.0",
"SunPro",
"ICU",
"Zlib",
"GPL-1.0-or-later",
"OpenSSL",
"ISC",
"LicenseRef-scancode-gutenberg-2020",
"MIT",
"GPL-2.0-only",
"CC0-1.0",
"BSL-1.0",
"LicenseRef-scancode-autoconf-simple-exception",
"LicenseRef-scancode-pcre",
"Bison-exception... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Config:
def __init__(self, name, rng=None, random_seed=None):
"""Args: name: Name of the used fuzzer. rng: Random number generator for generating experiments. random_seed: Random-seed used for d8 throughout one fuzz session. TODO(machenbach): Remove random_seed after a grace period of a ... | stack_v2_sparse_classes_36k_train_004222 | 3,487 | permissive | [
{
"docstring": "Args: name: Name of the used fuzzer. rng: Random number generator for generating experiments. random_seed: Random-seed used for d8 throughout one fuzz session. TODO(machenbach): Remove random_seed after a grace period of a couple of days. We only have it to keep bisection stable. Afterwards we c... | 2 | null | Implement the Python class `Config` described below.
Class description:
Implement the Config class.
Method signatures and docstrings:
- def __init__(self, name, rng=None, random_seed=None): Args: name: Name of the used fuzzer. rng: Random number generator for generating experiments. random_seed: Random-seed used for ... | Implement the Python class `Config` described below.
Class description:
Implement the Config class.
Method signatures and docstrings:
- def __init__(self, name, rng=None, random_seed=None): Args: name: Name of the used fuzzer. rng: Random number generator for generating experiments. random_seed: Random-seed used for ... | 43c40535cee37fc7349a21793dc33b1833735af5 | <|skeleton|>
class Config:
def __init__(self, name, rng=None, random_seed=None):
"""Args: name: Name of the used fuzzer. rng: Random number generator for generating experiments. random_seed: Random-seed used for d8 throughout one fuzz session. TODO(machenbach): Remove random_seed after a grace period of a ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Config:
def __init__(self, name, rng=None, random_seed=None):
"""Args: name: Name of the used fuzzer. rng: Random number generator for generating experiments. random_seed: Random-seed used for d8 throughout one fuzz session. TODO(machenbach): Remove random_seed after a grace period of a couple of days... | the_stack_v2_python_sparse | 3rdParty/V8/v7.9.317/tools/clusterfuzz/v8_fuzz_config.py | arangodb/arangodb | train | 13,385 | |
4902d6a177b39ddd30fe5d79329fee2b5ecc2c15 | [
"ans = []\nqueue = deque()\nif root == None:\n return ans\nqueue.append(root)\nwhile queue:\n for i in xrange(len(queue)):\n item = queue.popleft()\n if item.left:\n queue.append(item.left)\n if item.right:\n queue.append(item.right)\n ans.append(item.val)\n pr... | <|body_start_0|>
ans = []
queue = deque()
if root == None:
return ans
queue.append(root)
while queue:
for i in xrange(len(queue)):
item = queue.popleft()
if item.left:
queue.append(item.left)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rightSideView(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def rightSideView(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ans = []
queue = deque(... | stack_v2_sparse_classes_36k_train_004223 | 2,802 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "rightSideView",
"signature": "def rightSideView(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "rightSideView",
"signature": "def rightSideView(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rightSideView(self, root): :type root: TreeNode :rtype: List[int]
- def rightSideView(self, root): :type root: TreeNode :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rightSideView(self, root): :type root: TreeNode :rtype: List[int]
- def rightSideView(self, root): :type root: TreeNode :rtype: List[int]
<|skeleton|>
class Solution:
d... | 844f502da4d6fb9cd69cf0a1ef71da3385a4d2b4 | <|skeleton|>
class Solution:
def rightSideView(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def rightSideView(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rightSideView(self, root):
""":type root: TreeNode :rtype: List[int]"""
ans = []
queue = deque()
if root == None:
return ans
queue.append(root)
while queue:
for i in xrange(len(queue)):
item = queue.popleft()... | the_stack_v2_python_sparse | 199-binary_tree_right_side_view.py | stevestar888/leetcode-problems | train | 2 | |
7da174af6f0d3efd45785c0ccb36cc3aff06fdf9 | [
"self.datastore_id = datastore_id\nself.datastore_name = datastore_name\nself.throttling_policy = throttling_policy",
"if dictionary is None:\n return None\ndatastore_id = dictionary.get('datastoreId')\ndatastore_name = dictionary.get('datastoreName')\nthrottling_policy = cohesity_management_sdk.models.throttl... | <|body_start_0|>
self.datastore_id = datastore_id
self.datastore_name = datastore_name
self.throttling_policy = throttling_policy
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
datastore_id = dictionary.get('datastoreId')
datastore_name = ... | Implementation of the 'ThrottlingPolicyOverride' model. Specifies throttling policy override for a Datastore in a registered entity. Attributes: datastore_id (long|int): Specifies the Protection Source id of the Datastore. datastore_name (string): Specifies the display name of the Datastore. throttling_policy (Throttli... | ThrottlingPolicyOverride | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThrottlingPolicyOverride:
"""Implementation of the 'ThrottlingPolicyOverride' model. Specifies throttling policy override for a Datastore in a registered entity. Attributes: datastore_id (long|int): Specifies the Protection Source id of the Datastore. datastore_name (string): Specifies the displa... | stack_v2_sparse_classes_36k_train_004224 | 2,329 | permissive | [
{
"docstring": "Constructor for the ThrottlingPolicyOverride class",
"name": "__init__",
"signature": "def __init__(self, datastore_id=None, datastore_name=None, throttling_policy=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dicti... | 2 | null | Implement the Python class `ThrottlingPolicyOverride` described below.
Class description:
Implementation of the 'ThrottlingPolicyOverride' model. Specifies throttling policy override for a Datastore in a registered entity. Attributes: datastore_id (long|int): Specifies the Protection Source id of the Datastore. datast... | Implement the Python class `ThrottlingPolicyOverride` described below.
Class description:
Implementation of the 'ThrottlingPolicyOverride' model. Specifies throttling policy override for a Datastore in a registered entity. Attributes: datastore_id (long|int): Specifies the Protection Source id of the Datastore. datast... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ThrottlingPolicyOverride:
"""Implementation of the 'ThrottlingPolicyOverride' model. Specifies throttling policy override for a Datastore in a registered entity. Attributes: datastore_id (long|int): Specifies the Protection Source id of the Datastore. datastore_name (string): Specifies the displa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThrottlingPolicyOverride:
"""Implementation of the 'ThrottlingPolicyOverride' model. Specifies throttling policy override for a Datastore in a registered entity. Attributes: datastore_id (long|int): Specifies the Protection Source id of the Datastore. datastore_name (string): Specifies the display name of the... | the_stack_v2_python_sparse | cohesity_management_sdk/models/throttling_policy_override.py | cohesity/management-sdk-python | train | 24 |
84f9d64d459b69c23d2a093429a9b28f787cd860 | [
"self.path_1 = path_1\nself.path_2 = path_2\nself.dir_1 = Files(self.path_1)\nself.dir_2 = Files(self.path_2)\nself.dir_1.explore(match=match)\nself.dir_2.explore(match=match)\nself.map_1 = self.dir_1.mapper_nd\nself.map_2 = self.dir_2.mapper_nd\nself.dir_1_count = self.dir_1.file_counter\nself.dir_2_count = self.d... | <|body_start_0|>
self.path_1 = path_1
self.path_2 = path_2
self.dir_1 = Files(self.path_1)
self.dir_2 = Files(self.path_2)
self.dir_1.explore(match=match)
self.dir_2.explore(match=match)
self.map_1 = self.dir_1.mapper_nd
self.map_2 = self.dir_2.mapper_nd
... | Given two paths will make a list of the files. For the files which are not common in both paths can copy them in a new directory Attributes ---------- - path_1: First path - path_2: Second path - map_1: Dictionary mapping every file of path_1 ({basename: fullpath}) - map_2: Dictionary mapping every file of path_2 ({bas... | Compare | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Compare:
"""Given two paths will make a list of the files. For the files which are not common in both paths can copy them in a new directory Attributes ---------- - path_1: First path - path_2: Second path - map_1: Dictionary mapping every file of path_1 ({basename: fullpath}) - map_2: Dictionary... | stack_v2_sparse_classes_36k_train_004225 | 15,202 | no_license | [
{
"docstring": ":param path_1: str First path. :param path_2: str Second path. :param match: str, list Filter for extension in '.py' format. It can be a string with 1 extension or a list with multiple extensions. (default: None) -> yields all files.",
"name": "__init__",
"signature": "def __init__(self,... | 5 | stack_v2_sparse_classes_30k_train_014638 | Implement the Python class `Compare` described below.
Class description:
Given two paths will make a list of the files. For the files which are not common in both paths can copy them in a new directory Attributes ---------- - path_1: First path - path_2: Second path - map_1: Dictionary mapping every file of path_1 ({b... | Implement the Python class `Compare` described below.
Class description:
Given two paths will make a list of the files. For the files which are not common in both paths can copy them in a new directory Attributes ---------- - path_1: First path - path_2: Second path - map_1: Dictionary mapping every file of path_1 ({b... | d4f12cbb42d96988d55b1796a5b5d6b98430fcfc | <|skeleton|>
class Compare:
"""Given two paths will make a list of the files. For the files which are not common in both paths can copy them in a new directory Attributes ---------- - path_1: First path - path_2: Second path - map_1: Dictionary mapping every file of path_1 ({basename: fullpath}) - map_2: Dictionary... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Compare:
"""Given two paths will make a list of the files. For the files which are not common in both paths can copy them in a new directory Attributes ---------- - path_1: First path - path_2: Second path - map_1: Dictionary mapping every file of path_1 ({basename: fullpath}) - map_2: Dictionary mapping ever... | the_stack_v2_python_sparse | handler.py | kosazna/ktima | train | 0 |
cabcec521549e3ec11f22cad761fb02c2191fedf | [
"super().__init__(config=config, parent=tool, **kwargs)\nif self.output_path is None:\n raise ValueError('Please specify an output path to save pedestal file')\nself.ped_obj = TCPedestalMaker(self.n_tms, self.n_blocks, self.n_samples, self.diagnosis, self.std)\nself.ped_stats = None",
"telid = 0\nwaveforms = e... | <|body_start_0|>
super().__init__(config=config, parent=tool, **kwargs)
if self.output_path is None:
raise ValueError('Please specify an output path to save pedestal file')
self.ped_obj = TCPedestalMaker(self.n_tms, self.n_blocks, self.n_samples, self.diagnosis, self.std)
sel... | PedestalMaker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PedestalMaker:
def __init__(self, config, tool, **kwargs):
"""Generator of Pedestal files. Parameters ---------- config : traitlets.loader.Config Configuration specified by config file or cmdline arguments. Used to set traitlet values. Set to None if no configuration to pass. tool : ctap... | stack_v2_sparse_classes_36k_train_004226 | 7,556 | no_license | [
{
"docstring": "Generator of Pedestal files. Parameters ---------- config : traitlets.loader.Config Configuration specified by config file or cmdline arguments. Used to set traitlet values. Set to None if no configuration to pass. tool : ctapipe.core.Tool Tool executable that is calling this component. Passes t... | 3 | stack_v2_sparse_classes_30k_train_002803 | Implement the Python class `PedestalMaker` described below.
Class description:
Implement the PedestalMaker class.
Method signatures and docstrings:
- def __init__(self, config, tool, **kwargs): Generator of Pedestal files. Parameters ---------- config : traitlets.loader.Config Configuration specified by config file o... | Implement the Python class `PedestalMaker` described below.
Class description:
Implement the PedestalMaker class.
Method signatures and docstrings:
- def __init__(self, config, tool, **kwargs): Generator of Pedestal files. Parameters ---------- config : traitlets.loader.Config Configuration specified by config file o... | 7238646f0793f9d9b0544be6723152d540b061a3 | <|skeleton|>
class PedestalMaker:
def __init__(self, config, tool, **kwargs):
"""Generator of Pedestal files. Parameters ---------- config : traitlets.loader.Config Configuration specified by config file or cmdline arguments. Used to set traitlet values. Set to None if no configuration to pass. tool : ctap... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PedestalMaker:
def __init__(self, config, tool, **kwargs):
"""Generator of Pedestal files. Parameters ---------- config : traitlets.loader.Config Configuration specified by config file or cmdline arguments. Used to set traitlet values. Set to None if no configuration to pass. tool : ctapipe.core.Tool ... | the_stack_v2_python_sparse | targetpipe/calib/camera/makers.py | watsonjj/targetpipe | train | 0 | |
ce93af0c4a4c649840d3c82700548cdbad43d259 | [
"num_len = len(nums)\nfor i in range(num_len):\n for j in range(i + 1, num_len):\n if nums[i] + num[j] == target:\n return [i, j]",
"for i, n in enumerate(nums):\n second = target - n\n if second in nums[i + 1:]:\n return [i, nums[i + 1:].index(second) + i + 1]",
"pair_nums = {... | <|body_start_0|>
num_len = len(nums)
for i in range(num_len):
for j in range(i + 1, num_len):
if nums[i] + num[j] == target:
return [i, j]
<|end_body_0|>
<|body_start_1|>
for i, n in enumerate(nums):
second = target - n
if ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum_1(self, nums: List[int], target: int) -> List[int]:
"""Brute-Force"""
<|body_0|>
def twoSum_2(self, nums: List[int], target: int) -> List[int]:
"""In"""
<|body_1|>
def twoSum_3(self, nums: List[int], target: int) -> List[int]:
... | stack_v2_sparse_classes_36k_train_004227 | 1,412 | no_license | [
{
"docstring": "Brute-Force",
"name": "twoSum_1",
"signature": "def twoSum_1(self, nums: List[int], target: int) -> List[int]"
},
{
"docstring": "In",
"name": "twoSum_2",
"signature": "def twoSum_2(self, nums: List[int], target: int) -> List[int]"
},
{
"docstring": "Dictionary 2 ... | 4 | stack_v2_sparse_classes_30k_train_011671 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_1(self, nums: List[int], target: int) -> List[int]: Brute-Force
- def twoSum_2(self, nums: List[int], target: int) -> List[int]: In
- def twoSum_3(self, nums: List[int... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum_1(self, nums: List[int], target: int) -> List[int]: Brute-Force
- def twoSum_2(self, nums: List[int], target: int) -> List[int]: In
- def twoSum_3(self, nums: List[int... | 8e1825e2b78c3897bde813520c1af5608a7c576c | <|skeleton|>
class Solution:
def twoSum_1(self, nums: List[int], target: int) -> List[int]:
"""Brute-Force"""
<|body_0|>
def twoSum_2(self, nums: List[int], target: int) -> List[int]:
"""In"""
<|body_1|>
def twoSum_3(self, nums: List[int], target: int) -> List[int]:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum_1(self, nums: List[int], target: int) -> List[int]:
"""Brute-Force"""
num_len = len(nums)
for i in range(num_len):
for j in range(i + 1, num_len):
if nums[i] + num[j] == target:
return [i, j]
def twoSum_2(self, n... | the_stack_v2_python_sparse | leetcode/linear/leetcode_1_two-sum.py | ecpark4545/algorithms | train | 0 | |
2e56f7458de7172fce86ef388881bd22b670308d | [
"super(Encoder, self).__init__()\nself.hidden_dim = hidden_dim // 2 if bidir else hidden_dim\nself.n_layers = n_layers * 2 if bidir else n_layers\nself.bidir = bidir\nself.lstm = nn.LSTM(embedding_dim, self.hidden_dim, n_layers, dropout=dropout, bidirectional=bidir)\nself.h0 = Parameter(torch.zeros(1), requires_gra... | <|body_start_0|>
super(Encoder, self).__init__()
self.hidden_dim = hidden_dim // 2 if bidir else hidden_dim
self.n_layers = n_layers * 2 if bidir else n_layers
self.bidir = bidir
self.lstm = nn.LSTM(embedding_dim, self.hidden_dim, n_layers, dropout=dropout, bidirectional=bidir)
... | Encoder class for Pointer-Net | Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
"""Encoder class for Pointer-Net"""
def __init__(self, embedding_dim, hidden_dim, n_layers, dropout, bidir):
"""Initiate Encoder :param Tensor embedding_dim: Number of embbeding channels :param int hidden_dim: Number of hidden units for the LSTM :param int n_layers: Number o... | stack_v2_sparse_classes_36k_train_004228 | 14,528 | no_license | [
{
"docstring": "Initiate Encoder :param Tensor embedding_dim: Number of embbeding channels :param int hidden_dim: Number of hidden units for the LSTM :param int n_layers: Number of layers for LSTMs :param float dropout: Float between 0-1 :param bool bidir: Bidirectional",
"name": "__init__",
"signature"... | 2 | stack_v2_sparse_classes_30k_train_018733 | Implement the Python class `Encoder` described below.
Class description:
Encoder class for Pointer-Net
Method signatures and docstrings:
- def __init__(self, embedding_dim, hidden_dim, n_layers, dropout, bidir): Initiate Encoder :param Tensor embedding_dim: Number of embbeding channels :param int hidden_dim: Number o... | Implement the Python class `Encoder` described below.
Class description:
Encoder class for Pointer-Net
Method signatures and docstrings:
- def __init__(self, embedding_dim, hidden_dim, n_layers, dropout, bidir): Initiate Encoder :param Tensor embedding_dim: Number of embbeding channels :param int hidden_dim: Number o... | f4b63e6643fe5e2112cc5afa5915a2b847c29e06 | <|skeleton|>
class Encoder:
"""Encoder class for Pointer-Net"""
def __init__(self, embedding_dim, hidden_dim, n_layers, dropout, bidir):
"""Initiate Encoder :param Tensor embedding_dim: Number of embbeding channels :param int hidden_dim: Number of hidden units for the LSTM :param int n_layers: Number o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Encoder:
"""Encoder class for Pointer-Net"""
def __init__(self, embedding_dim, hidden_dim, n_layers, dropout, bidir):
"""Initiate Encoder :param Tensor embedding_dim: Number of embbeding channels :param int hidden_dim: Number of hidden units for the LSTM :param int n_layers: Number of layers for ... | the_stack_v2_python_sparse | PointerNet.py | Nishad94/SQuAD_PtrNets | train | 0 |
e56b1cf13574e362df8cd5785b9816c1507793f6 | [
"log_as_info('\\nDestinationDirective.run')\nnode = DestinationNode('')\njinja2_value = self.arguments[0].replace('<', '{{ ').replace('>', ' }}')\nnode.markup = create_post_processing_markup('DESTINATION', jinja2_value)\nreturn [node]",
"for node in doctree.traverse(DestinationNode):\n replacement_node = docut... | <|body_start_0|>
log_as_info('\nDestinationDirective.run')
node = DestinationNode('')
jinja2_value = self.arguments[0].replace('<', '{{ ').replace('>', ' }}')
node.markup = create_post_processing_markup('DESTINATION', jinja2_value)
return [node]
<|end_body_0|>
<|body_start_1|>
... | Implements the .\\. astutus_dyn_destintation:: directive. The one required argument specifies a relative filepath where to write the styled template. Its optional, and is for the convenience of the web developer. In most cases, the default location based on the name and location the dynamic page. | DestinationDirective | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DestinationDirective:
"""Implements the .\\. astutus_dyn_destintation:: directive. The one required argument specifies a relative filepath where to write the styled template. Its optional, and is for the convenience of the web developer. In most cases, the default location based on the name and l... | stack_v2_sparse_classes_36k_train_004229 | 16,710 | permissive | [
{
"docstring": "Replaces the directive in the \\\\*.rst file with a DestinationNode.",
"name": "run",
"signature": "def run(self) -> List[docutils.nodes.Node]"
},
{
"docstring": "Handle title modification by inserting post processing markup.",
"name": "handle_insert_markup",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_009238 | Implement the Python class `DestinationDirective` described below.
Class description:
Implements the .\\. astutus_dyn_destintation:: directive. The one required argument specifies a relative filepath where to write the styled template. Its optional, and is for the convenience of the web developer. In most cases, the d... | Implement the Python class `DestinationDirective` described below.
Class description:
Implements the .\\. astutus_dyn_destintation:: directive. The one required argument specifies a relative filepath where to write the styled template. Its optional, and is for the convenience of the web developer. In most cases, the d... | 46a11295394093de3a23cb8dec1e2e76eac752e8 | <|skeleton|>
class DestinationDirective:
"""Implements the .\\. astutus_dyn_destintation:: directive. The one required argument specifies a relative filepath where to write the styled template. Its optional, and is for the convenience of the web developer. In most cases, the default location based on the name and l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DestinationDirective:
"""Implements the .\\. astutus_dyn_destintation:: directive. The one required argument specifies a relative filepath where to write the styled template. Its optional, and is for the convenience of the web developer. In most cases, the default location based on the name and location the d... | the_stack_v2_python_sparse | src/astutus/sphinx/dyn_pages.py | rich-dobbs-13440/astutus | train | 0 |
9778558716d91380125fb079e5d5005ac9313c71 | [
"parser.add_argument('path', nargs='*', help='The path of objects and directories to list. The path must begin with gs:// and may or may not contain wildcard characters.')\nparser.add_argument('-a', '--all-versions', action='store_true', help='Includes non-current object versions / generations in the listing (only ... | <|body_start_0|>
parser.add_argument('path', nargs='*', help='The path of objects and directories to list. The path must begin with gs:// and may or may not contain wildcard characters.')
parser.add_argument('-a', '--all-versions', action='store_true', help='Includes non-current object versions / genera... | List Cloud Storage buckets and objects. | Ls | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ls:
"""List Cloud Storage buckets and objects."""
def Args(parser):
"""Edit argparse.ArgumentParser for the command."""
<|body_0|>
def Run(self, args):
"""Command execution logic."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
parser.add_argume... | stack_v2_sparse_classes_36k_train_004230 | 5,764 | permissive | [
{
"docstring": "Edit argparse.ArgumentParser for the command.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "Command execution logic.",
"name": "Run",
"signature": "def Run(self, args)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016329 | Implement the Python class `Ls` described below.
Class description:
List Cloud Storage buckets and objects.
Method signatures and docstrings:
- def Args(parser): Edit argparse.ArgumentParser for the command.
- def Run(self, args): Command execution logic. | Implement the Python class `Ls` described below.
Class description:
List Cloud Storage buckets and objects.
Method signatures and docstrings:
- def Args(parser): Edit argparse.ArgumentParser for the command.
- def Run(self, args): Command execution logic.
<|skeleton|>
class Ls:
"""List Cloud Storage buckets and ... | 849d09dd7863efecbdf4072a504e1554e119f6ae | <|skeleton|>
class Ls:
"""List Cloud Storage buckets and objects."""
def Args(parser):
"""Edit argparse.ArgumentParser for the command."""
<|body_0|>
def Run(self, args):
"""Command execution logic."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ls:
"""List Cloud Storage buckets and objects."""
def Args(parser):
"""Edit argparse.ArgumentParser for the command."""
parser.add_argument('path', nargs='*', help='The path of objects and directories to list. The path must begin with gs:// and may or may not contain wildcard characters.'... | the_stack_v2_python_sparse | google-cloud-sdk/lib/surface/storage/ls.py | PrateekKhatri/gcloud_cli | train | 0 |
ecd97a9935a567d3f0ea41b88f3747ded6a5ee4b | [
"table_name = os.environ.get('PAY_PAY_COUPON_INFO_DB')\nsuper().__init__(table_name)\nself._table = self._db.Table(table_name)",
"key = {'couponId': coupon_id}\ntry:\n item = self._get_item(key)\nexcept Exception as e:\n raise e\nreturn item",
"try:\n items = self._scan('deleted', '')\nexcept Exception... | <|body_start_0|>
table_name = os.environ.get('PAY_PAY_COUPON_INFO_DB')
super().__init__(table_name)
self._table = self._db.Table(table_name)
<|end_body_0|>
<|body_start_1|>
key = {'couponId': coupon_id}
try:
item = self._get_item(key)
except Exception as e:
... | SmartRegisterCouponInfo操作用クラス | SmartRegisterCouponInfo | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SmartRegisterCouponInfo:
"""SmartRegisterCouponInfo操作用クラス"""
def __init__(self):
"""初期化メソッド"""
<|body_0|>
def get_item(self, coupon_id):
"""データ取得 Parameters ---------- coupon_id : str クーポンID Returns ------- item : dict クーポン情報"""
<|body_1|>
def scan_n... | stack_v2_sparse_classes_36k_train_004231 | 1,189 | permissive | [
{
"docstring": "初期化メソッド",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "データ取得 Parameters ---------- coupon_id : str クーポンID Returns ------- item : dict クーポン情報",
"name": "get_item",
"signature": "def get_item(self, coupon_id)"
},
{
"docstring": "削除済みでないアイ... | 3 | stack_v2_sparse_classes_30k_train_019347 | Implement the Python class `SmartRegisterCouponInfo` described below.
Class description:
SmartRegisterCouponInfo操作用クラス
Method signatures and docstrings:
- def __init__(self): 初期化メソッド
- def get_item(self, coupon_id): データ取得 Parameters ---------- coupon_id : str クーポンID Returns ------- item : dict クーポン情報
- def scan_not_d... | Implement the Python class `SmartRegisterCouponInfo` described below.
Class description:
SmartRegisterCouponInfo操作用クラス
Method signatures and docstrings:
- def __init__(self): 初期化メソッド
- def get_item(self, coupon_id): データ取得 Parameters ---------- coupon_id : str クーポンID Returns ------- item : dict クーポン情報
- def scan_not_d... | 5667bc2d1db6d60950d8b9b6d6265e56b406ea1f | <|skeleton|>
class SmartRegisterCouponInfo:
"""SmartRegisterCouponInfo操作用クラス"""
def __init__(self):
"""初期化メソッド"""
<|body_0|>
def get_item(self, coupon_id):
"""データ取得 Parameters ---------- coupon_id : str クーポンID Returns ------- item : dict クーポン情報"""
<|body_1|>
def scan_n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SmartRegisterCouponInfo:
"""SmartRegisterCouponInfo操作用クラス"""
def __init__(self):
"""初期化メソッド"""
table_name = os.environ.get('PAY_PAY_COUPON_INFO_DB')
super().__init__(table_name)
self._table = self._db.Table(table_name)
def get_item(self, coupon_id):
"""データ取得 P... | the_stack_v2_python_sparse | backend/Layer/layer/smart_register/smart_register_coupon_info.py | tacck/line-api-use-case-smart-retail | train | 1 |
9e08d0309174e2e08b8384772de34d45b0b03eea | [
"index = self.isPalindrome(s)\nchars = list(s)\nsize = len(chars)\nif index != -1:\n k = size - index\n firstS = chars[index:k - 1]\n if self.isPalindrome(firstS) == -1:\n return True\n lastS = chars[index + 1:k]\n return self.isPalindrome(lastS) == -1\nelse:\n return True",
"size = len(c... | <|body_start_0|>
index = self.isPalindrome(s)
chars = list(s)
size = len(chars)
if index != -1:
k = size - index
firstS = chars[index:k - 1]
if self.isPalindrome(firstS) == -1:
return True
lastS = chars[index + 1:k]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def validPalindrome(self, s: str) -> bool:
""":type s: str :rtype: bool"""
<|body_0|>
def isPalindrome(self, chars: list) -> int:
""":type chars:list<str> :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
index = self.isPalindrom... | stack_v2_sparse_classes_36k_train_004232 | 1,252 | no_license | [
{
"docstring": ":type s: str :rtype: bool",
"name": "validPalindrome",
"signature": "def validPalindrome(self, s: str) -> bool"
},
{
"docstring": ":type chars:list<str> :rtype: int",
"name": "isPalindrome",
"signature": "def isPalindrome(self, chars: list) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validPalindrome(self, s: str) -> bool: :type s: str :rtype: bool
- def isPalindrome(self, chars: list) -> int: :type chars:list<str> :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validPalindrome(self, s: str) -> bool: :type s: str :rtype: bool
- def isPalindrome(self, chars: list) -> int: :type chars:list<str> :rtype: int
<|skeleton|>
class Solution:... | c4d3f3982862fb4dc1ba03df20e6c2901f5b5bb3 | <|skeleton|>
class Solution:
def validPalindrome(self, s: str) -> bool:
""":type s: str :rtype: bool"""
<|body_0|>
def isPalindrome(self, chars: list) -> int:
""":type chars:list<str> :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def validPalindrome(self, s: str) -> bool:
""":type s: str :rtype: bool"""
index = self.isPalindrome(s)
chars = list(s)
size = len(chars)
if index != -1:
k = size - index
firstS = chars[index:k - 1]
if self.isPalindrome(firs... | the_stack_v2_python_sparse | 600/valid_palindrome_ii.py | ramsayleung/leetcode | train | 0 | |
2d17306cdd0ef0c1074bd7ec0bdf68684b2c013f | [
"dev = self.selectedDevice(c)\ntemperatures = []\nfor i in range(1, 17):\n res = (yield dev.query('RDGR? ' + str(i)))\n res = float(res)\n temp = np.power(2.85 / np.log((res - 652) / 100), 4)\n temperatures.append(temp)\ntemperatures = temperatures * units.K\nreturnValue(temperatures)",
"dev = self.se... | <|body_start_0|>
dev = self.selectedDevice(c)
temperatures = []
for i in range(1, 17):
res = (yield dev.query('RDGR? ' + str(i)))
res = float(res)
temp = np.power(2.85 / np.log((res - 652) / 100), 4)
temperatures.append(temp)
temperatures =... | LakeshoreRuOxServer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LakeshoreRuOxServer:
def temperatures(self, c):
"""Read channel temperatures. Returns a ValueList of the channel temperatures in Kelvin."""
<|body_0|>
def resistances(self, c):
"""Read channel temperatures. Returns a ValueList of the channel temperatures in Kelvin.""... | stack_v2_sparse_classes_36k_train_004233 | 2,401 | no_license | [
{
"docstring": "Read channel temperatures. Returns a ValueList of the channel temperatures in Kelvin.",
"name": "temperatures",
"signature": "def temperatures(self, c)"
},
{
"docstring": "Read channel temperatures. Returns a ValueList of the channel temperatures in Kelvin.",
"name": "resista... | 2 | null | Implement the Python class `LakeshoreRuOxServer` described below.
Class description:
Implement the LakeshoreRuOxServer class.
Method signatures and docstrings:
- def temperatures(self, c): Read channel temperatures. Returns a ValueList of the channel temperatures in Kelvin.
- def resistances(self, c): Read channel te... | Implement the Python class `LakeshoreRuOxServer` described below.
Class description:
Implement the LakeshoreRuOxServer class.
Method signatures and docstrings:
- def temperatures(self, c): Read channel temperatures. Returns a ValueList of the channel temperatures in Kelvin.
- def resistances(self, c): Read channel te... | 6f041503ff9967e7ed52cfb619d9cc21d66b5ad6 | <|skeleton|>
class LakeshoreRuOxServer:
def temperatures(self, c):
"""Read channel temperatures. Returns a ValueList of the channel temperatures in Kelvin."""
<|body_0|>
def resistances(self, c):
"""Read channel temperatures. Returns a ValueList of the channel temperatures in Kelvin.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LakeshoreRuOxServer:
def temperatures(self, c):
"""Read channel temperatures. Returns a ValueList of the channel temperatures in Kelvin."""
dev = self.selectedDevice(c)
temperatures = []
for i in range(1, 17):
res = (yield dev.query('RDGR? ' + str(i)))
r... | the_stack_v2_python_sparse | instruments/gpibdevices/lakeshore370_simple.py | McDermott-Group/servers | train | 0 | |
812dac38df3190bb2b0d14dc3af4801fdf9d1147 | [
"self.protection_jobs = protection_jobs\nself.protection_policies = protection_policies\nself.protection_source = protection_source\nself.stats = stats",
"if dictionary is None:\n return None\nprotection_jobs = None\nif dictionary.get('protectionJobs') != None:\n protection_jobs = list()\n for structure ... | <|body_start_0|>
self.protection_jobs = protection_jobs
self.protection_policies = protection_policies
self.protection_source = protection_source
self.stats = stats
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
protection_jobs = None
... | Implementation of the 'ProtectedVmInfo' model. Specifies the Protection Jobs information of a VM. Attributes: protection_jobs (list of ProtectionJob): Specifies the list of Protection Jobs that protect the VM. protection_policies (list of ProtectionPolicy): Specifies the list of Policies that are used by the Protection... | ProtectedVmInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProtectedVmInfo:
"""Implementation of the 'ProtectedVmInfo' model. Specifies the Protection Jobs information of a VM. Attributes: protection_jobs (list of ProtectionJob): Specifies the list of Protection Jobs that protect the VM. protection_policies (list of ProtectionPolicy): Specifies the list ... | stack_v2_sparse_classes_36k_train_004234 | 3,391 | permissive | [
{
"docstring": "Constructor for the ProtectedVmInfo class",
"name": "__init__",
"signature": "def __init__(self, protection_jobs=None, protection_policies=None, protection_source=None, stats=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionar... | 2 | null | Implement the Python class `ProtectedVmInfo` described below.
Class description:
Implementation of the 'ProtectedVmInfo' model. Specifies the Protection Jobs information of a VM. Attributes: protection_jobs (list of ProtectionJob): Specifies the list of Protection Jobs that protect the VM. protection_policies (list of... | Implement the Python class `ProtectedVmInfo` described below.
Class description:
Implementation of the 'ProtectedVmInfo' model. Specifies the Protection Jobs information of a VM. Attributes: protection_jobs (list of ProtectionJob): Specifies the list of Protection Jobs that protect the VM. protection_policies (list of... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ProtectedVmInfo:
"""Implementation of the 'ProtectedVmInfo' model. Specifies the Protection Jobs information of a VM. Attributes: protection_jobs (list of ProtectionJob): Specifies the list of Protection Jobs that protect the VM. protection_policies (list of ProtectionPolicy): Specifies the list ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProtectedVmInfo:
"""Implementation of the 'ProtectedVmInfo' model. Specifies the Protection Jobs information of a VM. Attributes: protection_jobs (list of ProtectionJob): Specifies the list of Protection Jobs that protect the VM. protection_policies (list of ProtectionPolicy): Specifies the list of Policies t... | the_stack_v2_python_sparse | cohesity_management_sdk/models/protected_vm_info.py | cohesity/management-sdk-python | train | 24 |
3d09f495d753a288555f9a584c0e5851e420186c | [
"if not head:\n return None\nfast, slow = (head, head)\nwhile fast.next and fast.next.next:\n fast, slow = (fast.next.next, slow.next)\n if fast is slow:\n break\nif not fast.next or not fast.next.next:\n return None\nslow = head\nwhile fast is not slow:\n fast, slow = (fast.next, slow.next)\n... | <|body_start_0|>
if not head:
return None
fast, slow = (head, head)
while fast.next and fast.next.next:
fast, slow = (fast.next.next, slow.next)
if fast is slow:
break
if not fast.next or not fast.next.next:
return None
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def detectCycle(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def detectCycle1(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not head:
return None... | stack_v2_sparse_classes_36k_train_004235 | 1,929 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "detectCycle",
"signature": "def detectCycle(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "detectCycle1",
"signature": "def detectCycle1(self, head)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def detectCycle(self, head): :type head: ListNode :rtype: ListNode
- def detectCycle1(self, head): :type head: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def detectCycle(self, head): :type head: ListNode :rtype: ListNode
- def detectCycle1(self, head): :type head: ListNode :rtype: ListNode
<|skeleton|>
class Solution:
def de... | 4a1747b6497305f3821612d9c358a6795b1690da | <|skeleton|>
class Solution:
def detectCycle(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def detectCycle1(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def detectCycle(self, head):
""":type head: ListNode :rtype: ListNode"""
if not head:
return None
fast, slow = (head, head)
while fast.next and fast.next.next:
fast, slow = (fast.next.next, slow.next)
if fast is slow:
... | the_stack_v2_python_sparse | LinkedList/q142_linked_list_cycle_ii.py | sevenhe716/LeetCode | train | 0 | |
60e58ae2f11593b81982ec718ac87184974f3d9c | [
"try:\n payload = jwt.decode(data['token'], settings.SECRET_KEY, algorithms=['HS256'])\nexcept ExpiredSignatureError:\n raise serializers.ValidationError('The token has expired.')\nexcept JWTError:\n raise serializers.ValidationError('Error validating token. Ensure is the right token.')\nself.context['payl... | <|body_start_0|>
try:
payload = jwt.decode(data['token'], settings.SECRET_KEY, algorithms=['HS256'])
except ExpiredSignatureError:
raise serializers.ValidationError('The token has expired.')
except JWTError:
raise serializers.ValidationError('Error validating ... | Account verification Serializer that allows to know which user has a verificated account and which doesn't | AccountVerificationSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountVerificationSerializer:
"""Account verification Serializer that allows to know which user has a verificated account and which doesn't"""
def validate(self, data):
"""Validate method for the token"""
<|body_0|>
def save(self, **kwargs):
"""Update the user's... | stack_v2_sparse_classes_36k_train_004236 | 6,022 | no_license | [
{
"docstring": "Validate method for the token",
"name": "validate",
"signature": "def validate(self, data)"
},
{
"docstring": "Update the user's verification status",
"name": "save",
"signature": "def save(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002817 | Implement the Python class `AccountVerificationSerializer` described below.
Class description:
Account verification Serializer that allows to know which user has a verificated account and which doesn't
Method signatures and docstrings:
- def validate(self, data): Validate method for the token
- def save(self, **kwarg... | Implement the Python class `AccountVerificationSerializer` described below.
Class description:
Account verification Serializer that allows to know which user has a verificated account and which doesn't
Method signatures and docstrings:
- def validate(self, data): Validate method for the token
- def save(self, **kwarg... | bd037be8a814dce554e709d851c6a96e6a41ea78 | <|skeleton|>
class AccountVerificationSerializer:
"""Account verification Serializer that allows to know which user has a verificated account and which doesn't"""
def validate(self, data):
"""Validate method for the token"""
<|body_0|>
def save(self, **kwargs):
"""Update the user's... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccountVerificationSerializer:
"""Account verification Serializer that allows to know which user has a verificated account and which doesn't"""
def validate(self, data):
"""Validate method for the token"""
try:
payload = jwt.decode(data['token'], settings.SECRET_KEY, algorithm... | the_stack_v2_python_sparse | users/serializers/users.py | jpcano1/tShoes | train | 0 |
942f7e2ac06f33815a91e6f04e0527deb23a6d66 | [
"edge_width = 1\ncube = iris.util.squeeze(self.cube)\nsmoothing_coefficients_x, smoothing_coefficients_y = RecursiveFilter(edge_width=edge_width)._pad_coefficients(*self.smoothing_coefficients)\npadded_cube = pad_cube_with_halo(cube, 2 * edge_width, 2 * edge_width)\nresult = RecursiveFilter(edge_width=1)._run_recur... | <|body_start_0|>
edge_width = 1
cube = iris.util.squeeze(self.cube)
smoothing_coefficients_x, smoothing_coefficients_y = RecursiveFilter(edge_width=edge_width)._pad_coefficients(*self.smoothing_coefficients)
padded_cube = pad_cube_with_halo(cube, 2 * edge_width, 2 * edge_width)
r... | Test the _run_recursion method | Test__run_recursion | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__run_recursion:
"""Test the _run_recursion method"""
def test_return_type(self):
"""Test that the _run_recursion method returns an iris.cube.Cube."""
<|body_0|>
def test_result_basic(self):
"""Test that the _run_recursion method returns the expected value.""... | stack_v2_sparse_classes_36k_train_004237 | 22,857 | permissive | [
{
"docstring": "Test that the _run_recursion method returns an iris.cube.Cube.",
"name": "test_return_type",
"signature": "def test_return_type(self)"
},
{
"docstring": "Test that the _run_recursion method returns the expected value.",
"name": "test_result_basic",
"signature": "def test_... | 3 | null | Implement the Python class `Test__run_recursion` described below.
Class description:
Test the _run_recursion method
Method signatures and docstrings:
- def test_return_type(self): Test that the _run_recursion method returns an iris.cube.Cube.
- def test_result_basic(self): Test that the _run_recursion method returns ... | Implement the Python class `Test__run_recursion` described below.
Class description:
Test the _run_recursion method
Method signatures and docstrings:
- def test_return_type(self): Test that the _run_recursion method returns an iris.cube.Cube.
- def test_result_basic(self): Test that the _run_recursion method returns ... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test__run_recursion:
"""Test the _run_recursion method"""
def test_return_type(self):
"""Test that the _run_recursion method returns an iris.cube.Cube."""
<|body_0|>
def test_result_basic(self):
"""Test that the _run_recursion method returns the expected value.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test__run_recursion:
"""Test the _run_recursion method"""
def test_return_type(self):
"""Test that the _run_recursion method returns an iris.cube.Cube."""
edge_width = 1
cube = iris.util.squeeze(self.cube)
smoothing_coefficients_x, smoothing_coefficients_y = RecursiveFilte... | the_stack_v2_python_sparse | improver_tests/nbhood/recursive_filter/test_RecursiveFilter.py | metoppv/improver | train | 101 |
fa6a64edfedfb58724642f0f52551f877f909e29 | [
"result = []\nif is_blank:\n result.append(('', ''))\nclassify_person_list = ClassifyPersonOpe.get_classify_person_list(inout_kubun, kotei_hendo_kubun)\nfor classify_person_row in classify_person_list:\n classify_person_row: ClassifyPersonData = classify_person_row\n result.append((classify_person_row.clas... | <|body_start_0|>
result = []
if is_blank:
result.append(('', ''))
classify_person_list = ClassifyPersonOpe.get_classify_person_list(inout_kubun, kotei_hendo_kubun)
for classify_person_row in classify_person_list:
classify_person_row: ClassifyPersonData = classify_... | 収入支出分類と対象者に関わる操作 | ClassifyPersonOpe | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassifyPersonOpe:
"""収入支出分類と対象者に関わる操作"""
def get_classify_person_combobox(inout_kubun, kotei_hendo_kubun, is_blank):
"""コンボボックス表示用に「収入支出分類コード_対象者コード」のリストを作成する。 :param inout_kubun: リストに含める収入支出区分を指定する。空の場合はすべての区分となる。 :param kotei_hendo_kubun: リストに含める固定変動区分を指定する。空の場合はすべての区分となる。 :param ... | stack_v2_sparse_classes_36k_train_004238 | 15,255 | no_license | [
{
"docstring": "コンボボックス表示用に「収入支出分類コード_対象者コード」のリストを作成する。 :param inout_kubun: リストに含める収入支出区分を指定する。空の場合はすべての区分となる。 :param kotei_hendo_kubun: リストに含める固定変動区分を指定する。空の場合はすべての区分となる。 :param is_blank: コンボボックスの先頭に空白項目を持たせるかどうか。 :return: コンボボックス用のリスト",
"name": "get_classify_person_combobox",
"signature": "def get_cla... | 2 | stack_v2_sparse_classes_30k_train_003115 | Implement the Python class `ClassifyPersonOpe` described below.
Class description:
収入支出分類と対象者に関わる操作
Method signatures and docstrings:
- def get_classify_person_combobox(inout_kubun, kotei_hendo_kubun, is_blank): コンボボックス表示用に「収入支出分類コード_対象者コード」のリストを作成する。 :param inout_kubun: リストに含める収入支出区分を指定する。空の場合はすべての区分となる。 :param kote... | Implement the Python class `ClassifyPersonOpe` described below.
Class description:
収入支出分類と対象者に関わる操作
Method signatures and docstrings:
- def get_classify_person_combobox(inout_kubun, kotei_hendo_kubun, is_blank): コンボボックス表示用に「収入支出分類コード_対象者コード」のリストを作成する。 :param inout_kubun: リストに含める収入支出区分を指定する。空の場合はすべての区分となる。 :param kote... | 0ddf7b6e2fbb4863ab13bd7a3ae29cc27b3ae435 | <|skeleton|>
class ClassifyPersonOpe:
"""収入支出分類と対象者に関わる操作"""
def get_classify_person_combobox(inout_kubun, kotei_hendo_kubun, is_blank):
"""コンボボックス表示用に「収入支出分類コード_対象者コード」のリストを作成する。 :param inout_kubun: リストに含める収入支出区分を指定する。空の場合はすべての区分となる。 :param kotei_hendo_kubun: リストに含める固定変動区分を指定する。空の場合はすべての区分となる。 :param ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClassifyPersonOpe:
"""収入支出分類と対象者に関わる操作"""
def get_classify_person_combobox(inout_kubun, kotei_hendo_kubun, is_blank):
"""コンボボックス表示用に「収入支出分類コード_対象者コード」のリストを作成する。 :param inout_kubun: リストに含める収入支出区分を指定する。空の場合はすべての区分となる。 :param kotei_hendo_kubun: リストに含める固定変動区分を指定する。空の場合はすべての区分となる。 :param is_blank: コンボ... | the_stack_v2_python_sparse | kakeibo/util/kakeibo_util.py | Shogo596/kakeibo | train | 0 |
c1515c5dc778eff629afe7c54efb174fb38b91a3 | [
"query_param = {'delete_info': json.dumps({'volume_id': volume_id})}\nresp, body = self.delete('os-assisted-volume-snapshots/%s?%s' % (snapshot_id, urllib.urlencode(query_param)))\nreturn rest_client.ResponseBody(resp, body)",
"url = 'os-assisted-volume-snapshots'\ninfo = {'snapshot_id': snapshot_id}\nif kwargs:\... | <|body_start_0|>
query_param = {'delete_info': json.dumps({'volume_id': volume_id})}
resp, body = self.delete('os-assisted-volume-snapshots/%s?%s' % (snapshot_id, urllib.urlencode(query_param)))
return rest_client.ResponseBody(resp, body)
<|end_body_0|>
<|body_start_1|>
url = 'os-assist... | Service client for assisted volume snapshots | AssistedVolumeSnapshotsClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AssistedVolumeSnapshotsClient:
"""Service client for assisted volume snapshots"""
def delete_assisted_volume_snapshot(self, volume_id, snapshot_id):
"""Delete snapshot for the given volume id. For a full list of available parameters, please refer to the official API reference: https:... | stack_v2_sparse_classes_36k_train_004239 | 2,660 | permissive | [
{
"docstring": "Delete snapshot for the given volume id. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/compute/#delete-assisted-volume-snapshot :param volume_id: UUID of the volume :param snapshot_id: The UUID of the snapshot",
"name"... | 2 | null | Implement the Python class `AssistedVolumeSnapshotsClient` described below.
Class description:
Service client for assisted volume snapshots
Method signatures and docstrings:
- def delete_assisted_volume_snapshot(self, volume_id, snapshot_id): Delete snapshot for the given volume id. For a full list of available param... | Implement the Python class `AssistedVolumeSnapshotsClient` described below.
Class description:
Service client for assisted volume snapshots
Method signatures and docstrings:
- def delete_assisted_volume_snapshot(self, volume_id, snapshot_id): Delete snapshot for the given volume id. For a full list of available param... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class AssistedVolumeSnapshotsClient:
"""Service client for assisted volume snapshots"""
def delete_assisted_volume_snapshot(self, volume_id, snapshot_id):
"""Delete snapshot for the given volume id. For a full list of available parameters, please refer to the official API reference: https:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AssistedVolumeSnapshotsClient:
"""Service client for assisted volume snapshots"""
def delete_assisted_volume_snapshot(self, volume_id, snapshot_id):
"""Delete snapshot for the given volume id. For a full list of available parameters, please refer to the official API reference: https://docs.openst... | the_stack_v2_python_sparse | tempest/lib/services/compute/assisted_volume_snapshots_client.py | openstack/tempest | train | 270 |
5f6b7ba88fca5f6000e9e3375e78725d5fd5d568 | [
"super(NodeBuilder, self).__init__()\nself.parameters = parameters\nself._role = role\nself._connection = None\nself._interface = None\nself._node = None\nself._address = None\nreturn",
"if self._role is None:\n self._role = BaseDeviceEnum.node\nreturn self._role",
"if self._address is None:\n try:\n ... | <|body_start_0|>
super(NodeBuilder, self).__init__()
self.parameters = parameters
self._role = role
self._connection = None
self._interface = None
self._node = None
self._address = None
return
<|end_body_0|>
<|body_start_1|>
if self._role is None:... | A class to build a device (node) | NodeBuilder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NodeBuilder:
"""A class to build a device (node)"""
def __init__(self, parameters, role=None):
"""NodeBuilder Constructor :param: - `parameters`: object with attributes needed for device & connection - `role`: tpc or node"""
<|body_0|>
def role(self):
"""Sets the... | stack_v2_sparse_classes_36k_train_004240 | 3,647 | permissive | [
{
"docstring": "NodeBuilder Constructor :param: - `parameters`: object with attributes needed for device & connection - `role`: tpc or node",
"name": "__init__",
"signature": "def __init__(self, parameters, role=None)"
},
{
"docstring": "Sets the role to BaseDeviceEnum.node :return: the device r... | 6 | null | Implement the Python class `NodeBuilder` described below.
Class description:
A class to build a device (node)
Method signatures and docstrings:
- def __init__(self, parameters, role=None): NodeBuilder Constructor :param: - `parameters`: object with attributes needed for device & connection - `role`: tpc or node
- def... | Implement the Python class `NodeBuilder` described below.
Class description:
A class to build a device (node)
Method signatures and docstrings:
- def __init__(self, parameters, role=None): NodeBuilder Constructor :param: - `parameters`: object with attributes needed for device & connection - `role`: tpc or node
- def... | b4d1c77e1d611fe2b30768b42bdc7493afb0ea95 | <|skeleton|>
class NodeBuilder:
"""A class to build a device (node)"""
def __init__(self, parameters, role=None):
"""NodeBuilder Constructor :param: - `parameters`: object with attributes needed for device & connection - `role`: tpc or node"""
<|body_0|>
def role(self):
"""Sets the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NodeBuilder:
"""A class to build a device (node)"""
def __init__(self, parameters, role=None):
"""NodeBuilder Constructor :param: - `parameters`: object with attributes needed for device & connection - `role`: tpc or node"""
super(NodeBuilder, self).__init__()
self.parameters = pa... | the_stack_v2_python_sparse | apetools/builders/subbuilders/nodebuilder.py | russell-n/oldape | train | 0 |
c887e5ee53a65ed62a1ff9db64dccf7b8b3afa72 | [
"email = self.normalize_email(email)\nuser = self.model(email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, **extra_fields)\nuser.set_password(password)\nif user.user_id in [None, '']:\n user.user_id = generate_user_id()\nuser.save(using=self._db)\nreturn user",
"email = email or ''\ntry... | <|body_start_0|>
email = self.normalize_email(email)
user = self.model(email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, **extra_fields)
user.set_password(password)
if user.user_id in [None, '']:
user.user_id = generate_user_id()
user.save(usi... | UserProfileQuerySet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserProfileQuerySet:
def _create_user(self, email, password, is_staff, is_superuser, **extra_fields):
"""Creates and saves a User with the given email and password and primary_contact_number."""
<|body_0|>
def normalize_email(self, email):
"""Normalize the email addr... | stack_v2_sparse_classes_36k_train_004241 | 10,289 | no_license | [
{
"docstring": "Creates and saves a User with the given email and password and primary_contact_number.",
"name": "_create_user",
"signature": "def _create_user(self, email, password, is_staff, is_superuser, **extra_fields)"
},
{
"docstring": "Normalize the email address by lowercasing the domain... | 3 | stack_v2_sparse_classes_30k_train_021647 | Implement the Python class `UserProfileQuerySet` described below.
Class description:
Implement the UserProfileQuerySet class.
Method signatures and docstrings:
- def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): Creates and saves a User with the given email and password and primary_cont... | Implement the Python class `UserProfileQuerySet` described below.
Class description:
Implement the UserProfileQuerySet class.
Method signatures and docstrings:
- def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): Creates and saves a User with the given email and password and primary_cont... | 8e9c890c4f9c3df65847ae3cfea55c062194cdf9 | <|skeleton|>
class UserProfileQuerySet:
def _create_user(self, email, password, is_staff, is_superuser, **extra_fields):
"""Creates and saves a User with the given email and password and primary_contact_number."""
<|body_0|>
def normalize_email(self, email):
"""Normalize the email addr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserProfileQuerySet:
def _create_user(self, email, password, is_staff, is_superuser, **extra_fields):
"""Creates and saves a User with the given email and password and primary_contact_number."""
email = self.normalize_email(email)
user = self.model(email=email, is_staff=is_staff, is_ac... | the_stack_v2_python_sparse | awards/useraccount/models.py | anshul-choudhary/photography-awards | train | 0 | |
9f502c61502662aac3707af67bd11cec7c4b4805 | [
"res = []\nstack = [root]\nif not root:\n return '#'\nwhile stack:\n cur = stack.pop()\n if cur:\n res.append(str(cur.val))\n stack.append(cur.right)\n stack.append(cur.left)\n else:\n res.append('#')\nreturn ','.join(res)",
"if not data:\n return None\ndata_list = data.... | <|body_start_0|>
res = []
stack = [root]
if not root:
return '#'
while stack:
cur = stack.pop()
if cur:
res.append(str(cur.val))
stack.append(cur.right)
stack.append(cur.left)
else:
... | 二叉搜索树能只够通过前序序列或后序序列构造,是因为以下两个因素: 二叉树可以通过前序序列或后序序列和中序序列构造。 二叉搜索树的中序序列是递增排序的序列,inorder = sorted(preorder) | CodecMe | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CodecMe:
"""二叉搜索树能只够通过前序序列或后序序列构造,是因为以下两个因素: 二叉树可以通过前序序列或后序序列和中序序列构造。 二叉搜索树的中序序列是递增排序的序列,inorder = sorted(preorder)"""
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string. 照常前序遍历"""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
... | stack_v2_sparse_classes_36k_train_004242 | 3,644 | no_license | [
{
"docstring": "Encodes a tree to a single string. 照常前序遍历",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | null | Implement the Python class `CodecMe` described below.
Class description:
二叉搜索树能只够通过前序序列或后序序列构造,是因为以下两个因素: 二叉树可以通过前序序列或后序序列和中序序列构造。 二叉搜索树的中序序列是递增排序的序列,inorder = sorted(preorder)
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string. 照常前序遍历
- def deserialize(s... | Implement the Python class `CodecMe` described below.
Class description:
二叉搜索树能只够通过前序序列或后序序列构造,是因为以下两个因素: 二叉树可以通过前序序列或后序序列和中序序列构造。 二叉搜索树的中序序列是递增排序的序列,inorder = sorted(preorder)
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string. 照常前序遍历
- def deserialize(s... | 44765a7d89423b7ec2c159f70b1a6f6e446523c2 | <|skeleton|>
class CodecMe:
"""二叉搜索树能只够通过前序序列或后序序列构造,是因为以下两个因素: 二叉树可以通过前序序列或后序序列和中序序列构造。 二叉搜索树的中序序列是递增排序的序列,inorder = sorted(preorder)"""
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string. 照常前序遍历"""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CodecMe:
"""二叉搜索树能只够通过前序序列或后序序列构造,是因为以下两个因素: 二叉树可以通过前序序列或后序序列和中序序列构造。 二叉搜索树的中序序列是递增排序的序列,inorder = sorted(preorder)"""
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string. 照常前序遍历"""
res = []
stack = [root]
if not root:
return '#'
... | the_stack_v2_python_sparse | python/_0001_0500/0449_serialize-and-deserialize-bst.py | Wang-Yann/LeetCodeMe | train | 0 |
daf3b294bac699162b34977ef612deebc1874507 | [
"if not nums:\n return []\nif len(nums) == 1:\n return [nums]\nnums.sort()\nres = []\nself.helper(res, [], nums)\nreturn res",
"if not options:\n total_res.append(part_res)\n return\nsaved_e = options[0] - 1\nfor i, e in enumerate(options):\n if saved_e == e:\n continue\n saved_e = e\n ... | <|body_start_0|>
if not nums:
return []
if len(nums) == 1:
return [nums]
nums.sort()
res = []
self.helper(res, [], nums)
return res
<|end_body_0|>
<|body_start_1|>
if not options:
total_res.append(part_res)
return
... | Solution description | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Solution description"""
def permuteUnique(self, nums):
"""Solution function description"""
<|body_0|>
def helper(self, total_res, part_res, options):
"""solution helper func"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not num... | stack_v2_sparse_classes_36k_train_004243 | 973 | permissive | [
{
"docstring": "Solution function description",
"name": "permuteUnique",
"signature": "def permuteUnique(self, nums)"
},
{
"docstring": "solution helper func",
"name": "helper",
"signature": "def helper(self, total_res, part_res, options)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009429 | Implement the Python class `Solution` described below.
Class description:
Solution description
Method signatures and docstrings:
- def permuteUnique(self, nums): Solution function description
- def helper(self, total_res, part_res, options): solution helper func | Implement the Python class `Solution` described below.
Class description:
Solution description
Method signatures and docstrings:
- def permuteUnique(self, nums): Solution function description
- def helper(self, total_res, part_res, options): solution helper func
<|skeleton|>
class Solution:
"""Solution descripti... | 869ee24c50c08403b170e8f7868699185e9dfdd1 | <|skeleton|>
class Solution:
"""Solution description"""
def permuteUnique(self, nums):
"""Solution function description"""
<|body_0|>
def helper(self, total_res, part_res, options):
"""solution helper func"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""Solution description"""
def permuteUnique(self, nums):
"""Solution function description"""
if not nums:
return []
if len(nums) == 1:
return [nums]
nums.sort()
res = []
self.helper(res, [], nums)
return res
d... | the_stack_v2_python_sparse | 47.Permutations.2/1.py | cerebrumaize/leetcode | train | 0 |
d6242c1b427b95da9d6c3d4cf8e7007827d7a612 | [
"super().__init__()\nself.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)\nself.dropout = nn.Dropout(dropout)\nself.linear1 = nn.Linear(d_model, dim_feedforward)\nself.linear2 = nn.Linear(dim_feedforward, d_model)\nself.norm1 = nn.LayerNorm(d_model)\nself.norm2 = nn.LayerNorm(d_model)\nself.dropo... | <|body_start_0|>
super().__init__()
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
self.dropout = nn.Dropout(dropout)
self.linear1 = nn.Linear(d_model, dim_feedforward)
self.linear2 = nn.Linear(dim_feedforward, d_model)
self.norm1 = nn.LayerNorm(d... | TransformerEncoderLayer is made up of self-attn and feedforward. This standard encoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need. In Advances in Neu... | TransformerEncoderLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerEncoderLayer:
"""TransformerEncoderLayer is made up of self-attn and feedforward. This standard encoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhin. ... | stack_v2_sparse_classes_36k_train_004244 | 3,033 | no_license | [
{
"docstring": "Initialize a TransformerEncoderLayer. Parameters ---------- d_model : int The number of expected features in the input. n_head : int The number of heads in the multiheadattention models. dim_feedforward : int, optional The dimension of the feedforward network (default=2048). dropout : float, opt... | 2 | stack_v2_sparse_classes_30k_val_001096 | Implement the Python class `TransformerEncoderLayer` described below.
Class description:
TransformerEncoderLayer is made up of self-attn and feedforward. This standard encoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez... | Implement the Python class `TransformerEncoderLayer` described below.
Class description:
TransformerEncoderLayer is made up of self-attn and feedforward. This standard encoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez... | 8b9fadded0e9eed7e16bf6ce6c3235f3ad5132e8 | <|skeleton|>
class TransformerEncoderLayer:
"""TransformerEncoderLayer is made up of self-attn and feedforward. This standard encoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhin. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformerEncoderLayer:
"""TransformerEncoderLayer is made up of self-attn and feedforward. This standard encoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhin. 2017. Attenti... | the_stack_v2_python_sparse | models/cnn_dm/teacher/encoder/layers.3/source.py | asappresearch/imitkd | train | 3 |
e7b66866e0fb1494622909c40c9cd60965d6ac36 | [
"month = datetime.date.today().strftime('%B')\nyear = datetime.date.today().year\ndate_ = month + ' ' + str(year)\nmonth_no = datetime.date.today().month\nFiscal = Pool().get('account.fiscalyear')\ncompany = Transaction().context.get('company')\ncurrent_fiscal_year = Fiscal.find(company)\nPayslip = Pool().get('hr.p... | <|body_start_0|>
month = datetime.date.today().strftime('%B')
year = datetime.date.today().year
date_ = month + ' ' + str(year)
month_no = datetime.date.today().month
Fiscal = Pool().get('account.fiscalyear')
company = Transaction().context.get('company')
current_... | Salary Structure | SalaryStructure | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SalaryStructure:
"""Salary Structure"""
def generate_pay_slip(self, employee, contract, payslip_batch=None):
"""Generate a pay slip :return: A record of HR Payslip"""
<|body_0|>
def generate_pay_slip_for_ytd(self, employee, contract, given_month, payslip_batch=None):
... | stack_v2_sparse_classes_36k_train_004245 | 20,718 | no_license | [
{
"docstring": "Generate a pay slip :return: A record of HR Payslip",
"name": "generate_pay_slip",
"signature": "def generate_pay_slip(self, employee, contract, payslip_batch=None)"
},
{
"docstring": "Generate a pay slip :return: A record of HR Payslip",
"name": "generate_pay_slip_for_ytd",
... | 2 | stack_v2_sparse_classes_30k_test_001040 | Implement the Python class `SalaryStructure` described below.
Class description:
Salary Structure
Method signatures and docstrings:
- def generate_pay_slip(self, employee, contract, payslip_batch=None): Generate a pay slip :return: A record of HR Payslip
- def generate_pay_slip_for_ytd(self, employee, contract, given... | Implement the Python class `SalaryStructure` described below.
Class description:
Salary Structure
Method signatures and docstrings:
- def generate_pay_slip(self, employee, contract, payslip_batch=None): Generate a pay slip :return: A record of HR Payslip
- def generate_pay_slip_for_ytd(self, employee, contract, given... | cd392bf0e80d71c4742568e9c1dd5e5211da56a9 | <|skeleton|>
class SalaryStructure:
"""Salary Structure"""
def generate_pay_slip(self, employee, contract, payslip_batch=None):
"""Generate a pay slip :return: A record of HR Payslip"""
<|body_0|>
def generate_pay_slip_for_ytd(self, employee, contract, given_month, payslip_batch=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SalaryStructure:
"""Salary Structure"""
def generate_pay_slip(self, employee, contract, payslip_batch=None):
"""Generate a pay slip :return: A record of HR Payslip"""
month = datetime.date.today().strftime('%B')
year = datetime.date.today().year
date_ = month + ' ' + str(y... | the_stack_v2_python_sparse | src/modules/customised/payroll_test_2/payroll/hr_payroll/hr_payslip.py | kakamble-aiims/work | train | 0 |
6cea090446aead390d1b10208f0bdb0a67c118c9 | [
"lines = {}\nfor i in range(0, len(height)):\n h = height[i]\n if h in lines:\n lines[h][1] = i\n else:\n lines[h] = [i, i]\nr = 0\nstart, stop = (len(height), -1)\nfor h in sorted(lines.keys(), reverse=True):\n if h * len(height) <= r:\n break\n start = min(start, lines[h][0])\n... | <|body_start_0|>
lines = {}
for i in range(0, len(height)):
h = height[i]
if h in lines:
lines[h][1] = i
else:
lines[h] = [i, i]
r = 0
start, stop = (len(height), -1)
for h in sorted(lines.keys(), reverse=True):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def maxArea1(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
lines = {}
for i in range(0, len(hei... | stack_v2_sparse_classes_36k_train_004246 | 3,050 | no_license | [
{
"docstring": ":type height: List[int] :rtype: int",
"name": "maxArea",
"signature": "def maxArea(self, height)"
},
{
"docstring": ":type height: List[int] :rtype: int",
"name": "maxArea1",
"signature": "def maxArea1(self, height)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea(self, height): :type height: List[int] :rtype: int
- def maxArea1(self, height): :type height: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea(self, height): :type height: List[int] :rtype: int
- def maxArea1(self, height): :type height: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxArea(se... | bbd0a26b2d301b19005fc7368a25732d01c8ae2b | <|skeleton|>
class Solution:
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def maxArea1(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
lines = {}
for i in range(0, len(height)):
h = height[i]
if h in lines:
lines[h][1] = i
else:
lines[h] = [i, i]
r = 0
start... | the_stack_v2_python_sparse | problems_100/011_maxArea.py | txwjj33/leetcode | train | 0 | |
6ac0632964054b954bb4d0c09aa247265ebd17b9 | [
"if '_xml_ns' in kwargs:\n self._xml_ns = kwargs['_xml_ns']\nif '_xml_ns_key' in kwargs:\n self._xml_ns_key = kwargs['_xml_ns_key']\nself.PixelType = PixelType\nself.NumBands = NumBands\nself.DefaultBandDisplay = DefaultBandDisplay\nself.NonInteractiveProcessing = NonInteractiveProcessing\nself.InteractivePro... | <|body_start_0|>
if '_xml_ns' in kwargs:
self._xml_ns = kwargs['_xml_ns']
if '_xml_ns_key' in kwargs:
self._xml_ns_key = kwargs['_xml_ns_key']
self.PixelType = PixelType
self.NumBands = NumBands
self.DefaultBandDisplay = DefaultBandDisplay
self.Non... | ProductDisplayType | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductDisplayType:
def __init__(self, PixelType=None, NumBands=1, DefaultBandDisplay=None, NonInteractiveProcessing=None, InteractiveProcessing=None, DisplayExtensions=None, **kwargs):
"""Parameters ---------- PixelType : PixelTypeType NumBands : int DefaultBandDisplay : int|None NonInt... | stack_v2_sparse_classes_36k_train_004247 | 27,598 | permissive | [
{
"docstring": "Parameters ---------- PixelType : PixelTypeType NumBands : int DefaultBandDisplay : int|None NonInteractiveProcessing : List[NonInteractiveProcessingType] InteractiveProcessing : List[InteractiveProcessingType] DisplayExtensions : ParametersCollection|dict kwargs",
"name": "__init__",
"s... | 2 | null | Implement the Python class `ProductDisplayType` described below.
Class description:
Implement the ProductDisplayType class.
Method signatures and docstrings:
- def __init__(self, PixelType=None, NumBands=1, DefaultBandDisplay=None, NonInteractiveProcessing=None, InteractiveProcessing=None, DisplayExtensions=None, **k... | Implement the Python class `ProductDisplayType` described below.
Class description:
Implement the ProductDisplayType class.
Method signatures and docstrings:
- def __init__(self, PixelType=None, NumBands=1, DefaultBandDisplay=None, NonInteractiveProcessing=None, InteractiveProcessing=None, DisplayExtensions=None, **k... | de1b1886f161a83b6c89aadc7a2c7cfc4892ef81 | <|skeleton|>
class ProductDisplayType:
def __init__(self, PixelType=None, NumBands=1, DefaultBandDisplay=None, NonInteractiveProcessing=None, InteractiveProcessing=None, DisplayExtensions=None, **kwargs):
"""Parameters ---------- PixelType : PixelTypeType NumBands : int DefaultBandDisplay : int|None NonInt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProductDisplayType:
def __init__(self, PixelType=None, NumBands=1, DefaultBandDisplay=None, NonInteractiveProcessing=None, InteractiveProcessing=None, DisplayExtensions=None, **kwargs):
"""Parameters ---------- PixelType : PixelTypeType NumBands : int DefaultBandDisplay : int|None NonInteractiveProces... | the_stack_v2_python_sparse | sarpy/io/product/sidd2_elements/Display.py | ngageoint/sarpy | train | 192 | |
5fca7db2c06a0ad68b6e70dfb0e5cab039fb98d5 | [
"es_config = es_router.merge_es_config(destination_config)\nif not isinstance(data, (list, tuple)):\n data = [data]\n_param = param.get('fields') if param else {}\ninput_param = dict(data[0], **_param)\nes_config = es_router.route(es_config, input_param=input_param)\noperation = es_config.get('operation', 'creat... | <|body_start_0|>
es_config = es_router.merge_es_config(destination_config)
if not isinstance(data, (list, tuple)):
data = [data]
_param = param.get('fields') if param else {}
input_param = dict(data[0], **_param)
es_config = es_router.route(es_config, input_param=inpu... | 数据流目的地为Elasticsearch | ElasticSearchDestination | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElasticSearchDestination:
"""数据流目的地为Elasticsearch"""
def push(self, destination_config, data, param=None):
"""将数据推到ES中,数据流的最后一步 :param destination_config: :param data: :param param :return:"""
<|body_0|>
def clear(self, destination_config, data, param=None):
"""清... | stack_v2_sparse_classes_36k_train_004248 | 9,641 | permissive | [
{
"docstring": "将数据推到ES中,数据流的最后一步 :param destination_config: :param data: :param param :return:",
"name": "push",
"signature": "def push(self, destination_config, data, param=None)"
},
{
"docstring": "清除掉ES数据源中得所有数据 :param destination_config: :param data: :return:",
"name": "clear",
"sig... | 3 | stack_v2_sparse_classes_30k_test_000270 | Implement the Python class `ElasticSearchDestination` described below.
Class description:
数据流目的地为Elasticsearch
Method signatures and docstrings:
- def push(self, destination_config, data, param=None): 将数据推到ES中,数据流的最后一步 :param destination_config: :param data: :param param :return:
- def clear(self, destination_config,... | Implement the Python class `ElasticSearchDestination` described below.
Class description:
数据流目的地为Elasticsearch
Method signatures and docstrings:
- def push(self, destination_config, data, param=None): 将数据推到ES中,数据流的最后一步 :param destination_config: :param data: :param param :return:
- def clear(self, destination_config,... | a72b4e4d78b4375f69887e75abcc1e6a6782c551 | <|skeleton|>
class ElasticSearchDestination:
"""数据流目的地为Elasticsearch"""
def push(self, destination_config, data, param=None):
"""将数据推到ES中,数据流的最后一步 :param destination_config: :param data: :param param :return:"""
<|body_0|>
def clear(self, destination_config, data, param=None):
"""清... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ElasticSearchDestination:
"""数据流目的地为Elasticsearch"""
def push(self, destination_config, data, param=None):
"""将数据推到ES中,数据流的最后一步 :param destination_config: :param data: :param param :return:"""
es_config = es_router.merge_es_config(destination_config)
if not isinstance(data, (list,... | the_stack_v2_python_sparse | river/destination.py | RitterHou/search_platform | train | 0 |
1e810e571d92b4e125d73052b8bc26950be63694 | [
"pump = Pump('127.0.0.1', 8000)\npump.set_state = MagicMock(return_value=True)\nself.decider = Decider(100, 10)\nself.actions = {'PUMP_IN': pump.PUMP_IN, 'PUMP_OUT': pump.PUMP_OUT, 'PUMP_OFF': pump.PUMP_OFF}\nassert self.decider.decide(50, 'PUMP_IN', self.actions) == 1",
"pump = Pump('127.0.0.1', 8000)\npump.set_... | <|body_start_0|>
pump = Pump('127.0.0.1', 8000)
pump.set_state = MagicMock(return_value=True)
self.decider = Decider(100, 10)
self.actions = {'PUMP_IN': pump.PUMP_IN, 'PUMP_OUT': pump.PUMP_OUT, 'PUMP_OFF': pump.PUMP_OFF}
assert self.decider.decide(50, 'PUMP_IN', self.actions) == ... | Unit tests for the Decider class | DeciderTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeciderTests:
"""Unit tests for the Decider class"""
def test_decider1(self):
"""Does it return 1 to pump in when below margins?"""
<|body_0|>
def test_decider2(self):
"""Does it return 0 to shut off when within margins?"""
<|body_1|>
def test_decide... | stack_v2_sparse_classes_36k_train_004249 | 2,419 | no_license | [
{
"docstring": "Does it return 1 to pump in when below margins?",
"name": "test_decider1",
"signature": "def test_decider1(self)"
},
{
"docstring": "Does it return 0 to shut off when within margins?",
"name": "test_decider2",
"signature": "def test_decider2(self)"
},
{
"docstring... | 3 | null | Implement the Python class `DeciderTests` described below.
Class description:
Unit tests for the Decider class
Method signatures and docstrings:
- def test_decider1(self): Does it return 1 to pump in when below margins?
- def test_decider2(self): Does it return 0 to shut off when within margins?
- def test_decider3(s... | Implement the Python class `DeciderTests` described below.
Class description:
Unit tests for the Decider class
Method signatures and docstrings:
- def test_decider1(self): Does it return 1 to pump in when below margins?
- def test_decider2(self): Does it return 0 to shut off when within margins?
- def test_decider3(s... | f0a6d8df31d28f0fecf32add03a05285e58aac22 | <|skeleton|>
class DeciderTests:
"""Unit tests for the Decider class"""
def test_decider1(self):
"""Does it return 1 to pump in when below margins?"""
<|body_0|>
def test_decider2(self):
"""Does it return 0 to shut off when within margins?"""
<|body_1|>
def test_decide... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeciderTests:
"""Unit tests for the Decider class"""
def test_decider1(self):
"""Does it return 1 to pump in when below margins?"""
pump = Pump('127.0.0.1', 8000)
pump.set_state = MagicMock(return_value=True)
self.decider = Decider(100, 10)
self.actions = {'PUMP_IN... | the_stack_v2_python_sparse | students/Harry_Maher/Python220B/session06/water-regulation/waterregulation/test.py | UWPCE-PythonCert-ClassRepos/Wi2018-Classroom | train | 3 |
a74235a62df25111fafe435e8cc23caa7f41d10c | [
"super().__init__(width, height)\nself.ball = Ball()\nself.paddle = Paddle()\nself.score = 0\nself.holding_left = False\nself.holding_right = False\narcade.set_background_color(arcade.color.WHITE)",
"arcade.start_render()\nself.ball.draw()\nself.paddle.draw()"
] | <|body_start_0|>
super().__init__(width, height)
self.ball = Ball()
self.paddle = Paddle()
self.score = 0
self.holding_left = False
self.holding_right = False
arcade.set_background_color(arcade.color.WHITE)
<|end_body_0|>
<|body_start_1|>
arcade.start_ren... | This class handles all the game callbacks and interaction It assumes the following classes exist: Point Velocity Ball Paddle This class will then call the appropriate functions of each of the above classes. You are welcome to modify anything in this class, but should not have to if you don't want to. | Pong | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pong:
"""This class handles all the game callbacks and interaction It assumes the following classes exist: Point Velocity Ball Paddle This class will then call the appropriate functions of each of the above classes. You are welcome to modify anything in this class, but should not have to if you d... | stack_v2_sparse_classes_36k_train_004250 | 2,585 | no_license | [
{
"docstring": "Sets up the initial conditions of the game :param width: Screen width :param height: Screen height",
"name": "__init__",
"signature": "def __init__(self, width, height)"
},
{
"docstring": "Called automatically by the arcade framework. Handles the responsiblity of drawing all elem... | 2 | stack_v2_sparse_classes_30k_train_001957 | Implement the Python class `Pong` described below.
Class description:
This class handles all the game callbacks and interaction It assumes the following classes exist: Point Velocity Ball Paddle This class will then call the appropriate functions of each of the above classes. You are welcome to modify anything in this... | Implement the Python class `Pong` described below.
Class description:
This class handles all the game callbacks and interaction It assumes the following classes exist: Point Velocity Ball Paddle This class will then call the appropriate functions of each of the above classes. You are welcome to modify anything in this... | 14ed7cd8268e2810a6434d0a0ad0f1357e4df5a4 | <|skeleton|>
class Pong:
"""This class handles all the game callbacks and interaction It assumes the following classes exist: Point Velocity Ball Paddle This class will then call the appropriate functions of each of the above classes. You are welcome to modify anything in this class, but should not have to if you d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pong:
"""This class handles all the game callbacks and interaction It assumes the following classes exist: Point Velocity Ball Paddle This class will then call the appropriate functions of each of the above classes. You are welcome to modify anything in this class, but should not have to if you don't want to.... | the_stack_v2_python_sparse | python/cs241/w05/assignment/pong_practice.py | robertggovias/robertgovia.github.io | train | 0 |
ba28ecd2c4f99542cfa2330745801482f67ad76f | [
"appliance = ElectricAppliances('1111', 'Computer', '$800', '$100', 'Dell', '120')\nself.assertEqual('1111', appliance.product_code)\nself.assertEqual('Computer', appliance.description)\nself.assertEqual('$800', appliance.market_price)\nself.assertEqual('$100', appliance.rental_price)\nself.assertEqual('Dell', appl... | <|body_start_0|>
appliance = ElectricAppliances('1111', 'Computer', '$800', '$100', 'Dell', '120')
self.assertEqual('1111', appliance.product_code)
self.assertEqual('Computer', appliance.description)
self.assertEqual('$800', appliance.market_price)
self.assertEqual('$100', applia... | Unit tests the ElectricAppliances class | ElectricAppliancesTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElectricAppliancesTest:
"""Unit tests the ElectricAppliances class"""
def test_add_electronic(self):
"""creates an object of the ElectricAppliendes class"""
<|body_0|>
def test_return_dict(self):
"""calls the return_as_dictionary function on the ElectricAppliende... | stack_v2_sparse_classes_36k_train_004251 | 10,292 | no_license | [
{
"docstring": "creates an object of the ElectricAppliendes class",
"name": "test_add_electronic",
"signature": "def test_add_electronic(self)"
},
{
"docstring": "calls the return_as_dictionary function on the ElectricAppliendes class",
"name": "test_return_dict",
"signature": "def test_... | 2 | null | Implement the Python class `ElectricAppliancesTest` described below.
Class description:
Unit tests the ElectricAppliances class
Method signatures and docstrings:
- def test_add_electronic(self): creates an object of the ElectricAppliendes class
- def test_return_dict(self): calls the return_as_dictionary function on ... | Implement the Python class `ElectricAppliancesTest` described below.
Class description:
Unit tests the ElectricAppliances class
Method signatures and docstrings:
- def test_add_electronic(self): creates an object of the ElectricAppliendes class
- def test_return_dict(self): calls the return_as_dictionary function on ... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class ElectricAppliancesTest:
"""Unit tests the ElectricAppliances class"""
def test_add_electronic(self):
"""creates an object of the ElectricAppliendes class"""
<|body_0|>
def test_return_dict(self):
"""calls the return_as_dictionary function on the ElectricAppliende... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ElectricAppliancesTest:
"""Unit tests the ElectricAppliances class"""
def test_add_electronic(self):
"""creates an object of the ElectricAppliendes class"""
appliance = ElectricAppliances('1111', 'Computer', '$800', '$100', 'Dell', '120')
self.assertEqual('1111', appliance.product... | the_stack_v2_python_sparse | students/David_Baylor/lesson01/Assignment/test_unit.py | JavaRod/SP_Python220B_2019 | train | 1 |
1754f5acdf34df7b0963316bcc2a7a2d44538469 | [
"super().__init__()\nself.version = version\nself.ihl = ihl\nself.dscp = dscp\nself.ecn = ecn\nself.length = length\nself.identification = identification\nself.flags = flags\nself.offset = offset\nself.ttl = ttl\nself.protocol = protocol\nself.checksum = checksum\nself.source = source\nself.destination = destinatio... | <|body_start_0|>
super().__init__()
self.version = version
self.ihl = ihl
self.dscp = dscp
self.ecn = ecn
self.length = length
self.identification = identification
self.flags = flags
self.offset = offset
self.ttl = ttl
self.protocol... | IPv4 packet "struct". Contains all fields of an IP version 4 packet header, plus the upper layer content as binary data. Some of the fields were merged together because of their size being inferior to 8 bits. They are represented as a single class attribute, but pack/unpack methods will take into account the values in ... | IPv4 | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IPv4:
"""IPv4 packet "struct". Contains all fields of an IP version 4 packet header, plus the upper layer content as binary data. Some of the fields were merged together because of their size being inferior to 8 bits. They are represented as a single class attribute, but pack/unpack methods will ... | stack_v2_sparse_classes_36k_train_004252 | 27,921 | permissive | [
{
"docstring": "Create an IPv4 with the parameters below. Args: version (int): IP protocol version. Defaults to 4. ihl (int): Internet Header Length. Default is 5. dscp (int): Differentiated Service Code Point. Defaults to 0. ecn (int): Explicit Congestion Notification. Defaults to 0. length (int): IP packet le... | 4 | null | Implement the Python class `IPv4` described below.
Class description:
IPv4 packet "struct". Contains all fields of an IP version 4 packet header, plus the upper layer content as binary data. Some of the fields were merged together because of their size being inferior to 8 bits. They are represented as a single class a... | Implement the Python class `IPv4` described below.
Class description:
IPv4 packet "struct". Contains all fields of an IP version 4 packet header, plus the upper layer content as binary data. Some of the fields were merged together because of their size being inferior to 8 bits. They are represented as a single class a... | 89940bed83f8e792f5ed5c9f12346016cd380d6f | <|skeleton|>
class IPv4:
"""IPv4 packet "struct". Contains all fields of an IP version 4 packet header, plus the upper layer content as binary data. Some of the fields were merged together because of their size being inferior to 8 bits. They are represented as a single class attribute, but pack/unpack methods will ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IPv4:
"""IPv4 packet "struct". Contains all fields of an IP version 4 packet header, plus the upper layer content as binary data. Some of the fields were merged together because of their size being inferior to 8 bits. They are represented as a single class attribute, but pack/unpack methods will take into acc... | the_stack_v2_python_sparse | pyof/foundation/network_types.py | kytos/python-openflow | train | 53 |
463db3f60eefbe5236d6486c6634e6b8d14a5c2b | [
"self.solution = nan\nself.muhat = full(levels, inf)\nself.sighat = full(levels, inf)\nself.t_eval = zeros(levels)\nself.n = tile(n_init, levels).astype(float)\nself.n_total = 0\nself.confid_int = array([-inf, inf])\nsuper().__init__()",
"for i in range(len(true_measure)):\n t_start = process_time()\n set_x... | <|body_start_0|>
self.solution = nan
self.muhat = full(levels, inf)
self.sighat = full(levels, inf)
self.t_eval = zeros(levels)
self.n = tile(n_init, levels).astype(float)
self.n_total = 0
self.confid_int = array([-inf, inf])
super().__init__()
<|end_body_... | Accumulated data for IIDDistribution calculations, and store the sample mean and variance of integrand values | MeanVarData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MeanVarData:
"""Accumulated data for IIDDistribution calculations, and store the sample mean and variance of integrand values"""
def __init__(self, levels, n_init):
"""Initialize data instance Args: levels (int): number of integrands n_init (int): initial number of samples"""
... | stack_v2_sparse_classes_36k_train_004253 | 1,918 | no_license | [
{
"docstring": "Initialize data instance Args: levels (int): number of integrands n_init (int): initial number of samples",
"name": "__init__",
"signature": "def __init__(self, levels, n_init)"
},
{
"docstring": "Update data Args: integrand (Integrand): an instance of Integrand true_measure (Tru... | 2 | stack_v2_sparse_classes_30k_train_011497 | Implement the Python class `MeanVarData` described below.
Class description:
Accumulated data for IIDDistribution calculations, and store the sample mean and variance of integrand values
Method signatures and docstrings:
- def __init__(self, levels, n_init): Initialize data instance Args: levels (int): number of inte... | Implement the Python class `MeanVarData` described below.
Class description:
Accumulated data for IIDDistribution calculations, and store the sample mean and variance of integrand values
Method signatures and docstrings:
- def __init__(self, levels, n_init): Initialize data instance Args: levels (int): number of inte... | 9f37eb67f74c4b1a4ccfb5547a2b284cb5897d37 | <|skeleton|>
class MeanVarData:
"""Accumulated data for IIDDistribution calculations, and store the sample mean and variance of integrand values"""
def __init__(self, levels, n_init):
"""Initialize data instance Args: levels (int): number of integrands n_init (int): initial number of samples"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MeanVarData:
"""Accumulated data for IIDDistribution calculations, and store the sample mean and variance of integrand values"""
def __init__(self, levels, n_init):
"""Initialize data instance Args: levels (int): number of integrands n_init (int): initial number of samples"""
self.solutio... | the_stack_v2_python_sparse | python_prototype/qmcpy/accum_data/mean_var_data.py | jagadeesr/QMCSoftware | train | 0 |
e7c1fb90c281338f6e931ca65df2a9696017fd46 | [
"import bisect\n\ndef Count(num, m, n):\n count = 0\n ans = 0\n for i in range(1, m + 1):\n a = min(num // i, n)\n count += a\n ans = max(ans, a * i)\n return (count, ans)\nstart, end = (1, m * n)\nresult = []\ndicts = {}\nwhile start <= end:\n mid = (start + end) // 2\n c, an... | <|body_start_0|>
import bisect
def Count(num, m, n):
count = 0
ans = 0
for i in range(1, m + 1):
a = min(num // i, n)
count += a
ans = max(ans, a * i)
return (count, ans)
start, end = (1, m * n)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findKthNumber(self, m, n, k):
""":type m: int :type n: int :type k: int :rtype: int"""
<|body_0|>
def findKthNumber_1(self, m, n, k):
""":type m: int :type n: int :type k: int :rtype: int 1858ms"""
<|body_1|>
def findKthNumber_2(self, m, n,... | stack_v2_sparse_classes_36k_train_004254 | 3,475 | no_license | [
{
"docstring": ":type m: int :type n: int :type k: int :rtype: int",
"name": "findKthNumber",
"signature": "def findKthNumber(self, m, n, k)"
},
{
"docstring": ":type m: int :type n: int :type k: int :rtype: int 1858ms",
"name": "findKthNumber_1",
"signature": "def findKthNumber_1(self, ... | 3 | stack_v2_sparse_classes_30k_train_009216 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findKthNumber(self, m, n, k): :type m: int :type n: int :type k: int :rtype: int
- def findKthNumber_1(self, m, n, k): :type m: int :type n: int :type k: int :rtype: int 1858... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findKthNumber(self, m, n, k): :type m: int :type n: int :type k: int :rtype: int
- def findKthNumber_1(self, m, n, k): :type m: int :type n: int :type k: int :rtype: int 1858... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def findKthNumber(self, m, n, k):
""":type m: int :type n: int :type k: int :rtype: int"""
<|body_0|>
def findKthNumber_1(self, m, n, k):
""":type m: int :type n: int :type k: int :rtype: int 1858ms"""
<|body_1|>
def findKthNumber_2(self, m, n,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findKthNumber(self, m, n, k):
""":type m: int :type n: int :type k: int :rtype: int"""
import bisect
def Count(num, m, n):
count = 0
ans = 0
for i in range(1, m + 1):
a = min(num // i, n)
count += a
... | the_stack_v2_python_sparse | KthSmallestNumberInMultiplicationTable_HARD_668.py | 953250587/leetcode-python | train | 2 | |
c7c9f5bd89577ea8169673b5f7153cda6143df35 | [
"self._outFile = outFile\nself._holdback_time = holdback_time\nself._last_flush_time = None\nself._buffer = []\nself._draw_progressbar = draw_progressbar\nself._current_ticks = 0\nself._max_ticks = max_ticks",
"self._buffer.append(data)\nself._current_ticks += 1\nflush = False\nif self._last_flush_time is None or... | <|body_start_0|>
self._outFile = outFile
self._holdback_time = holdback_time
self._last_flush_time = None
self._buffer = []
self._draw_progressbar = draw_progressbar
self._current_ticks = 0
self._max_ticks = max_ticks
<|end_body_0|>
<|body_start_1|>
self.... | ThrottledOut | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThrottledOut:
def __init__(self, outFile, holdback_time=None, max_ticks=0, draw_progressbar=None):
"""holdback_time: float, 1.0 = 1 second"""
<|body_0|>
def write(self, data):
"""only put to stdout every now and then"""
<|body_1|>
def flush(self, draw_pr... | stack_v2_sparse_classes_36k_train_004255 | 25,789 | permissive | [
{
"docstring": "holdback_time: float, 1.0 = 1 second",
"name": "__init__",
"signature": "def __init__(self, outFile, holdback_time=None, max_ticks=0, draw_progressbar=None)"
},
{
"docstring": "only put to stdout every now and then",
"name": "write",
"signature": "def write(self, data)"
... | 3 | stack_v2_sparse_classes_30k_train_001540 | Implement the Python class `ThrottledOut` described below.
Class description:
Implement the ThrottledOut class.
Method signatures and docstrings:
- def __init__(self, outFile, holdback_time=None, max_ticks=0, draw_progressbar=None): holdback_time: float, 1.0 = 1 second
- def write(self, data): only put to stdout ever... | Implement the Python class `ThrottledOut` described below.
Class description:
Implement the ThrottledOut class.
Method signatures and docstrings:
- def __init__(self, outFile, holdback_time=None, max_ticks=0, draw_progressbar=None): holdback_time: float, 1.0 = 1 second
- def write(self, data): only put to stdout ever... | 74ece8a050851ab7163b3ca166a37b98348602d8 | <|skeleton|>
class ThrottledOut:
def __init__(self, outFile, holdback_time=None, max_ticks=0, draw_progressbar=None):
"""holdback_time: float, 1.0 = 1 second"""
<|body_0|>
def write(self, data):
"""only put to stdout every now and then"""
<|body_1|>
def flush(self, draw_pr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThrottledOut:
def __init__(self, outFile, holdback_time=None, max_ticks=0, draw_progressbar=None):
"""holdback_time: float, 1.0 = 1 second"""
self._outFile = outFile
self._holdback_time = holdback_time
self._last_flush_time = None
self._buffer = []
self._draw_pr... | the_stack_v2_python_sparse | Lib/fontbakery/reporters/terminal.py | chrissimpkins/fontbakery | train | 2 | |
0083d17bd870b43dd317f06dd11081c5cd423232 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn WorkbookRangeFormat()",
"from .entity import Entity\nfrom .workbook_format_protection import WorkbookFormatProtection\nfrom .workbook_range_border import WorkbookRangeBorder\nfrom .workbook_range_fill import WorkbookRangeFill\nfrom .wo... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return WorkbookRangeFormat()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .workbook_format_protection import WorkbookFormatProtection
from .workbook_range_border impo... | WorkbookRangeFormat | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkbookRangeFormat:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WorkbookRangeFormat:
"""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 ob... | stack_v2_sparse_classes_36k_train_004256 | 5,372 | 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: WorkbookRangeFormat",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator... | 3 | null | Implement the Python class `WorkbookRangeFormat` described below.
Class description:
Implement the WorkbookRangeFormat class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WorkbookRangeFormat: Creates a new instance of the appropriate class based on d... | Implement the Python class `WorkbookRangeFormat` described below.
Class description:
Implement the WorkbookRangeFormat class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WorkbookRangeFormat: Creates a new instance of the appropriate class based on d... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class WorkbookRangeFormat:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WorkbookRangeFormat:
"""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 ob... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkbookRangeFormat:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> WorkbookRangeFormat:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ... | the_stack_v2_python_sparse | msgraph/generated/models/workbook_range_format.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
c9a38b5db482db29a62080a8ff5ab99fd15d7570 | [
"name = 'git ' + args[0]\nif args[0] == 'config' and (not args[1].startswith('-')):\n name += ' ' + args[1]\nif 'cwd' not in kwargs:\n kwargs.setdefault('cwd', self.m.path.checkout())\nreturn self.m.step(name, ['git'] + list(args), **kwargs)",
"if not dir_path:\n dir_path = url.rsplit('/', 1)[-1]\n if... | <|body_start_0|>
name = 'git ' + args[0]
if args[0] == 'config' and (not args[1].startswith('-')):
name += ' ' + args[1]
if 'cwd' not in kwargs:
kwargs.setdefault('cwd', self.m.path.checkout())
return self.m.step(name, ['git'] + list(args), **kwargs)
<|end_body_0|... | GitApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GitApi:
def command(self, *args, **kwargs):
"""Return a git command step."""
<|body_0|>
def checkout(self, url, dir_path=None, branch='master', recursive=False, keep_paths=None):
"""Returns an iterable of steps to perform a full git checkout. Args: url (string): url ... | stack_v2_sparse_classes_36k_train_004257 | 2,325 | no_license | [
{
"docstring": "Return a git command step.",
"name": "command",
"signature": "def command(self, *args, **kwargs)"
},
{
"docstring": "Returns an iterable of steps to perform a full git checkout. Args: url (string): url of remote repo to use as upstream dir_path (string): optional directory to clo... | 2 | null | Implement the Python class `GitApi` described below.
Class description:
Implement the GitApi class.
Method signatures and docstrings:
- def command(self, *args, **kwargs): Return a git command step.
- def checkout(self, url, dir_path=None, branch='master', recursive=False, keep_paths=None): Returns an iterable of ste... | Implement the Python class `GitApi` described below.
Class description:
Implement the GitApi class.
Method signatures and docstrings:
- def command(self, *args, **kwargs): Return a git command step.
- def checkout(self, url, dir_path=None, branch='master', recursive=False, keep_paths=None): Returns an iterable of ste... | 516718f9b7b95c4280257b2d319638d4728a90e1 | <|skeleton|>
class GitApi:
def command(self, *args, **kwargs):
"""Return a git command step."""
<|body_0|>
def checkout(self, url, dir_path=None, branch='master', recursive=False, keep_paths=None):
"""Returns an iterable of steps to perform a full git checkout. Args: url (string): url ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GitApi:
def command(self, *args, **kwargs):
"""Return a git command step."""
name = 'git ' + args[0]
if args[0] == 'config' and (not args[1].startswith('-')):
name += ' ' + args[1]
if 'cwd' not in kwargs:
kwargs.setdefault('cwd', self.m.path.checkout())
... | the_stack_v2_python_sparse | build/scripts/slave/recipe_modules/git/api.py | mhcchang/chromium30 | train | 0 | |
744b85f377a0d84048fbf5c614a594194706623f | [
"processed = 0\nfor net in queryset:\n net.AddDomains(1)\n processed += 1\nself.message_user(request, '%s added.' % GetMessageBit(processed))",
"processed = 0\nfor net in queryset:\n net.AddDomains()\n processed += 1\nself.message_user(request, '%s processed.' % GetMessageBit(processed))",
"processe... | <|body_start_0|>
processed = 0
for net in queryset:
net.AddDomains(1)
processed += 1
self.message_user(request, '%s added.' % GetMessageBit(processed))
<|end_body_0|>
<|body_start_1|>
processed = 0
for net in queryset:
net.AddDomains()
... | NetAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetAdmin:
def AddDomains(self, request, queryset):
"""Добавляем в сеть один домен"""
<|body_0|>
def AddDomainsAll(self, request, queryset):
"""Добавляем в сеть один домен"""
<|body_1|>
def GenerateDoorways(self, request, queryset):
"""Генерируем ... | stack_v2_sparse_classes_36k_train_004258 | 29,849 | no_license | [
{
"docstring": "Добавляем в сеть один домен",
"name": "AddDomains",
"signature": "def AddDomains(self, request, queryset)"
},
{
"docstring": "Добавляем в сеть один домен",
"name": "AddDomainsAll",
"signature": "def AddDomainsAll(self, request, queryset)"
},
{
"docstring": "Генери... | 6 | stack_v2_sparse_classes_30k_val_001191 | Implement the Python class `NetAdmin` described below.
Class description:
Implement the NetAdmin class.
Method signatures and docstrings:
- def AddDomains(self, request, queryset): Добавляем в сеть один домен
- def AddDomainsAll(self, request, queryset): Добавляем в сеть один домен
- def GenerateDoorways(self, reques... | Implement the Python class `NetAdmin` described below.
Class description:
Implement the NetAdmin class.
Method signatures and docstrings:
- def AddDomains(self, request, queryset): Добавляем в сеть один домен
- def AddDomainsAll(self, request, queryset): Добавляем в сеть один домен
- def GenerateDoorways(self, reques... | d2771bf04aa187dda6d468883a5a167237589369 | <|skeleton|>
class NetAdmin:
def AddDomains(self, request, queryset):
"""Добавляем в сеть один домен"""
<|body_0|>
def AddDomainsAll(self, request, queryset):
"""Добавляем в сеть один домен"""
<|body_1|>
def GenerateDoorways(self, request, queryset):
"""Генерируем ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NetAdmin:
def AddDomains(self, request, queryset):
"""Добавляем в сеть один домен"""
processed = 0
for net in queryset:
net.AddDomains(1)
processed += 1
self.message_user(request, '%s added.' % GetMessageBit(processed))
def AddDomainsAll(self, reque... | the_stack_v2_python_sparse | doorsadmin/admin.py | cash2one/doorscenter | train | 0 | |
48c24ab6ba1f56814b406a9ddbcdf1235913f441 | [
"msg = cast(DefaultMessage, msg)\ndefault_msg = default_pb2.DefaultMessage()\ndefault_msg.message_id = msg.message_id\ndialogue_reference = msg.dialogue_reference\ndefault_msg.dialogue_starter_reference = dialogue_reference[0]\ndefault_msg.dialogue_responder_reference = dialogue_reference[1]\ndefault_msg.target = m... | <|body_start_0|>
msg = cast(DefaultMessage, msg)
default_msg = default_pb2.DefaultMessage()
default_msg.message_id = msg.message_id
dialogue_reference = msg.dialogue_reference
default_msg.dialogue_starter_reference = dialogue_reference[0]
default_msg.dialogue_responder_re... | Serialization for the 'default' protocol. | DefaultSerializer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefaultSerializer:
"""Serialization for the 'default' protocol."""
def encode(msg: Message) -> bytes:
"""Encode a 'Default' message into bytes. :param msg: the message object. :return: the bytes."""
<|body_0|>
def decode(obj: bytes) -> Message:
"""Decode bytes in... | stack_v2_sparse_classes_36k_train_004259 | 4,510 | permissive | [
{
"docstring": "Encode a 'Default' message into bytes. :param msg: the message object. :return: the bytes.",
"name": "encode",
"signature": "def encode(msg: Message) -> bytes"
},
{
"docstring": "Decode bytes into a 'Default' message. :param obj: the bytes object. :return: the 'Default' message."... | 2 | stack_v2_sparse_classes_30k_train_001904 | Implement the Python class `DefaultSerializer` described below.
Class description:
Serialization for the 'default' protocol.
Method signatures and docstrings:
- def encode(msg: Message) -> bytes: Encode a 'Default' message into bytes. :param msg: the message object. :return: the bytes.
- def decode(obj: bytes) -> Mes... | Implement the Python class `DefaultSerializer` described below.
Class description:
Serialization for the 'default' protocol.
Method signatures and docstrings:
- def encode(msg: Message) -> bytes: Encode a 'Default' message into bytes. :param msg: the message object. :return: the bytes.
- def decode(obj: bytes) -> Mes... | 6411fcba8af2cdf55a3005939ae8129df92e8c3e | <|skeleton|>
class DefaultSerializer:
"""Serialization for the 'default' protocol."""
def encode(msg: Message) -> bytes:
"""Encode a 'Default' message into bytes. :param msg: the message object. :return: the bytes."""
<|body_0|>
def decode(obj: bytes) -> Message:
"""Decode bytes in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DefaultSerializer:
"""Serialization for the 'default' protocol."""
def encode(msg: Message) -> bytes:
"""Encode a 'Default' message into bytes. :param msg: the message object. :return: the bytes."""
msg = cast(DefaultMessage, msg)
default_msg = default_pb2.DefaultMessage()
... | the_stack_v2_python_sparse | aea/protocols/default/serialization.py | ejfitzgerald/agents-aea | train | 0 |
ca5d568698ce901c12f87caac00ad3bf46e6e73c | [
"self.p = p\nself.d = d\nself.cov = np.eye(d)\nself.x = np.zeros(d)\nreturn",
"xD = np.random.multivariate_normal(self.x, self.cov, 1).flatten()\nr = min([self.p(xD) / self.p(self.x), 1])\nif np.random.rand() < r:\n self.x = xD\nreturn self.x",
"samples = [self.x]\nfor _ in range(N - 1):\n samples.append(... | <|body_start_0|>
self.p = p
self.d = d
self.cov = np.eye(d)
self.x = np.zeros(d)
return
<|end_body_0|>
<|body_start_1|>
xD = np.random.multivariate_normal(self.x, self.cov, 1).flatten()
r = min([self.p(xD) / self.p(self.x), 1])
if np.random.rand() < r:
... | The MH algorithm is sampling implementation of the MCMC algorithm in which we sample form a given distribution :math:`p(\\mathbf x)`. This is done using the following implementation. Given a current position in the parameter space :math:`\\mathbf x`, get a new position using a proposal rule :math:`q(\\mathbf x'| \\math... | MetropolisHastingsNormal | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetropolisHastingsNormal:
"""The MH algorithm is sampling implementation of the MCMC algorithm in which we sample form a given distribution :math:`p(\\mathbf x)`. This is done using the following implementation. Given a current position in the parameter space :math:`\\mathbf x`, get a new positio... | stack_v2_sparse_classes_36k_train_004260 | 3,397 | permissive | [
{
"docstring": "Initialize the module Parameters ---------- p : function This function returns the probability density of points within a :math:`d`-dimensional space. Given an :math:`(N.d)` dimensional nd-array, consisting of :math:`N` :math:`d`-dimensional vectors, this function is going to return the PDF at e... | 3 | stack_v2_sparse_classes_30k_val_000033 | Implement the Python class `MetropolisHastingsNormal` described below.
Class description:
The MH algorithm is sampling implementation of the MCMC algorithm in which we sample form a given distribution :math:`p(\\mathbf x)`. This is done using the following implementation. Given a current position in the parameter spac... | Implement the Python class `MetropolisHastingsNormal` described below.
Class description:
The MH algorithm is sampling implementation of the MCMC algorithm in which we sample form a given distribution :math:`p(\\mathbf x)`. This is done using the following implementation. Given a current position in the parameter spac... | adf76196506633e761f2df46a087fa80e5f1d35c | <|skeleton|>
class MetropolisHastingsNormal:
"""The MH algorithm is sampling implementation of the MCMC algorithm in which we sample form a given distribution :math:`p(\\mathbf x)`. This is done using the following implementation. Given a current position in the parameter space :math:`\\mathbf x`, get a new positio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MetropolisHastingsNormal:
"""The MH algorithm is sampling implementation of the MCMC algorithm in which we sample form a given distribution :math:`p(\\mathbf x)`. This is done using the following implementation. Given a current position in the parameter space :math:`\\mathbf x`, get a new position using a pro... | the_stack_v2_python_sparse | src/lib/density/sampling/MCMC.py | sankhaMukherjee/densityNN | train | 0 |
0a7bb81c88338d5bcebdb82e6c6931febb20808c | [
"super().__init__()\nself._use_condition = use_condition\nself._model = tf.keras.Sequential([tf.keras.layers.Dense(4 * 4 * 1024, use_bias=False), tf.keras.layers.BatchNormalization(), tf.keras.layers.ReLU(), tf.keras.layers.Reshape([4, 4, 1024]), tf.keras.layers.Conv2DTranspose(512, [5, 5], strides=2, padding='same... | <|body_start_0|>
super().__init__()
self._use_condition = use_condition
self._model = tf.keras.Sequential([tf.keras.layers.Dense(4 * 4 * 1024, use_bias=False), tf.keras.layers.BatchNormalization(), tf.keras.layers.ReLU(), tf.keras.layers.Reshape([4, 4, 1024]), tf.keras.layers.Conv2DTranspose(512... | Embedding conditioned decoder. This decoder is used by CUB, Flowers, MSCOCO datasets. Attributes: | EmbeddingConditionedDecoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmbeddingConditionedDecoder:
"""Embedding conditioned decoder. This decoder is used by CUB, Flowers, MSCOCO datasets. Attributes:"""
def __init__(self, use_condition, compression_size):
"""Initializes the object. Args: use_condition: compression_size:"""
<|body_0|>
def c... | stack_v2_sparse_classes_36k_train_004261 | 10,560 | no_license | [
{
"docstring": "Initializes the object. Args: use_condition: compression_size:",
"name": "__init__",
"signature": "def __init__(self, use_condition, compression_size)"
},
{
"docstring": "Applies the model to the inputs. Args: noise: embedding: Returns:",
"name": "call",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_test_001170 | Implement the Python class `EmbeddingConditionedDecoder` described below.
Class description:
Embedding conditioned decoder. This decoder is used by CUB, Flowers, MSCOCO datasets. Attributes:
Method signatures and docstrings:
- def __init__(self, use_condition, compression_size): Initializes the object. Args: use_cond... | Implement the Python class `EmbeddingConditionedDecoder` described below.
Class description:
Embedding conditioned decoder. This decoder is used by CUB, Flowers, MSCOCO datasets. Attributes:
Method signatures and docstrings:
- def __init__(self, use_condition, compression_size): Initializes the object. Args: use_cond... | 6d04861ef87ba2ba2a4182ad36f3b322fcf47cfa | <|skeleton|>
class EmbeddingConditionedDecoder:
"""Embedding conditioned decoder. This decoder is used by CUB, Flowers, MSCOCO datasets. Attributes:"""
def __init__(self, use_condition, compression_size):
"""Initializes the object. Args: use_condition: compression_size:"""
<|body_0|>
def c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmbeddingConditionedDecoder:
"""Embedding conditioned decoder. This decoder is used by CUB, Flowers, MSCOCO datasets. Attributes:"""
def __init__(self, use_condition, compression_size):
"""Initializes the object. Args: use_condition: compression_size:"""
super().__init__()
self._u... | the_stack_v2_python_sparse | vae.py | gaotianxiang/text-to-image-synthesis | train | 0 |
1cb0a3e2cab7ef95893fdb45f6a3f49c16dff589 | [
"ys = np.linspace(extent[2], extent[3], shape_native[1] + 1)\nxs = np.linspace(extent[0], extent[1], shape_native[0] + 1)\nfor x in xs:\n plt.plot([x, x], [ys[0], ys[-1]], **self.config_dict)\nfor y in ys:\n plt.plot([xs[0], xs[-1]], [y, y], **self.config_dict)",
"try:\n plt.plot(grid[:, 1], grid[:, 0], ... | <|body_start_0|>
ys = np.linspace(extent[2], extent[3], shape_native[1] + 1)
xs = np.linspace(extent[0], extent[1], shape_native[0] + 1)
for x in xs:
plt.plot([x, x], [ys[0], ys[-1]], **self.config_dict)
for y in ys:
plt.plot([xs[0], xs[-1]], [y, y], **self.config... | Plots `Grid2D` data structure that are better visualized as solid lines, for example rectangular lines that are plotted over an image and grids of (y,x) coordinates as lines (as opposed to a scatter of points using the `GridScatter` object). This object wraps the following Matplotlib methods: - plt.plot: https://matplo... | GridPlot | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GridPlot:
"""Plots `Grid2D` data structure that are better visualized as solid lines, for example rectangular lines that are plotted over an image and grids of (y,x) coordinates as lines (as opposed to a scatter of points using the `GridScatter` object). This object wraps the following Matplotlib... | stack_v2_sparse_classes_36k_train_004262 | 21,101 | permissive | [
{
"docstring": "Plots a rectangular grid of lines on a plot, using the coordinate system of the figure. The size and shape of the grid is specified by the `extent` and `shape_native` properties of a data structure which will provide the rectangaular grid lines on a suitable coordinate system for the plot. Param... | 3 | null | Implement the Python class `GridPlot` described below.
Class description:
Plots `Grid2D` data structure that are better visualized as solid lines, for example rectangular lines that are plotted over an image and grids of (y,x) coordinates as lines (as opposed to a scatter of points using the `GridScatter` object). Thi... | Implement the Python class `GridPlot` described below.
Class description:
Plots `Grid2D` data structure that are better visualized as solid lines, for example rectangular lines that are plotted over an image and grids of (y,x) coordinates as lines (as opposed to a scatter of points using the `GridScatter` object). Thi... | c21e8859bdb20737352147b9904797ac99985b73 | <|skeleton|>
class GridPlot:
"""Plots `Grid2D` data structure that are better visualized as solid lines, for example rectangular lines that are plotted over an image and grids of (y,x) coordinates as lines (as opposed to a scatter of points using the `GridScatter` object). This object wraps the following Matplotlib... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GridPlot:
"""Plots `Grid2D` data structure that are better visualized as solid lines, for example rectangular lines that are plotted over an image and grids of (y,x) coordinates as lines (as opposed to a scatter of points using the `GridScatter` object). This object wraps the following Matplotlib methods: - p... | the_stack_v2_python_sparse | autoarray/plot/mat_wrap/wrap/wrap_2d.py | jonathanfrawley/PyAutoArray_copy | train | 0 |
2aecf525c7041dcb9c7c2cf97f75b7d1334847e7 | [
"if num == 0:\n return '0'\nd = {'0000': '0', '0001': '1', '0010': '2', '0011': '3', '0100': '4', '0101': '5', '0110': '6', '0111': '7', '1000': '8', '1001': '9', '1010': 'a', '1011': 'b', '1100': 'c', '1101': 'd', '1110': 'e', '1111': 'f'}\ni = 0\nr = ''\nm = 1\nt = ''\nwhile i < 32:\n t = str(num >> i & m) ... | <|body_start_0|>
if num == 0:
return '0'
d = {'0000': '0', '0001': '1', '0010': '2', '0011': '3', '0100': '4', '0101': '5', '0110': '6', '0111': '7', '1000': '8', '1001': '9', '1010': 'a', '1011': 'b', '1100': 'c', '1101': 'd', '1110': 'e', '1111': 'f'}
i = 0
r = ''
m... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def toHex(self, num):
""":type num: int :rtype: str"""
<|body_0|>
def toHex1(self, num):
""":type num: int :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if num == 0:
return '0'
d = {'0000': '0', '0001': '1... | stack_v2_sparse_classes_36k_train_004263 | 1,278 | no_license | [
{
"docstring": ":type num: int :rtype: str",
"name": "toHex",
"signature": "def toHex(self, num)"
},
{
"docstring": ":type num: int :rtype: str",
"name": "toHex1",
"signature": "def toHex1(self, num)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def toHex(self, num): :type num: int :rtype: str
- def toHex1(self, num): :type num: int :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def toHex(self, num): :type num: int :rtype: str
- def toHex1(self, num): :type num: int :rtype: str
<|skeleton|>
class Solution:
def toHex(self, num):
""":type num... | e5b018493bbd12edcdcd0434f35d9c358106d391 | <|skeleton|>
class Solution:
def toHex(self, num):
""":type num: int :rtype: str"""
<|body_0|>
def toHex1(self, num):
""":type num: int :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def toHex(self, num):
""":type num: int :rtype: str"""
if num == 0:
return '0'
d = {'0000': '0', '0001': '1', '0010': '2', '0011': '3', '0100': '4', '0101': '5', '0110': '6', '0111': '7', '1000': '8', '1001': '9', '1010': 'a', '1011': 'b', '1100': 'c', '1101': 'd'... | the_stack_v2_python_sparse | py/leetcode/405.py | wfeng1991/learnpy | train | 0 | |
d40cea7d00ccf04245c49739e51ff52e3aad4cf3 | [
"super(TempBase, self).__init__(*args, **kwargs)\nforbidden = []\nfor i in self.FORBIDDEN_COLUMN_LIST:\n forbidden.append(self.__tablename__ + '.' + i)\nself.FORBIDDEN_COLUMN_LIST = forbidden\nshow = []\nfor k in self.SHOW_COLUMN_LIST:\n show.append(self.__tablename__ + '.' + k)\nself.SHOW_COLUMN_LIST = show"... | <|body_start_0|>
super(TempBase, self).__init__(*args, **kwargs)
forbidden = []
for i in self.FORBIDDEN_COLUMN_LIST:
forbidden.append(self.__tablename__ + '.' + i)
self.FORBIDDEN_COLUMN_LIST = forbidden
show = []
for k in self.SHOW_COLUMN_LIST:
sho... | 基类 | TempBase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TempBase:
"""基类"""
def __init__(self, *args, **kwargs):
"""初始化"""
<|body_0|>
def to_dict(self):
"""序列化"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(TempBase, self).__init__(*args, **kwargs)
forbidden = []
for i in self.F... | stack_v2_sparse_classes_36k_train_004264 | 22,283 | no_license | [
{
"docstring": "初始化",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "序列化",
"name": "to_dict",
"signature": "def to_dict(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000321 | Implement the Python class `TempBase` described below.
Class description:
基类
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): 初始化
- def to_dict(self): 序列化 | Implement the Python class `TempBase` described below.
Class description:
基类
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): 初始化
- def to_dict(self): 序列化
<|skeleton|>
class TempBase:
"""基类"""
def __init__(self, *args, **kwargs):
"""初始化"""
<|body_0|>
def to_dict(... | c50def8cde58fd4663032b860eb058302cbac6da | <|skeleton|>
class TempBase:
"""基类"""
def __init__(self, *args, **kwargs):
"""初始化"""
<|body_0|>
def to_dict(self):
"""序列化"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TempBase:
"""基类"""
def __init__(self, *args, **kwargs):
"""初始化"""
super(TempBase, self).__init__(*args, **kwargs)
forbidden = []
for i in self.FORBIDDEN_COLUMN_LIST:
forbidden.append(self.__tablename__ + '.' + i)
self.FORBIDDEN_COLUMN_LIST = forbidden
... | the_stack_v2_python_sparse | src/workers/preprocess/models/models.py | fan1018wen/Alpha | train | 0 |
9381d990a61a52e5d4218a8836a8cf7f04985e96 | [
"super(MultiLayerCSAttCNN, self).__init__()\nself.tok_embedding = nn.Embedding(input_dim, emb_dim, padding_idx=PAD_IDX)\nself.pos_embedding = nn.Embedding(max_length, emb_dim, padding_idx=PAD_IDX)\nself.encoder = nn.ModuleList([Encoder(emb_dim, hid_dim, cnn_layers, kernel_size, dropout, max_length) for _ in range(e... | <|body_start_0|>
super(MultiLayerCSAttCNN, self).__init__()
self.tok_embedding = nn.Embedding(input_dim, emb_dim, padding_idx=PAD_IDX)
self.pos_embedding = nn.Embedding(max_length, emb_dim, padding_idx=PAD_IDX)
self.encoder = nn.ModuleList([Encoder(emb_dim, hid_dim, cnn_layers, kernel_si... | MultiLayerCSAttCNN | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiLayerCSAttCNN:
def __init__(self, input_dim, output_dim, emb_dim, hid_dim, cnn_layers, encoder_layers, kernel_size, dropout, PAD_IDX, max_length=100, use_crf=True):
"""define berc model :param input_dim: :param output_dim: :param emb_dim: :param hid_dim: :param cnn_layers: :param en... | stack_v2_sparse_classes_36k_train_004265 | 6,870 | permissive | [
{
"docstring": "define berc model :param input_dim: :param output_dim: :param emb_dim: :param hid_dim: :param cnn_layers: :param encoder_layers: :param kernel_size: :param dropout: :param padding_idx: :param max_length:",
"name": "__init__",
"signature": "def __init__(self, input_dim, output_dim, emb_di... | 3 | stack_v2_sparse_classes_30k_train_018975 | Implement the Python class `MultiLayerCSAttCNN` described below.
Class description:
Implement the MultiLayerCSAttCNN class.
Method signatures and docstrings:
- def __init__(self, input_dim, output_dim, emb_dim, hid_dim, cnn_layers, encoder_layers, kernel_size, dropout, PAD_IDX, max_length=100, use_crf=True): define b... | Implement the Python class `MultiLayerCSAttCNN` described below.
Class description:
Implement the MultiLayerCSAttCNN class.
Method signatures and docstrings:
- def __init__(self, input_dim, output_dim, emb_dim, hid_dim, cnn_layers, encoder_layers, kernel_size, dropout, PAD_IDX, max_length=100, use_crf=True): define b... | dcbd46fea0023d88b485b479bf65c56df9609efa | <|skeleton|>
class MultiLayerCSAttCNN:
def __init__(self, input_dim, output_dim, emb_dim, hid_dim, cnn_layers, encoder_layers, kernel_size, dropout, PAD_IDX, max_length=100, use_crf=True):
"""define berc model :param input_dim: :param output_dim: :param emb_dim: :param hid_dim: :param cnn_layers: :param en... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiLayerCSAttCNN:
def __init__(self, input_dim, output_dim, emb_dim, hid_dim, cnn_layers, encoder_layers, kernel_size, dropout, PAD_IDX, max_length=100, use_crf=True):
"""define berc model :param input_dim: :param output_dim: :param emb_dim: :param hid_dim: :param cnn_layers: :param encoder_layers: ... | the_stack_v2_python_sparse | cnn4ie/channel_spatial_attention_cnn/model.py | pengdada98/CNN4IE | train | 0 | |
087cce9d7e4e757cf3f97bfd605b87a958f43831 | [
"self.str_path = os.path.dirname(os.path.abspath(__file__))\nself.list_pdf = list_pdf\nself.str_name = '%s\\\\files\\\\%s.pdf' % (self.str_path, str_name)\nself.bool_is_custom_color = bool_is_custom_color\nself.int_font_size = int_font_size\nself.float_offset_x = float_offset_x\nself.float_offset_y = float_offset_y... | <|body_start_0|>
self.str_path = os.path.dirname(os.path.abspath(__file__))
self.list_pdf = list_pdf
self.str_name = '%s\\files\\%s.pdf' % (self.str_path, str_name)
self.bool_is_custom_color = bool_is_custom_color
self.int_font_size = int_font_size
self.float_offset_x = f... | PDF类 | PDF | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PDF:
"""PDF类"""
def __init__(self, list_pdf: list, str_name: str, bool_is_custom_color: bool=False, tulpe_color: tuple=(0.77, 0.77, 0.77), int_font_size: int=18, float_offset_x: float=5, float_offset_y: float=5):
"""【初始化】 list_pdf:保存的内容 str_name:保存的文件名"""
<|body_0|>
def ... | stack_v2_sparse_classes_36k_train_004266 | 1,938 | no_license | [
{
"docstring": "【初始化】 list_pdf:保存的内容 str_name:保存的文件名",
"name": "__init__",
"signature": "def __init__(self, list_pdf: list, str_name: str, bool_is_custom_color: bool=False, tulpe_color: tuple=(0.77, 0.77, 0.77), int_font_size: int=18, float_offset_x: float=5, float_offset_y: float=5)"
},
{
"docs... | 2 | stack_v2_sparse_classes_30k_train_015126 | Implement the Python class `PDF` described below.
Class description:
PDF类
Method signatures and docstrings:
- def __init__(self, list_pdf: list, str_name: str, bool_is_custom_color: bool=False, tulpe_color: tuple=(0.77, 0.77, 0.77), int_font_size: int=18, float_offset_x: float=5, float_offset_y: float=5): 【初始化】 list_... | Implement the Python class `PDF` described below.
Class description:
PDF类
Method signatures and docstrings:
- def __init__(self, list_pdf: list, str_name: str, bool_is_custom_color: bool=False, tulpe_color: tuple=(0.77, 0.77, 0.77), int_font_size: int=18, float_offset_x: float=5, float_offset_y: float=5): 【初始化】 list_... | bd7152899dcb04aa76ed9f65b36e6a8ccc0affd0 | <|skeleton|>
class PDF:
"""PDF类"""
def __init__(self, list_pdf: list, str_name: str, bool_is_custom_color: bool=False, tulpe_color: tuple=(0.77, 0.77, 0.77), int_font_size: int=18, float_offset_x: float=5, float_offset_y: float=5):
"""【初始化】 list_pdf:保存的内容 str_name:保存的文件名"""
<|body_0|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PDF:
"""PDF类"""
def __init__(self, list_pdf: list, str_name: str, bool_is_custom_color: bool=False, tulpe_color: tuple=(0.77, 0.77, 0.77), int_font_size: int=18, float_offset_x: float=5, float_offset_y: float=5):
"""【初始化】 list_pdf:保存的内容 str_name:保存的文件名"""
self.str_path = os.path.dirname(o... | the_stack_v2_python_sparse | part03/week01/pdf.py | tea8336/test | train | 0 |
80d28bd3fc21f2bf10b604c7454298c9da528aa2 | [
"def rserialize(root):\n if root is None:\n data.append('None')\n else:\n data.append(str(root.val))\n rserialize(root.left)\n rserialize(root.right)\ndata = []\nrserialize(data)\nreturn ' '.join(data)",
"def rdeserialize():\n data = next(data_list)\n if data == 'None':\n ... | <|body_start_0|>
def rserialize(root):
if root is None:
data.append('None')
else:
data.append(str(root.val))
rserialize(root.left)
rserialize(root.right)
data = []
rserialize(data)
return ' '.join(dat... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_004267 | 2,729 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 4732fb80710a08a715c3e7080c394f5298b8326d | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def rserialize(root):
if root is None:
data.append('None')
else:
data.append(str(root.val))
rserialize(root.left)
... | the_stack_v2_python_sparse | .leetcode/297.二叉树的序列化与反序列化.py | xiaoruijiang/algorithm | train | 0 | |
39fa632554349c2ebc60f548dd86d7e13e19377d | [
"client_id = client_id.strip()\nif not len(client_id) > 0:\n raise InvalidParameterException('Client id is invalid'.format(cmd))\nreturn RetrieveClient(client_id=client_id)",
"client_id = client_id.strip()\nif not len(client_id) > 0:\n raise InvalidParameterException('Client id is invalid'.format(cmd))\ncod... | <|body_start_0|>
client_id = client_id.strip()
if not len(client_id) > 0:
raise InvalidParameterException('Client id is invalid'.format(cmd))
return RetrieveClient(client_id=client_id)
<|end_body_0|>
<|body_start_1|>
client_id = client_id.strip()
if not len(client_id... | This factory instantiates query objects to be sent to a rest querybus. | QueryFactory | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QueryFactory:
"""This factory instantiates query objects to be sent to a rest querybus."""
def newRetrieveClient(client_id):
"""Generates a new RetrieveClient query :param client_id: the client id :type client_id: string :returns: A RetrieveClient query object :rtype: RetrieveClient"... | stack_v2_sparse_classes_36k_train_004268 | 2,535 | permissive | [
{
"docstring": "Generates a new RetrieveClient query :param client_id: the client id :type client_id: string :returns: A RetrieveClient query object :rtype: RetrieveClient",
"name": "newRetrieveClient",
"signature": "def newRetrieveClient(client_id)"
},
{
"docstring": "Generates a new RetrieveGr... | 4 | null | Implement the Python class `QueryFactory` described below.
Class description:
This factory instantiates query objects to be sent to a rest querybus.
Method signatures and docstrings:
- def newRetrieveClient(client_id): Generates a new RetrieveClient query :param client_id: the client id :type client_id: string :retur... | Implement the Python class `QueryFactory` described below.
Class description:
This factory instantiates query objects to be sent to a rest querybus.
Method signatures and docstrings:
- def newRetrieveClient(client_id): Generates a new RetrieveClient query :param client_id: the client id :type client_id: string :retur... | 48573e170771a251f629f2d13dba7173f010a38c | <|skeleton|>
class QueryFactory:
"""This factory instantiates query objects to be sent to a rest querybus."""
def newRetrieveClient(client_id):
"""Generates a new RetrieveClient query :param client_id: the client id :type client_id: string :returns: A RetrieveClient query object :rtype: RetrieveClient"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QueryFactory:
"""This factory instantiates query objects to be sent to a rest querybus."""
def newRetrieveClient(client_id):
"""Generates a new RetrieveClient query :param client_id: the client id :type client_id: string :returns: A RetrieveClient query object :rtype: RetrieveClient"""
cl... | the_stack_v2_python_sparse | strongr/restdomain/factory/oauth2/queryfactory.py | bigr-erasmusmc/StrongR | train | 0 |
27701991639a3d2aeeb7689fba6321c07836db99 | [
"pygame.font.init()\nbasicfont = pygame.font.Font(None, fontsize)\nself.linewidths = []\nfor x in text:\n self.texttemp = basicfont.render(x, 0, (1, 1, 1))\n self.linewidths.append(self.texttemp.get_width())\nself.imagewidth = basicfont.render(text[self.linewidths.index(max(self.linewidths))], 0, (1, 1, 1)).g... | <|body_start_0|>
pygame.font.init()
basicfont = pygame.font.Font(None, fontsize)
self.linewidths = []
for x in text:
self.texttemp = basicfont.render(x, 0, (1, 1, 1))
self.linewidths.append(self.texttemp.get_width())
self.imagewidth = basicfont.render(text... | Linesoftext | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Linesoftext:
def __init__(self, text, position, xmid=False, fontsize=36, backgroundcolor=(200, 200, 200), surface=None):
"""This object will create an image of text that is passed in as a list of strings. It will put a new line for each element in the list. Use its image attribute to put... | stack_v2_sparse_classes_36k_train_004269 | 5,935 | no_license | [
{
"docstring": "This object will create an image of text that is passed in as a list of strings. It will put a new line for each element in the list. Use its image attribute to put this text on your screen",
"name": "__init__",
"signature": "def __init__(self, text, position, xmid=False, fontsize=36, ba... | 2 | stack_v2_sparse_classes_30k_train_008582 | Implement the Python class `Linesoftext` described below.
Class description:
Implement the Linesoftext class.
Method signatures and docstrings:
- def __init__(self, text, position, xmid=False, fontsize=36, backgroundcolor=(200, 200, 200), surface=None): This object will create an image of text that is passed in as a ... | Implement the Python class `Linesoftext` described below.
Class description:
Implement the Linesoftext class.
Method signatures and docstrings:
- def __init__(self, text, position, xmid=False, fontsize=36, backgroundcolor=(200, 200, 200), surface=None): This object will create an image of text that is passed in as a ... | 3eae1428fdd30fddc66669d40b8bb0a715d5595a | <|skeleton|>
class Linesoftext:
def __init__(self, text, position, xmid=False, fontsize=36, backgroundcolor=(200, 200, 200), surface=None):
"""This object will create an image of text that is passed in as a list of strings. It will put a new line for each element in the list. Use its image attribute to put... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Linesoftext:
def __init__(self, text, position, xmid=False, fontsize=36, backgroundcolor=(200, 200, 200), surface=None):
"""This object will create an image of text that is passed in as a list of strings. It will put a new line for each element in the list. Use its image attribute to put this text on ... | the_stack_v2_python_sparse | General Python/Guessing_game_with_gui/pygametools.py | jbm950/personal_projects | train | 0 | |
493d56e0d1af5ccbdd148bdb278b9620768c4e72 | [
"self.bins = bins\nself.nbreaks = nbreaks\nself.total_psi = None",
"if self.bins is None:\n breaks = pd.qcut(df1[var], self.nbreaks, duplicates='drop', retbins=True)[1]\n breaks = breaks[1:-1]\n bins = []\n bins.append(-float('Inf'))\n for i in breaks:\n bins.append(i)\n bins.append(float... | <|body_start_0|>
self.bins = bins
self.nbreaks = nbreaks
self.total_psi = None
<|end_body_0|>
<|body_start_1|>
if self.bins is None:
breaks = pd.qcut(df1[var], self.nbreaks, duplicates='drop', retbins=True)[1]
breaks = breaks[1:-1]
bins = []
... | psi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class psi:
def __init__(self, bins=None, nbreaks=10):
"""nbreaks: Número de Cortes para el percentil bins: Puntos de corte"""
<|body_0|>
def fit(self, df1, df2, var):
"""df1: Muestra Original df2: Muestra a Probar var: Variable de interes Retorna la tabla"""
<|body... | stack_v2_sparse_classes_36k_train_004270 | 2,367 | no_license | [
{
"docstring": "nbreaks: Número de Cortes para el percentil bins: Puntos de corte",
"name": "__init__",
"signature": "def __init__(self, bins=None, nbreaks=10)"
},
{
"docstring": "df1: Muestra Original df2: Muestra a Probar var: Variable de interes Retorna la tabla",
"name": "fit",
"sign... | 2 | stack_v2_sparse_classes_30k_train_020690 | Implement the Python class `psi` described below.
Class description:
Implement the psi class.
Method signatures and docstrings:
- def __init__(self, bins=None, nbreaks=10): nbreaks: Número de Cortes para el percentil bins: Puntos de corte
- def fit(self, df1, df2, var): df1: Muestra Original df2: Muestra a Probar var... | Implement the Python class `psi` described below.
Class description:
Implement the psi class.
Method signatures and docstrings:
- def __init__(self, bins=None, nbreaks=10): nbreaks: Número de Cortes para el percentil bins: Puntos de corte
- def fit(self, df1, df2, var): df1: Muestra Original df2: Muestra a Probar var... | 2c3061e0a152d91d962e61bbbe04e74a4f9abfaf | <|skeleton|>
class psi:
def __init__(self, bins=None, nbreaks=10):
"""nbreaks: Número de Cortes para el percentil bins: Puntos de corte"""
<|body_0|>
def fit(self, df1, df2, var):
"""df1: Muestra Original df2: Muestra a Probar var: Variable de interes Retorna la tabla"""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class psi:
def __init__(self, bins=None, nbreaks=10):
"""nbreaks: Número de Cortes para el percentil bins: Puntos de corte"""
self.bins = bins
self.nbreaks = nbreaks
self.total_psi = None
def fit(self, df1, df2, var):
"""df1: Muestra Original df2: Muestra a Probar var: V... | the_stack_v2_python_sparse | psi.py | NigthDragon5000/Credit-Risk-Modeling | train | 0 | |
3f212b9cf18461f4f8b7521317851cebffca86e4 | [
"while low >= 0 and high < len(s):\n if s[low] == s[high]:\n low -= 1\n high += 1\n else:\n return s[low + 1:high - 1 + 1]\nreturn s[low + 1:high - 1 + 1]",
"if len(s) == 1:\n return s\nres = []\nfor i in range(len(s) - 1):\n res.append(self.expandCheckPalindrome(s, i, i))\n do... | <|body_start_0|>
while low >= 0 and high < len(s):
if s[low] == s[high]:
low -= 1
high += 1
else:
return s[low + 1:high - 1 + 1]
return s[low + 1:high - 1 + 1]
<|end_body_0|>
<|body_start_1|>
if len(s) == 1:
ret... | Brute-force改进,中心外扩法——局部函数,输出所有回文序列,取最长即可 | Solution2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution2:
"""Brute-force改进,中心外扩法——局部函数,输出所有回文序列,取最长即可"""
def expandCheckPalindrome(self, s, low, high):
"""从中心点向外扩散,利用回文子串的中心对称性,复杂度O(n^2),直接返回所有的回文子串,不做判断处理"""
<|body_0|>
def longestPalindrome(self, s):
"""以每个字符串为中心位置外扩,需要考虑单核'aba',也需要考虑双核'abba'"""
<|bo... | stack_v2_sparse_classes_36k_train_004271 | 5,121 | no_license | [
{
"docstring": "从中心点向外扩散,利用回文子串的中心对称性,复杂度O(n^2),直接返回所有的回文子串,不做判断处理",
"name": "expandCheckPalindrome",
"signature": "def expandCheckPalindrome(self, s, low, high)"
},
{
"docstring": "以每个字符串为中心位置外扩,需要考虑单核'aba',也需要考虑双核'abba'",
"name": "longestPalindrome",
"signature": "def longestPalindrome... | 2 | null | Implement the Python class `Solution2` described below.
Class description:
Brute-force改进,中心外扩法——局部函数,输出所有回文序列,取最长即可
Method signatures and docstrings:
- def expandCheckPalindrome(self, s, low, high): 从中心点向外扩散,利用回文子串的中心对称性,复杂度O(n^2),直接返回所有的回文子串,不做判断处理
- def longestPalindrome(self, s): 以每个字符串为中心位置外扩,需要考虑单核'aba',也需要考虑双核'... | Implement the Python class `Solution2` described below.
Class description:
Brute-force改进,中心外扩法——局部函数,输出所有回文序列,取最长即可
Method signatures and docstrings:
- def expandCheckPalindrome(self, s, low, high): 从中心点向外扩散,利用回文子串的中心对称性,复杂度O(n^2),直接返回所有的回文子串,不做判断处理
- def longestPalindrome(self, s): 以每个字符串为中心位置外扩,需要考虑单核'aba',也需要考虑双核'... | 4e4f739402b95691f6c91411da26d7d3bfe042b6 | <|skeleton|>
class Solution2:
"""Brute-force改进,中心外扩法——局部函数,输出所有回文序列,取最长即可"""
def expandCheckPalindrome(self, s, low, high):
"""从中心点向外扩散,利用回文子串的中心对称性,复杂度O(n^2),直接返回所有的回文子串,不做判断处理"""
<|body_0|>
def longestPalindrome(self, s):
"""以每个字符串为中心位置外扩,需要考虑单核'aba',也需要考虑双核'abba'"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution2:
"""Brute-force改进,中心外扩法——局部函数,输出所有回文序列,取最长即可"""
def expandCheckPalindrome(self, s, low, high):
"""从中心点向外扩散,利用回文子串的中心对称性,复杂度O(n^2),直接返回所有的回文子串,不做判断处理"""
while low >= 0 and high < len(s):
if s[low] == s[high]:
low -= 1
high += 1
... | the_stack_v2_python_sparse | other_code_programe/13、最长回文子串.py | hugechuanqi/Algorithms-and-Data-Structures | train | 3 |
a740ab51a24397adceb53ccaa891a0e4e5ea9d18 | [
"filters = {}\nts_model = self.model.timesheet.field.rel.to\nstatus = querystring.get('status')\nif status == 'approved':\n filters['timesheet__status'] = ts_model.STATUS_APPROVED\nelif status == 'issued':\n filters['timesheet__status'] = ts_model.STATUS_ISSUED\ndate_start = querystring.get('from_date')\ndate... | <|body_start_0|>
filters = {}
ts_model = self.model.timesheet.field.rel.to
status = querystring.get('status')
if status == 'approved':
filters['timesheet__status'] = ts_model.STATUS_APPROVED
elif status == 'issued':
filters['timesheet__status'] = ts_model.... | WorkLogQuerySet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkLogQuerySet:
def filter_for_querystring(self, querystring):
"""Apply a bunch of filters according to the passed querystring."""
<|body_0|>
def group_for_querystring(self, main_groups):
"""Apply a bunch of group_bys according to the passed querystring."""
... | stack_v2_sparse_classes_36k_train_004272 | 2,351 | no_license | [
{
"docstring": "Apply a bunch of filters according to the passed querystring.",
"name": "filter_for_querystring",
"signature": "def filter_for_querystring(self, querystring)"
},
{
"docstring": "Apply a bunch of group_bys according to the passed querystring.",
"name": "group_for_querystring",... | 2 | null | Implement the Python class `WorkLogQuerySet` described below.
Class description:
Implement the WorkLogQuerySet class.
Method signatures and docstrings:
- def filter_for_querystring(self, querystring): Apply a bunch of filters according to the passed querystring.
- def group_for_querystring(self, main_groups): Apply a... | Implement the Python class `WorkLogQuerySet` described below.
Class description:
Implement the WorkLogQuerySet class.
Method signatures and docstrings:
- def filter_for_querystring(self, querystring): Apply a bunch of filters according to the passed querystring.
- def group_for_querystring(self, main_groups): Apply a... | 4dcf0e6a37e8753ae9d69d663c0c280fcca0a26c | <|skeleton|>
class WorkLogQuerySet:
def filter_for_querystring(self, querystring):
"""Apply a bunch of filters according to the passed querystring."""
<|body_0|>
def group_for_querystring(self, main_groups):
"""Apply a bunch of group_bys according to the passed querystring."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkLogQuerySet:
def filter_for_querystring(self, querystring):
"""Apply a bunch of filters according to the passed querystring."""
filters = {}
ts_model = self.model.timesheet.field.rel.to
status = querystring.get('status')
if status == 'approved':
filters[... | the_stack_v2_python_sparse | apps/deployment/query.py | ESCL/pjtracker | train | 1 | |
f26511ab31383a6139ce94571990035a9f80aa4e | [
"seen = set()\nq = collections.deque([s])\nwhile q:\n s = q.popleft()\n for word in wordDict:\n if s.startswith(word):\n new_s = s[len(word):]\n if new_s == '':\n return True\n if new_s not in seen:\n q.append(new_s)\n seen.a... | <|body_start_0|>
seen = set()
q = collections.deque([s])
while q:
s = q.popleft()
for word in wordDict:
if s.startswith(word):
new_s = s[len(word):]
if new_s == '':
return True
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordBreak(self, s: str, wordDict: list[str]) -> bool:
"""iterative"""
<|body_0|>
def wordBreak(self, s: str, wordDict: list[str]) -> bool:
"""DP programming"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
seen = set()
q = colle... | stack_v2_sparse_classes_36k_train_004273 | 972 | no_license | [
{
"docstring": "iterative",
"name": "wordBreak",
"signature": "def wordBreak(self, s: str, wordDict: list[str]) -> bool"
},
{
"docstring": "DP programming",
"name": "wordBreak",
"signature": "def wordBreak(self, s: str, wordDict: list[str]) -> bool"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(self, s: str, wordDict: list[str]) -> bool: iterative
- def wordBreak(self, s: str, wordDict: list[str]) -> bool: DP programming | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(self, s: str, wordDict: list[str]) -> bool: iterative
- def wordBreak(self, s: str, wordDict: list[str]) -> bool: DP programming
<|skeleton|>
class Solution:
... | e50dc0642f087f37ab3234390be3d8a0ed48fe62 | <|skeleton|>
class Solution:
def wordBreak(self, s: str, wordDict: list[str]) -> bool:
"""iterative"""
<|body_0|>
def wordBreak(self, s: str, wordDict: list[str]) -> bool:
"""DP programming"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def wordBreak(self, s: str, wordDict: list[str]) -> bool:
"""iterative"""
seen = set()
q = collections.deque([s])
while q:
s = q.popleft()
for word in wordDict:
if s.startswith(word):
new_s = s[len(word):]
... | the_stack_v2_python_sparse | Leetcode/139. Word Break.py | brlala/Educative-Grokking-Coding-Exercise | train | 3 | |
c88140dc32830d5aa861dc2efde26767e7994ac0 | [
"if not matrix:\n return\nrows = len(matrix)\ncolumns = len(matrix[0])\nzero_rows = [0 for _ in range(rows)]\nzero_columns = [0 for _ in range(columns)]\nfor i in range(rows):\n for j in range(columns):\n if not matrix[i][j]:\n zero_rows[i] = 1\n zero_columns[j] = 1\nfor i in rang... | <|body_start_0|>
if not matrix:
return
rows = len(matrix)
columns = len(matrix[0])
zero_rows = [0 for _ in range(rows)]
zero_columns = [0 for _ in range(columns)]
for i in range(rows):
for j in range(columns):
if not matrix[i][j]:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def setZeroes_v1(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def setZeroes_v2(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify ... | stack_v2_sparse_classes_36k_train_004274 | 2,367 | permissive | [
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.",
"name": "setZeroes_v1",
"signature": "def setZeroes_v1(self, matrix)"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place ... | 2 | stack_v2_sparse_classes_30k_train_009931 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes_v1(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def setZeroes_v2(self, matrix): :type matrix:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes_v1(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def setZeroes_v2(self, matrix): :type matrix:... | 0fd165afa2ec339a6f194bc57f8810e66cd2822b | <|skeleton|>
class Solution:
def setZeroes_v1(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def setZeroes_v2(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def setZeroes_v1(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
if not matrix:
return
rows = len(matrix)
columns = len(matrix[0])
zero_rows = [0 for _ in range(rows)]
... | the_stack_v2_python_sparse | Array/73_SetMatrixZeroes.py | wanggalex/leetcode | train | 0 | |
212662617ec022b1fb98911483f7fdcf1c8dcb1f | [
"self.assertEqual(address_helper.separate_path('zhfs/A/yanbx/lib'), ['zhfs', 'A', 'yanbx', 'lib'])\nself.assertEqual(address_helper.separate_path('/zhfs/A/yanbx/lib'), ['zhfs', 'A', 'yanbx', 'lib'])\nself.assertEqual(address_helper.separate_path('zhfs/A/yanbx/lib/'), ['zhfs', 'A', 'yanbx', 'lib'])\nself.assertEqual... | <|body_start_0|>
self.assertEqual(address_helper.separate_path('zhfs/A/yanbx/lib'), ['zhfs', 'A', 'yanbx', 'lib'])
self.assertEqual(address_helper.separate_path('/zhfs/A/yanbx/lib'), ['zhfs', 'A', 'yanbx', 'lib'])
self.assertEqual(address_helper.separate_path('zhfs/A/yanbx/lib/'), ['zhfs', 'A', ... | common.address_helper的测试函数 | TestAddressHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAddressHelper:
"""common.address_helper的测试函数"""
def test_separate_path(self):
"""测试 address_helper.separate_path(path)"""
<|body_0|>
def test_is_contain_path(self):
"""测试 address_helper.is_contain_path(A,B) which checkes if A is contained in B"""
<|bo... | stack_v2_sparse_classes_36k_train_004275 | 3,170 | no_license | [
{
"docstring": "测试 address_helper.separate_path(path)",
"name": "test_separate_path",
"signature": "def test_separate_path(self)"
},
{
"docstring": "测试 address_helper.is_contain_path(A,B) which checkes if A is contained in B",
"name": "test_is_contain_path",
"signature": "def test_is_con... | 3 | null | Implement the Python class `TestAddressHelper` described below.
Class description:
common.address_helper的测试函数
Method signatures and docstrings:
- def test_separate_path(self): 测试 address_helper.separate_path(path)
- def test_is_contain_path(self): 测试 address_helper.is_contain_path(A,B) which checkes if A is contained... | Implement the Python class `TestAddressHelper` described below.
Class description:
common.address_helper的测试函数
Method signatures and docstrings:
- def test_separate_path(self): 测试 address_helper.separate_path(path)
- def test_is_contain_path(self): 测试 address_helper.is_contain_path(A,B) which checkes if A is contained... | 5a4eca0758ad4e4814561c761aca6dfcc31a6c4c | <|skeleton|>
class TestAddressHelper:
"""common.address_helper的测试函数"""
def test_separate_path(self):
"""测试 address_helper.separate_path(path)"""
<|body_0|>
def test_is_contain_path(self):
"""测试 address_helper.is_contain_path(A,B) which checkes if A is contained in B"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestAddressHelper:
"""common.address_helper的测试函数"""
def test_separate_path(self):
"""测试 address_helper.separate_path(path)"""
self.assertEqual(address_helper.separate_path('zhfs/A/yanbx/lib'), ['zhfs', 'A', 'yanbx', 'lib'])
self.assertEqual(address_helper.separate_path('/zhfs/A/ya... | the_stack_v2_python_sparse | common/test_address_helper.py | 7venminutes/WebService | train | 0 |
bba604ad48df909bfc7f1a9c9d0961b1927d3bc6 | [
"count = 0\nfor row in range(len(grid)):\n for column in range(len(grid[0])):\n if grid[row][column] == '1':\n count += 1\n self.find(row, column, grid)\nreturn count",
"grid[row][column] = '-1'\nif row > 0 and grid[row - 1][column] == '1':\n self.find(row - 1, column, grid)\nif... | <|body_start_0|>
count = 0
for row in range(len(grid)):
for column in range(len(grid[0])):
if grid[row][column] == '1':
count += 1
self.find(row, column, grid)
return count
<|end_body_0|>
<|body_start_1|>
grid[row][colu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numIslands(self, grid):
""":type grid: List[List[str]] :rtype: int"""
<|body_0|>
def find(self, row, column, grid):
""":type row: int :type column: int :type grid: List[List[str]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
count =... | stack_v2_sparse_classes_36k_train_004276 | 3,323 | no_license | [
{
"docstring": ":type grid: List[List[str]] :rtype: int",
"name": "numIslands",
"signature": "def numIslands(self, grid)"
},
{
"docstring": ":type row: int :type column: int :type grid: List[List[str]]",
"name": "find",
"signature": "def find(self, row, column, grid)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numIslands(self, grid): :type grid: List[List[str]] :rtype: int
- def find(self, row, column, grid): :type row: int :type column: int :type grid: List[List[str]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numIslands(self, grid): :type grid: List[List[str]] :rtype: int
- def find(self, row, column, grid): :type row: int :type column: int :type grid: List[List[str]]
<|skeleton|... | f832227c4d0e0b1c0cc326561187004ef24e2a68 | <|skeleton|>
class Solution:
def numIslands(self, grid):
""":type grid: List[List[str]] :rtype: int"""
<|body_0|>
def find(self, row, column, grid):
""":type row: int :type column: int :type grid: List[List[str]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numIslands(self, grid):
""":type grid: List[List[str]] :rtype: int"""
count = 0
for row in range(len(grid)):
for column in range(len(grid[0])):
if grid[row][column] == '1':
count += 1
self.find(row, colum... | the_stack_v2_python_sparse | 200.py | Gackle/leetcode_practice | train | 0 | |
88b2439cbb6400403b7c3a34451b6355e3358996 | [
"try:\n version = get_openflow_header(this_packet, 0)\n if version['version'] == 1:\n self.ofp = unpack10(this_packet)\n elif version['version'] == 4:\n self.ofp = unpack13(this_packet)\n else:\n self.ofp = 0\nexcept:\n self.ofp = 0",
"if not libs.core.filters.filter_msg(self):... | <|body_start_0|>
try:
version = get_openflow_header(this_packet, 0)
if version['version'] == 1:
self.ofp = unpack10(this_packet)
elif version['version'] == 4:
self.ofp = unpack13(this_packet)
else:
self.ofp = 0
... | Used to process all data regarding this OpenFlow message. With the python-openflow (pyof) lib, only one variable became necessary. | OFMessage | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OFMessage:
"""Used to process all data regarding this OpenFlow message. With the python-openflow (pyof) lib, only one variable became necessary."""
def __init__(self, this_packet):
"""Instantiate OFMessage class Args: self: this class this_packet: OpenFlow msg in binary format"""
... | stack_v2_sparse_classes_36k_train_004277 | 2,331 | permissive | [
{
"docstring": "Instantiate OFMessage class Args: self: this class this_packet: OpenFlow msg in binary format",
"name": "__init__",
"signature": "def __init__(self, this_packet)"
},
{
"docstring": "Generic printing function Args: pkt: Packet class",
"name": "print_packet",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_000900 | Implement the Python class `OFMessage` described below.
Class description:
Used to process all data regarding this OpenFlow message. With the python-openflow (pyof) lib, only one variable became necessary.
Method signatures and docstrings:
- def __init__(self, this_packet): Instantiate OFMessage class Args: self: thi... | Implement the Python class `OFMessage` described below.
Class description:
Used to process all data regarding this OpenFlow message. With the python-openflow (pyof) lib, only one variable became necessary.
Method signatures and docstrings:
- def __init__(self, this_packet): Instantiate OFMessage class Args: self: thi... | 4b79b6c9ebb8f237ed189c38eefc9e98226606f6 | <|skeleton|>
class OFMessage:
"""Used to process all data regarding this OpenFlow message. With the python-openflow (pyof) lib, only one variable became necessary."""
def __init__(self, this_packet):
"""Instantiate OFMessage class Args: self: this class this_packet: OpenFlow msg in binary format"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OFMessage:
"""Used to process all data regarding this OpenFlow message. With the python-openflow (pyof) lib, only one variable became necessary."""
def __init__(self, this_packet):
"""Instantiate OFMessage class Args: self: this class this_packet: OpenFlow msg in binary format"""
try:
... | the_stack_v2_python_sparse | libs/gen/ofmessage.py | amlight/ofp_sniffer | train | 16 |
0b437f1d9490256469d57263bcc0185705fa5d89 | [
"u = Group.objects.create(name='ADMINISTRACION')\nself.assertTrue(isinstance(u, Group))\nprint('Test de crear perfil, exitoso')",
"c = Client()\nc.login(username='nabil', password='123')\nresp = c.get('/perfil/listar_perfiles/', follow=True)\nself.assertEqual(resp.status_code, 200)\nprint('Test de listado de perf... | <|body_start_0|>
u = Group.objects.create(name='ADMINISTRACION')
self.assertTrue(isinstance(u, Group))
print('Test de crear perfil, exitoso')
<|end_body_0|>
<|body_start_1|>
c = Client()
c.login(username='nabil', password='123')
resp = c.get('/perfil/listar_perfiles/', f... | PerfilTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PerfilTestCase:
def test_crea_perfil(self):
"""Test para verificar la correcta creacion de un rol"""
<|body_0|>
def test_listar_perfiles(self):
"""Test para ver si se listan correctamente los usuarios"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_004278 | 799 | no_license | [
{
"docstring": "Test para verificar la correcta creacion de un rol",
"name": "test_crea_perfil",
"signature": "def test_crea_perfil(self)"
},
{
"docstring": "Test para ver si se listan correctamente los usuarios",
"name": "test_listar_perfiles",
"signature": "def test_listar_perfiles(sel... | 2 | stack_v2_sparse_classes_30k_val_000637 | Implement the Python class `PerfilTestCase` described below.
Class description:
Implement the PerfilTestCase class.
Method signatures and docstrings:
- def test_crea_perfil(self): Test para verificar la correcta creacion de un rol
- def test_listar_perfiles(self): Test para ver si se listan correctamente los usuarios | Implement the Python class `PerfilTestCase` described below.
Class description:
Implement the PerfilTestCase class.
Method signatures and docstrings:
- def test_crea_perfil(self): Test para verificar la correcta creacion de un rol
- def test_listar_perfiles(self): Test para ver si se listan correctamente los usuarios... | bd4e55661f7897d2294a27ce240c044192385102 | <|skeleton|>
class PerfilTestCase:
def test_crea_perfil(self):
"""Test para verificar la correcta creacion de un rol"""
<|body_0|>
def test_listar_perfiles(self):
"""Test para ver si se listan correctamente los usuarios"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PerfilTestCase:
def test_crea_perfil(self):
"""Test para verificar la correcta creacion de un rol"""
u = Group.objects.create(name='ADMINISTRACION')
self.assertTrue(isinstance(u, Group))
print('Test de crear perfil, exitoso')
def test_listar_perfiles(self):
"""Test... | the_stack_v2_python_sparse | apps/perfil/tests.py | nabilchamas/is2 | train | 0 | |
6ccd502a082eaf192a1f68bbce7f8d18e1d04648 | [
"super(AnswerManager, self).__init__()\nself.getters.update({'correct': 'get_general', 'end_exam': 'get_general', 'end_question_pool': 'get_general', 'label': 'get_general', 'name': 'get_general', 'next_question_pool': 'get_foreign_key', 'order': 'get_general', 'question': 'get_foreign_key', 'responses': 'get_many_... | <|body_start_0|>
super(AnswerManager, self).__init__()
self.getters.update({'correct': 'get_general', 'end_exam': 'get_general', 'end_question_pool': 'get_general', 'label': 'get_general', 'name': 'get_general', 'next_question_pool': 'get_foreign_key', 'order': 'get_general', 'question': 'get_foreign_ke... | Manage answers in the Power Reg system. **Attributes:** * *correct* -- True if this answer is a correct one. * *end_exam* -- When True and this answer is selected, end the exam after this question pool. * *end_question_pool* -- When True and this answer is selected, immediately end the question pool. * *label* -- The t... | AnswerManager | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnswerManager:
"""Manage answers in the Power Reg system. **Attributes:** * *correct* -- True if this answer is a correct one. * *end_exam* -- When True and this answer is selected, end the exam after this question pool. * *end_question_pool* -- When True and this answer is selected, immediately ... | stack_v2_sparse_classes_36k_train_004279 | 3,905 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Create a new Answer. :param auth_token: The authentication token of the acting user :type auth_token: pr_services.models.AuthToken :param question_id: primary key of question to which this ans... | 2 | null | Implement the Python class `AnswerManager` described below.
Class description:
Manage answers in the Power Reg system. **Attributes:** * *correct* -- True if this answer is a correct one. * *end_exam* -- When True and this answer is selected, end the exam after this question pool. * *end_question_pool* -- When True an... | Implement the Python class `AnswerManager` described below.
Class description:
Manage answers in the Power Reg system. **Attributes:** * *correct* -- True if this answer is a correct one. * *end_exam* -- When True and this answer is selected, end the exam after this question pool. * *end_question_pool* -- When True an... | a59457bc37f0501aea1f54d006a6de94ff80511c | <|skeleton|>
class AnswerManager:
"""Manage answers in the Power Reg system. **Attributes:** * *correct* -- True if this answer is a correct one. * *end_exam* -- When True and this answer is selected, end the exam after this question pool. * *end_question_pool* -- When True and this answer is selected, immediately ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnswerManager:
"""Manage answers in the Power Reg system. **Attributes:** * *correct* -- True if this answer is a correct one. * *end_exam* -- When True and this answer is selected, end the exam after this question pool. * *end_question_pool* -- When True and this answer is selected, immediately end the quest... | the_stack_v2_python_sparse | pr_services/exam_system/answer_manager.py | ninemoreminutes/openassign-server | train | 0 |
5d1aadb7c69aab49f4a3ba6a4c20d9919aaa38fb | [
"style = wx.CB_READONLY | wx.CB_DROPDOWN\niqItemComboBox.__init__(self, parent, id=wx.NewId(), size=DEFAULT_COMBO_SIZE, style=style)\nif requisites:\n self.appendItems(requisites)",
"selection = self.GetCurrentSelection()\nif selection >= 0:\n return self.items[selection]\nreturn None"
] | <|body_start_0|>
style = wx.CB_READONLY | wx.CB_DROPDOWN
iqItemComboBox.__init__(self, parent, id=wx.NewId(), size=DEFAULT_COMBO_SIZE, style=style)
if requisites:
self.appendItems(requisites)
<|end_body_0|>
<|body_start_1|>
selection = self.GetCurrentSelection()
if s... | Object requisite combobox class. | iqRequisiteComboBox | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class iqRequisiteComboBox:
"""Object requisite combobox class."""
def __init__(self, parent, requisites=None):
"""Constructor."""
<|body_0|>
def getSelectedRequisite(self):
"""Get selected requisite item data."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_004280 | 19,825 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, parent, requisites=None)"
},
{
"docstring": "Get selected requisite item data.",
"name": "getSelectedRequisite",
"signature": "def getSelectedRequisite(self)"
}
] | 2 | null | Implement the Python class `iqRequisiteComboBox` described below.
Class description:
Object requisite combobox class.
Method signatures and docstrings:
- def __init__(self, parent, requisites=None): Constructor.
- def getSelectedRequisite(self): Get selected requisite item data. | Implement the Python class `iqRequisiteComboBox` described below.
Class description:
Object requisite combobox class.
Method signatures and docstrings:
- def __init__(self, parent, requisites=None): Constructor.
- def getSelectedRequisite(self): Get selected requisite item data.
<|skeleton|>
class iqRequisiteComboBo... | 7550e242746cb2fb1219474463f8db21f8e3e114 | <|skeleton|>
class iqRequisiteComboBox:
"""Object requisite combobox class."""
def __init__(self, parent, requisites=None):
"""Constructor."""
<|body_0|>
def getSelectedRequisite(self):
"""Get selected requisite item data."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class iqRequisiteComboBox:
"""Object requisite combobox class."""
def __init__(self, parent, requisites=None):
"""Constructor."""
style = wx.CB_READONLY | wx.CB_DROPDOWN
iqItemComboBox.__init__(self, parent, id=wx.NewId(), size=DEFAULT_COMBO_SIZE, style=style)
if requisites:
... | the_stack_v2_python_sparse | iq/components/wx_filterchoicectrl/filter_builder_ctrl.py | XHermitOne/iq_framework | train | 1 |
50300abc226fe6ade6567f6861c443679a2441ff | [
"def dfs(nums, index, res, path):\n res.append(path)\n for i in range(index, len(nums)):\n dfs(nums, i + 1, res, path + [nums[i]])\nres = []\ndfs(nums, 0, res, [])\nreturn res",
"def dfs(nums, index, res, path):\n res.append(path)\n for i in range(index, len(nums)):\n if i > index and nu... | <|body_start_0|>
def dfs(nums, index, res, path):
res.append(path)
for i in range(index, len(nums)):
dfs(nums, i + 1, res, path + [nums[i]])
res = []
dfs(nums, 0, res, [])
return res
<|end_body_0|>
<|body_start_1|>
def dfs(nums, index, res... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subsets(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def subsetsWithDup(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def dfs(nums, index, r... | stack_v2_sparse_classes_36k_train_004281 | 1,525 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "subsets",
"signature": "def subsets(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "subsetsWithDup",
"signature": "def subsetsWithDup(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005136 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subsets(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def subsetsWithDup(self, nums): :type nums: List[int] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subsets(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def subsetsWithDup(self, nums): :type nums: List[int] :rtype: List[List[int]]
<|skeleton|>
class Solutio... | 35f324250739aa9b2cebdc84ff3c3e260717b199 | <|skeleton|>
class Solution:
def subsets(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def subsetsWithDup(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def subsets(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
def dfs(nums, index, res, path):
res.append(path)
for i in range(index, len(nums)):
dfs(nums, i + 1, res, path + [nums[i]])
res = []
dfs(nums, 0, res, ... | the_stack_v2_python_sparse | 78.py | ShyZhou/LeetCode-Python | train | 2 | |
676a2af9819ef697e86af220b7d64029ef60b16e | [
"super().__init__(process_list=process_list)\nself.collector_dict = collector_dict\nself.merge_func = merge_func",
"collect_dict = {}\nfor collector_key, collector in self.collector_dict.items():\n tmp_dict = collector()\n for key, value in tmp_dict.items():\n if self.merge_func is not None:\n ... | <|body_start_0|>
super().__init__(process_list=process_list)
self.collector_dict = collector_dict
self.merge_func = merge_func
<|end_body_0|>
<|body_start_1|>
collect_dict = {}
for collector_key, collector in self.collector_dict.items():
tmp_dict = collector()
... | A collector to collect the results of other Collectors For example: We have 2 collector, which named A and B. A can collect {"prediction": pd.Series} and B can collect {"IC": {"Xgboost": pd.Series, "LSTM": pd.Series}}. Then after this class's collect, we can collect {"A_prediction": pd.Series, "B_IC": {"Xgboost": pd.Se... | MergeCollector | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MergeCollector:
"""A collector to collect the results of other Collectors For example: We have 2 collector, which named A and B. A can collect {"prediction": pd.Series} and B can collect {"IC": {"Xgboost": pd.Series, "LSTM": pd.Series}}. Then after this class's collect, we can collect {"A_predict... | stack_v2_sparse_classes_36k_train_004282 | 10,057 | permissive | [
{
"docstring": "Init MergeCollector. Args: collector_dict (Dict[str,Collector]): the dict like {collector_key, Collector} process_list (List[Callable]): the list of processors or the instance of processor to process dict. merge_func (Callable): a method to generate outermost key. The given params are ``collecto... | 2 | stack_v2_sparse_classes_30k_train_019575 | Implement the Python class `MergeCollector` described below.
Class description:
A collector to collect the results of other Collectors For example: We have 2 collector, which named A and B. A can collect {"prediction": pd.Series} and B can collect {"IC": {"Xgboost": pd.Series, "LSTM": pd.Series}}. Then after this clas... | Implement the Python class `MergeCollector` described below.
Class description:
A collector to collect the results of other Collectors For example: We have 2 collector, which named A and B. A can collect {"prediction": pd.Series} and B can collect {"IC": {"Xgboost": pd.Series, "LSTM": pd.Series}}. Then after this clas... | 4c30e5827b74bcc45f14cf3ae0c1715459ed09ae | <|skeleton|>
class MergeCollector:
"""A collector to collect the results of other Collectors For example: We have 2 collector, which named A and B. A can collect {"prediction": pd.Series} and B can collect {"IC": {"Xgboost": pd.Series, "LSTM": pd.Series}}. Then after this class's collect, we can collect {"A_predict... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MergeCollector:
"""A collector to collect the results of other Collectors For example: We have 2 collector, which named A and B. A can collect {"prediction": pd.Series} and B can collect {"IC": {"Xgboost": pd.Series, "LSTM": pd.Series}}. Then after this class's collect, we can collect {"A_prediction": pd.Seri... | the_stack_v2_python_sparse | qlib/workflow/task/collect.py | microsoft/qlib | train | 12,822 |
951e9294f4c0d4c9c9346e4886fe1ecf234a15d0 | [
"if data is not None:\n if not isinstance(data, list):\n raise TypeError('data must be a list')\n if len(data) <= 2:\n raise ValueError('data must contain multiple values')\n mean = sum(data) / len(data)\n variance = 0\n for x in data:\n variance += (x - mean) ** 2\n variance ... | <|body_start_0|>
if data is not None:
if not isinstance(data, list):
raise TypeError('data must be a list')
if len(data) <= 2:
raise ValueError('data must contain multiple values')
mean = sum(data) / len(data)
variance = 0
... | Binomial class | Binomial | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Binomial:
"""Binomial class"""
def __init__(self, data=None, n=1, p=0.5):
"""Class constructor"""
<|body_0|>
def factorial(n):
"""Calculates the factorial of a given number"""
<|body_1|>
def pmf(self, k):
"""Calculates the value of the PMF fo... | stack_v2_sparse_classes_36k_train_004283 | 2,028 | no_license | [
{
"docstring": "Class constructor",
"name": "__init__",
"signature": "def __init__(self, data=None, n=1, p=0.5)"
},
{
"docstring": "Calculates the factorial of a given number",
"name": "factorial",
"signature": "def factorial(n)"
},
{
"docstring": "Calculates the value of the PMF... | 4 | stack_v2_sparse_classes_30k_train_010809 | Implement the Python class `Binomial` described below.
Class description:
Binomial class
Method signatures and docstrings:
- def __init__(self, data=None, n=1, p=0.5): Class constructor
- def factorial(n): Calculates the factorial of a given number
- def pmf(self, k): Calculates the value of the PMF for a given numbe... | Implement the Python class `Binomial` described below.
Class description:
Binomial class
Method signatures and docstrings:
- def __init__(self, data=None, n=1, p=0.5): Class constructor
- def factorial(n): Calculates the factorial of a given number
- def pmf(self, k): Calculates the value of the PMF for a given numbe... | 23162e01761cfa56158a1ebc88ac7709ff1c2af2 | <|skeleton|>
class Binomial:
"""Binomial class"""
def __init__(self, data=None, n=1, p=0.5):
"""Class constructor"""
<|body_0|>
def factorial(n):
"""Calculates the factorial of a given number"""
<|body_1|>
def pmf(self, k):
"""Calculates the value of the PMF fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Binomial:
"""Binomial class"""
def __init__(self, data=None, n=1, p=0.5):
"""Class constructor"""
if data is not None:
if not isinstance(data, list):
raise TypeError('data must be a list')
if len(data) <= 2:
raise ValueError('data mu... | the_stack_v2_python_sparse | math/0x03-probability/binomial.py | emmanavarro/holbertonschool-machine_learning | train | 0 |
ca237a19f521e42837ee457880a8919835add664 | [
"schema_info = SchemaRegistry.find_schema_info(schema_name)\nsdl = schema_info['sdl']\nschema = schema_from_sdl(sdl, schema_name=schema_name)\nschema_info['inst'] = schema\nreturn schema",
"schema = SchemaBakery._preheat(schema_name)\nawait schema.bake(custom_default_resolver, custom_default_type_resolver, custom... | <|body_start_0|>
schema_info = SchemaRegistry.find_schema_info(schema_name)
sdl = schema_info['sdl']
schema = schema_from_sdl(sdl, schema_name=schema_name)
schema_info['inst'] = schema
return schema
<|end_body_0|>
<|body_start_1|>
schema = SchemaBakery._preheat(schema_na... | Utility class in charge of baking schemas. | SchemaBakery | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchemaBakery:
"""Utility class in charge of baking schemas."""
def _preheat(schema_name: str) -> 'GraphQLSchema':
"""Loads the SDL and converts it to a GraphQLSchema instance before baking each registered objects of this schema. :param schema_name: name of the schema to treat :type s... | stack_v2_sparse_classes_36k_train_004284 | 2,812 | permissive | [
{
"docstring": "Loads the SDL and converts it to a GraphQLSchema instance before baking each registered objects of this schema. :param schema_name: name of the schema to treat :type schema_name: str :return: a pre-baked GraphQLSchema instance :rtype: GraphQLSchema",
"name": "_preheat",
"signature": "def... | 2 | null | Implement the Python class `SchemaBakery` described below.
Class description:
Utility class in charge of baking schemas.
Method signatures and docstrings:
- def _preheat(schema_name: str) -> 'GraphQLSchema': Loads the SDL and converts it to a GraphQLSchema instance before baking each registered objects of this schema... | Implement the Python class `SchemaBakery` described below.
Class description:
Utility class in charge of baking schemas.
Method signatures and docstrings:
- def _preheat(schema_name: str) -> 'GraphQLSchema': Loads the SDL and converts it to a GraphQLSchema instance before baking each registered objects of this schema... | 421c1e937f553d6a5bf2f30154022c0d77053cfb | <|skeleton|>
class SchemaBakery:
"""Utility class in charge of baking schemas."""
def _preheat(schema_name: str) -> 'GraphQLSchema':
"""Loads the SDL and converts it to a GraphQLSchema instance before baking each registered objects of this schema. :param schema_name: name of the schema to treat :type s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SchemaBakery:
"""Utility class in charge of baking schemas."""
def _preheat(schema_name: str) -> 'GraphQLSchema':
"""Loads the SDL and converts it to a GraphQLSchema instance before baking each registered objects of this schema. :param schema_name: name of the schema to treat :type schema_name: s... | the_stack_v2_python_sparse | tartiflette/schema/bakery.py | tartiflette/tartiflette | train | 586 |
68527588863cbf0e7231b2bfdabc04df8b4931b0 | [
"data = {}\nself.parse_bs(soup.find_all('b'), data)\nself.parse_tables(soup.find_all('table'), data)\nreturn [data]",
"for line in btags:\n if isinstance(line, bs4.element.Tag):\n if line.text.lower().strip().startswith('maintenance ticket #:'):\n data['maintenance_id'] = self.clean_line(line... | <|body_start_0|>
data = {}
self.parse_bs(soup.find_all('b'), data)
self.parse_tables(soup.find_all('table'), data)
return [data]
<|end_body_0|>
<|body_start_1|>
for line in btags:
if isinstance(line, bs4.element.Tag):
if line.text.lower().strip().star... | Notifications Parser for Zayo notifications. | HtmlParserZayo1 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HtmlParserZayo1:
"""Notifications Parser for Zayo notifications."""
def parse_html(self, soup):
"""Execute parsing."""
<|body_0|>
def parse_bs(self, btags: ResultSet, data: dict):
"""Parse B tag."""
<|body_1|>
def parse_tables(self, tables: ResultSet... | stack_v2_sparse_classes_36k_train_004285 | 3,773 | permissive | [
{
"docstring": "Execute parsing.",
"name": "parse_html",
"signature": "def parse_html(self, soup)"
},
{
"docstring": "Parse B tag.",
"name": "parse_bs",
"signature": "def parse_bs(self, btags: ResultSet, data: dict)"
},
{
"docstring": "Parse Table tag.",
"name": "parse_tables... | 3 | null | Implement the Python class `HtmlParserZayo1` described below.
Class description:
Notifications Parser for Zayo notifications.
Method signatures and docstrings:
- def parse_html(self, soup): Execute parsing.
- def parse_bs(self, btags: ResultSet, data: dict): Parse B tag.
- def parse_tables(self, tables: ResultSet, da... | Implement the Python class `HtmlParserZayo1` described below.
Class description:
Notifications Parser for Zayo notifications.
Method signatures and docstrings:
- def parse_html(self, soup): Execute parsing.
- def parse_bs(self, btags: ResultSet, data: dict): Parse B tag.
- def parse_tables(self, tables: ResultSet, da... | 2f89d326a1dea49de24b47448549d1715dee189c | <|skeleton|>
class HtmlParserZayo1:
"""Notifications Parser for Zayo notifications."""
def parse_html(self, soup):
"""Execute parsing."""
<|body_0|>
def parse_bs(self, btags: ResultSet, data: dict):
"""Parse B tag."""
<|body_1|>
def parse_tables(self, tables: ResultSet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HtmlParserZayo1:
"""Notifications Parser for Zayo notifications."""
def parse_html(self, soup):
"""Execute parsing."""
data = {}
self.parse_bs(soup.find_all('b'), data)
self.parse_tables(soup.find_all('table'), data)
return [data]
def parse_bs(self, btags: Res... | the_stack_v2_python_sparse | circuit_maintenance_parser/parsers/zayo.py | NickCostadura/circuit-maintenance-parser | train | 0 |
2b0e6a33813f253090c7df713f4f929fc4712d28 | [
"Json = json.loads(self.content)\ncount = len(Json['companylist'])\nassert count == 36",
"Json = json.loads(self.content)\ncount = len(Json['catalogs'])\nassert count == 10",
"Json = json.loads(self.content)\nid = api_company_data._bruce_company['id']\nfor item in range(len(Json['companylist'])):\n if Json['... | <|body_start_0|>
Json = json.loads(self.content)
count = len(Json['companylist'])
assert count == 36
<|end_body_0|>
<|body_start_1|>
Json = json.loads(self.content)
count = len(Json['catalogs'])
assert count == 10
<|end_body_1|>
<|body_start_2|>
Json = json.load... | Test_API_Company | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_API_Company:
def test_company_count(self):
"""验证接口公司数量"""
<|body_0|>
def test_catalog_count(self):
"""验证接口Catalog数量"""
<|body_1|>
def test_company_info(self):
"""验证接口公司详细数据信息"""
<|body_2|>
def test_catalog_info(self):
""... | stack_v2_sparse_classes_36k_train_004286 | 2,360 | no_license | [
{
"docstring": "验证接口公司数量",
"name": "test_company_count",
"signature": "def test_company_count(self)"
},
{
"docstring": "验证接口Catalog数量",
"name": "test_catalog_count",
"signature": "def test_catalog_count(self)"
},
{
"docstring": "验证接口公司详细数据信息",
"name": "test_company_info",
... | 4 | null | Implement the Python class `Test_API_Company` described below.
Class description:
Implement the Test_API_Company class.
Method signatures and docstrings:
- def test_company_count(self): 验证接口公司数量
- def test_catalog_count(self): 验证接口Catalog数量
- def test_company_info(self): 验证接口公司详细数据信息
- def test_catalog_info(self): 验证... | Implement the Python class `Test_API_Company` described below.
Class description:
Implement the Test_API_Company class.
Method signatures and docstrings:
- def test_company_count(self): 验证接口公司数量
- def test_catalog_count(self): 验证接口Catalog数量
- def test_company_info(self): 验证接口公司详细数据信息
- def test_catalog_info(self): 验证... | cc36a93c01c53f856426ccf2724848142524d9c0 | <|skeleton|>
class Test_API_Company:
def test_company_count(self):
"""验证接口公司数量"""
<|body_0|>
def test_catalog_count(self):
"""验证接口Catalog数量"""
<|body_1|>
def test_company_info(self):
"""验证接口公司详细数据信息"""
<|body_2|>
def test_catalog_info(self):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_API_Company:
def test_company_count(self):
"""验证接口公司数量"""
Json = json.loads(self.content)
count = len(Json['companylist'])
assert count == 36
def test_catalog_count(self):
"""验证接口Catalog数量"""
Json = json.loads(self.content)
count = len(Json['ca... | the_stack_v2_python_sparse | SilkTestStructure/testcase/test_api_company.py | activehuahua/python | train | 0 | |
8c427bb2076e8aeade30aa179a4338e208a62544 | [
"if self.current_user is None:\n return\nfilter_dict = {}\nfilters = [('username', str), ('email', str), ('priority', int), ('enabled', bool), ('auth_source', str), ('role_id', int), ('quota_id', int)]\nfor filt in filters:\n if filt[0] in self.request.arguments:\n if filt[1] == str:\n filte... | <|body_start_0|>
if self.current_user is None:
return
filter_dict = {}
filters = [('username', str), ('email', str), ('priority', int), ('enabled', bool), ('auth_source', str), ('role_id', int), ('quota_id', int)]
for filt in filters:
if filt[0] in self.request.ar... | The UserCollection API. Ops that interact with the User collection. | UserCollectionAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserCollectionAPI:
"""The UserCollection API. Ops that interact with the User collection."""
def get(self):
"""HTTP GET method"""
<|body_0|>
def post(self):
"""HTTP POST method."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if self.current_use... | stack_v2_sparse_classes_36k_train_004287 | 7,558 | permissive | [
{
"docstring": "HTTP GET method",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "HTTP POST method.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | null | Implement the Python class `UserCollectionAPI` described below.
Class description:
The UserCollection API. Ops that interact with the User collection.
Method signatures and docstrings:
- def get(self): HTTP GET method
- def post(self): HTTP POST method. | Implement the Python class `UserCollectionAPI` described below.
Class description:
The UserCollection API. Ops that interact with the User collection.
Method signatures and docstrings:
- def get(self): HTTP GET method
- def post(self): HTTP POST method.
<|skeleton|>
class UserCollectionAPI:
"""The UserCollection... | c8e0c908af1954a8b41d0f6de23d08589564f0ab | <|skeleton|>
class UserCollectionAPI:
"""The UserCollection API. Ops that interact with the User collection."""
def get(self):
"""HTTP GET method"""
<|body_0|>
def post(self):
"""HTTP POST method."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserCollectionAPI:
"""The UserCollection API. Ops that interact with the User collection."""
def get(self):
"""HTTP GET method"""
if self.current_user is None:
return
filter_dict = {}
filters = [('username', str), ('email', str), ('priority', int), ('enabled', ... | the_stack_v2_python_sparse | zoe_api/rest_api/user.py | DistributedSystemsGroup/zoe | train | 60 |
ad02543f5274f8ab00f2d797d0a6b8035633d1b3 | [
"if s == None or t == None:\n return False\nif s.val != t.val:\n return False\nque = []\nque.append((s, t))\nwhile len(que) != 0:\n sNode, tNode = que.pop(0)\n if sNode.val == tNode.val:\n if sNode.left != None and tNode.left != None:\n que.append((sNode.left, tNode.left))\n eli... | <|body_start_0|>
if s == None or t == None:
return False
if s.val != t.val:
return False
que = []
que.append((s, t))
while len(que) != 0:
sNode, tNode = que.pop(0)
if sNode.val == tNode.val:
if sNode.left != None and... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isEqualTree(self, s, t):
""":type s: TreeNode :type t: TreeNode"""
<|body_0|>
def isSubtree(self, s, t):
""":type s: TreeNode :type t: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if s == None or t == None:
... | stack_v2_sparse_classes_36k_train_004288 | 1,538 | permissive | [
{
"docstring": ":type s: TreeNode :type t: TreeNode",
"name": "isEqualTree",
"signature": "def isEqualTree(self, s, t)"
},
{
"docstring": ":type s: TreeNode :type t: TreeNode :rtype: bool",
"name": "isSubtree",
"signature": "def isSubtree(self, s, t)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isEqualTree(self, s, t): :type s: TreeNode :type t: TreeNode
- def isSubtree(self, s, t): :type s: TreeNode :type t: TreeNode :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isEqualTree(self, s, t): :type s: TreeNode :type t: TreeNode
- def isSubtree(self, s, t): :type s: TreeNode :type t: TreeNode :rtype: bool
<|skeleton|>
class Solution:
... | d137df53fa2489821b3c17ac22f24d9a1ae86304 | <|skeleton|>
class Solution:
def isEqualTree(self, s, t):
""":type s: TreeNode :type t: TreeNode"""
<|body_0|>
def isSubtree(self, s, t):
""":type s: TreeNode :type t: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isEqualTree(self, s, t):
""":type s: TreeNode :type t: TreeNode"""
if s == None or t == None:
return False
if s.val != t.val:
return False
que = []
que.append((s, t))
while len(que) != 0:
sNode, tNode = que.pop(0... | the_stack_v2_python_sparse | easy/subtree-of-another-tree.py | trilliwon/LeetCode | train | 0 | |
b95f8fd016c1b1356c24ed3daca5112055b740a7 | [
"size = len(prices)\nif size <= 0:\n return 0\nminIdx = 0\nmaxPro = 0\nfor i in range(1, size):\n if prices[i] < prices[minIdx]:\n minIdx = i\n maxPro = max(maxPro, prices[i] - prices[minIdx])\nreturn maxPro",
"size = len(prices)\nif size <= 0:\n return 0\ndp = [[0] * 2 for _ in range(size)]\nd... | <|body_start_0|>
size = len(prices)
if size <= 0:
return 0
minIdx = 0
maxPro = 0
for i in range(1, size):
if prices[i] < prices[minIdx]:
minIdx = i
maxPro = max(maxPro, prices[i] - prices[minIdx])
return maxPro
<|end_bod... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""贪心思想:固定了买入时间 vs 固定卖出时间 动态规划:dp[i]为卖出价是数组中第i个数字的最大利润,显然找出i-1中的最小值就可以了 https://mp.weixin.qq.com/s?__biz=MzAxODQxMDM0Mw==&mid=2247484509&idx=1&sn=21ace57f19d996d46e82bd7d806a2e3c&source=41#wechat_redirect"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_004289 | 4,159 | permissive | [
{
"docstring": "贪心思想:固定了买入时间 vs 固定卖出时间 动态规划:dp[i]为卖出价是数组中第i个数字的最大利润,显然找出i-1中的最小值就可以了 https://mp.weixin.qq.com/s?__biz=MzAxODQxMDM0Mw==&mid=2247484509&idx=1&sn=21ace57f19d996d46e82bd7d806a2e3c&source=41#wechat_redirect",
"name": "maxProfit",
"signature": "def maxProfit(self, prices: List[int]) -> int"
... | 3 | 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: 贪心思想:固定了买入时间 vs 固定卖出时间 动态规划:dp[i]为卖出价是数组中第i个数字的最大利润,显然找出i-1中的最小值就可以了 https://mp.weixin.qq.com/s?__biz=MzAxODQxMDM0Mw==&mid=22474845... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices: List[int]) -> int: 贪心思想:固定了买入时间 vs 固定卖出时间 动态规划:dp[i]为卖出价是数组中第i个数字的最大利润,显然找出i-1中的最小值就可以了 https://mp.weixin.qq.com/s?__biz=MzAxODQxMDM0Mw==&mid=22474845... | e8a1c6cae6547cbcb6e8494be6df685f3e7c837c | <|skeleton|>
class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""贪心思想:固定了买入时间 vs 固定卖出时间 动态规划:dp[i]为卖出价是数组中第i个数字的最大利润,显然找出i-1中的最小值就可以了 https://mp.weixin.qq.com/s?__biz=MzAxODQxMDM0Mw==&mid=2247484509&idx=1&sn=21ace57f19d996d46e82bd7d806a2e3c&source=41#wechat_redirect"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""贪心思想:固定了买入时间 vs 固定卖出时间 动态规划:dp[i]为卖出价是数组中第i个数字的最大利润,显然找出i-1中的最小值就可以了 https://mp.weixin.qq.com/s?__biz=MzAxODQxMDM0Mw==&mid=2247484509&idx=1&sn=21ace57f19d996d46e82bd7d806a2e3c&source=41#wechat_redirect"""
size = len(prices)
if... | the_stack_v2_python_sparse | 121-best-time-to-buy-and-sell-stock.py | yuenliou/leetcode | train | 0 | |
1889934b14d1cee0ce13c5c48692522caac2fe78 | [
"ws = set(wordDict)\nif s in ws:\n return True\ndp = [False for _ in range(len(s) + 1)]\ndp[0] = True\nfor end in range(len(dp)):\n for start in range(end):\n if dp[start] and s[start:end] in ws:\n dp[end] = True\nreturn dp[-1]",
"ws = set(wordDict)\nif s in ws:\n return True\nstack = [... | <|body_start_0|>
ws = set(wordDict)
if s in ws:
return True
dp = [False for _ in range(len(s) + 1)]
dp[0] = True
for end in range(len(dp)):
for start in range(end):
if dp[start] and s[start:end] in ws:
dp[end] = True
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordBreak2(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_0|>
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_004290 | 2,198 | no_license | [
{
"docstring": ":type s: str :type wordDict: List[str] :rtype: bool",
"name": "wordBreak2",
"signature": "def wordBreak2(self, s, wordDict)"
},
{
"docstring": ":type s: str :type wordDict: List[str] :rtype: bool",
"name": "wordBreak",
"signature": "def wordBreak(self, s, wordDict)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004014 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak2(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak2(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool
<|... | b4da922c4e8406c486760639b71e3ec50283ca43 | <|skeleton|>
class Solution:
def wordBreak2(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_0|>
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def wordBreak2(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
ws = set(wordDict)
if s in ws:
return True
dp = [False for _ in range(len(s) + 1)]
dp[0] = True
for end in range(len(dp)):
for start in... | the_stack_v2_python_sparse | current_session/python/139_redo2.py | YJL33/LeetCode | train | 3 | |
850f6b637d7e61d3ff78db91a8d5399b0597c28b | [
"self._resource = resource\nself._pin = pin\nself.data = {}\nself.available = True",
"try:\n if self._pin is None:\n response = requests.get(self._resource, timeout=10)\n self.data = response.json()['variables']\n else:\n try:\n if str(self._pin[0]) == 'A':\n r... | <|body_start_0|>
self._resource = resource
self._pin = pin
self.data = {}
self.available = True
<|end_body_0|>
<|body_start_1|>
try:
if self._pin is None:
response = requests.get(self._resource, timeout=10)
self.data = response.json()[... | The Class for handling the data retrieval for variables. | ArestData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArestData:
"""The Class for handling the data retrieval for variables."""
def __init__(self, resource, pin=None):
"""Initialize the data object."""
<|body_0|>
def update(self):
"""Get the latest data from aREST device."""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_004291 | 6,651 | permissive | [
{
"docstring": "Initialize the data object.",
"name": "__init__",
"signature": "def __init__(self, resource, pin=None)"
},
{
"docstring": "Get the latest data from aREST device.",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001861 | Implement the Python class `ArestData` described below.
Class description:
The Class for handling the data retrieval for variables.
Method signatures and docstrings:
- def __init__(self, resource, pin=None): Initialize the data object.
- def update(self): Get the latest data from aREST device. | Implement the Python class `ArestData` described below.
Class description:
The Class for handling the data retrieval for variables.
Method signatures and docstrings:
- def __init__(self, resource, pin=None): Initialize the data object.
- def update(self): Get the latest data from aREST device.
<|skeleton|>
class Are... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ArestData:
"""The Class for handling the data retrieval for variables."""
def __init__(self, resource, pin=None):
"""Initialize the data object."""
<|body_0|>
def update(self):
"""Get the latest data from aREST device."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArestData:
"""The Class for handling the data retrieval for variables."""
def __init__(self, resource, pin=None):
"""Initialize the data object."""
self._resource = resource
self._pin = pin
self.data = {}
self.available = True
def update(self):
"""Get ... | the_stack_v2_python_sparse | homeassistant/components/arest/sensor.py | home-assistant/core | train | 35,501 |
1a71a6b9d289cad134e1714029f12347194dca3e | [
"QtGui.QTabWidget.__init__(self, parent)\nself.__tabs = list()\nself.tabBar().setContextMenuPolicy(QtCore.Qt.CustomContextMenu)\nQtCore.QObject.connect(self.tabBar(), QtCore.SIGNAL('customContextMenuRequested(QPoint)'), self.showTabBarContextMenuSlot)",
"count = self.count()\nself.__tabs = self.__tabs[:index]\nfo... | <|body_start_0|>
QtGui.QTabWidget.__init__(self, parent)
self.__tabs = list()
self.tabBar().setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
QtCore.QObject.connect(self.tabBar(), QtCore.SIGNAL('customContextMenuRequested(QPoint)'), self.showTabBarContextMenuSlot)
<|end_body_0|>
<|body_... | Decorator for the QTabWidget class to change the visibility of tab items. | HideableTabWidget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HideableTabWidget:
"""Decorator for the QTabWidget class to change the visibility of tab items."""
def __init__(self, parent=None):
"""Constructor. @param tabWidget: TabWidget that you want to decorate. @type tabWidget: C{QtGui.QTabWidget} @param parent: Parent of this L{QtCore.QObje... | stack_v2_sparse_classes_36k_train_004292 | 14,327 | no_license | [
{
"docstring": "Constructor. @param tabWidget: TabWidget that you want to decorate. @type tabWidget: C{QtGui.QTabWidget} @param parent: Parent of this L{QtCore.QObject}. @type parent: C{QtCore.QObject}",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "Fetch ... | 4 | null | Implement the Python class `HideableTabWidget` described below.
Class description:
Decorator for the QTabWidget class to change the visibility of tab items.
Method signatures and docstrings:
- def __init__(self, parent=None): Constructor. @param tabWidget: TabWidget that you want to decorate. @type tabWidget: C{QtGui... | Implement the Python class `HideableTabWidget` described below.
Class description:
Decorator for the QTabWidget class to change the visibility of tab items.
Method signatures and docstrings:
- def __init__(self, parent=None): Constructor. @param tabWidget: TabWidget that you want to decorate. @type tabWidget: C{QtGui... | 958fda4f3064f9f6b2034da396a20ac9d9abd52f | <|skeleton|>
class HideableTabWidget:
"""Decorator for the QTabWidget class to change the visibility of tab items."""
def __init__(self, parent=None):
"""Constructor. @param tabWidget: TabWidget that you want to decorate. @type tabWidget: C{QtGui.QTabWidget} @param parent: Parent of this L{QtCore.QObje... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HideableTabWidget:
"""Decorator for the QTabWidget class to change the visibility of tab items."""
def __init__(self, parent=None):
"""Constructor. @param tabWidget: TabWidget that you want to decorate. @type tabWidget: C{QtGui.QTabWidget} @param parent: Parent of this L{QtCore.QObject}. @type pa... | the_stack_v2_python_sparse | src/datafinder/gui/user/common/widget/widget.py | DLR-SC/DataFinder | train | 9 |
abfe7c28341650c579e6785b774e3c6cd38c3d30 | [
"if not str_1 and (not str_2):\n return 0\nresult = JaroWinklerDistance.matches(str_1, str_2)\nm = result[0]\nif not m:\n return 0\nif not p:\n p = JaroWinklerDistance.P\nj = (m / len(str_1) + m / len(str_2) + (m - result[1]) / m) / 3\nreturn j + min(p, JaroWinklerDistance.MAX_P) * result[2] * (1 - j)",
... | <|body_start_0|>
if not str_1 and (not str_2):
return 0
result = JaroWinklerDistance.matches(str_1, str_2)
m = result[0]
if not m:
return 0
if not p:
p = JaroWinklerDistance.P
j = (m / len(str_1) + m / len(str_2) + (m - result[1]) / m) ... | JaroWinklerDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JaroWinklerDistance:
def jaro_winkler_distance(str_1, str_2, p=None):
"""jaro-winkler 距离 Keyword arguments: str_1 -- 字符串1 str_2 -- 字符串2 Return: 匹配值"""
<|body_0|>
def jaro_distance(str_1, str_2):
"""jaro 距离 Keyword arguments: str_1 -- 字符串1 str_2 -- 字符串2 Return: 匹配值"""... | stack_v2_sparse_classes_36k_train_004293 | 3,407 | no_license | [
{
"docstring": "jaro-winkler 距离 Keyword arguments: str_1 -- 字符串1 str_2 -- 字符串2 Return: 匹配值",
"name": "jaro_winkler_distance",
"signature": "def jaro_winkler_distance(str_1, str_2, p=None)"
},
{
"docstring": "jaro 距离 Keyword arguments: str_1 -- 字符串1 str_2 -- 字符串2 Return: 匹配值",
"name": "jaro_d... | 3 | stack_v2_sparse_classes_30k_test_001039 | Implement the Python class `JaroWinklerDistance` described below.
Class description:
Implement the JaroWinklerDistance class.
Method signatures and docstrings:
- def jaro_winkler_distance(str_1, str_2, p=None): jaro-winkler 距离 Keyword arguments: str_1 -- 字符串1 str_2 -- 字符串2 Return: 匹配值
- def jaro_distance(str_1, str_2... | Implement the Python class `JaroWinklerDistance` described below.
Class description:
Implement the JaroWinklerDistance class.
Method signatures and docstrings:
- def jaro_winkler_distance(str_1, str_2, p=None): jaro-winkler 距离 Keyword arguments: str_1 -- 字符串1 str_2 -- 字符串2 Return: 匹配值
- def jaro_distance(str_1, str_2... | 6bd8b923dd052ee1aa7efc468c505277b9f2c24f | <|skeleton|>
class JaroWinklerDistance:
def jaro_winkler_distance(str_1, str_2, p=None):
"""jaro-winkler 距离 Keyword arguments: str_1 -- 字符串1 str_2 -- 字符串2 Return: 匹配值"""
<|body_0|>
def jaro_distance(str_1, str_2):
"""jaro 距离 Keyword arguments: str_1 -- 字符串1 str_2 -- 字符串2 Return: 匹配值"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JaroWinklerDistance:
def jaro_winkler_distance(str_1, str_2, p=None):
"""jaro-winkler 距离 Keyword arguments: str_1 -- 字符串1 str_2 -- 字符串2 Return: 匹配值"""
if not str_1 and (not str_2):
return 0
result = JaroWinklerDistance.matches(str_1, str_2)
m = result[0]
if ... | the_stack_v2_python_sparse | algorithms/similarity/jaro_winkler_distance.py | zh826256645/my-algorithm-exercises | train | 0 | |
2518837864fadecf8d2f26c5d4480d4a0bac72eb | [
"if response.status_code == 404:\n if request.user and request.user.is_authenticated():\n return response\n return redirect_to_login(settings.LOGIN_URL, request.get_full_path())\nreturn response",
"if request.user.is_authenticated():\n return None\npath = request.path_info.lstrip('/')\nif any((m.m... | <|body_start_0|>
if response.status_code == 404:
if request.user and request.user.is_authenticated():
return response
return redirect_to_login(settings.LOGIN_URL, request.get_full_path())
return response
<|end_body_0|>
<|body_start_1|>
if request.user.is_... | LoginRequiredMiddleware | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoginRequiredMiddleware:
def process_response(self, request, response):
"""Force 404 responses to authenticate"""
<|body_0|>
def process_view(self, request, view_func, view_args, view_kwargs):
"""Force all views to authenticate"""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_004294 | 2,071 | no_license | [
{
"docstring": "Force 404 responses to authenticate",
"name": "process_response",
"signature": "def process_response(self, request, response)"
},
{
"docstring": "Force all views to authenticate",
"name": "process_view",
"signature": "def process_view(self, request, view_func, view_args, ... | 2 | stack_v2_sparse_classes_30k_train_016304 | Implement the Python class `LoginRequiredMiddleware` described below.
Class description:
Implement the LoginRequiredMiddleware class.
Method signatures and docstrings:
- def process_response(self, request, response): Force 404 responses to authenticate
- def process_view(self, request, view_func, view_args, view_kwar... | Implement the Python class `LoginRequiredMiddleware` described below.
Class description:
Implement the LoginRequiredMiddleware class.
Method signatures and docstrings:
- def process_response(self, request, response): Force 404 responses to authenticate
- def process_view(self, request, view_func, view_args, view_kwar... | cf22164721e32b68b540f0bbb1058ab2da90f3f0 | <|skeleton|>
class LoginRequiredMiddleware:
def process_response(self, request, response):
"""Force 404 responses to authenticate"""
<|body_0|>
def process_view(self, request, view_func, view_args, view_kwargs):
"""Force all views to authenticate"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoginRequiredMiddleware:
def process_response(self, request, response):
"""Force 404 responses to authenticate"""
if response.status_code == 404:
if request.user and request.user.is_authenticated():
return response
return redirect_to_login(settings.LOGIN... | the_stack_v2_python_sparse | colonialsite/coloauth/middleware.py | ColonialDevelopment/website | train | 3 | |
9f75a49d92e089e64bcbe77b2587becc1d28a79e | [
"super(FileObjectOutputWriter, self).__init__(encoding=encoding)\nself._errors = 'strict'\nself._file_object = file_object",
"try:\n encoded_string = codecs.encode(string, self._encoding, self._errors)\nexcept UnicodeEncodeError:\n if self._errors == 'strict':\n logging.error('Unable to properly writ... | <|body_start_0|>
super(FileObjectOutputWriter, self).__init__(encoding=encoding)
self._errors = 'strict'
self._file_object = file_object
<|end_body_0|>
<|body_start_1|>
try:
encoded_string = codecs.encode(string, self._encoding, self._errors)
except UnicodeEncodeErro... | File object command line interface output writer. This output writer relies on the file-like object having a write method. | FileObjectOutputWriter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileObjectOutputWriter:
"""File object command line interface output writer. This output writer relies on the file-like object having a write method."""
def __init__(self, file_object, encoding='utf-8'):
"""Initializes a file object output writer. Args: file_object (file): file-like ... | stack_v2_sparse_classes_36k_train_004295 | 29,440 | permissive | [
{
"docstring": "Initializes a file object output writer. Args: file_object (file): file-like object to read from. encoding (Optional[str]): output encoding.",
"name": "__init__",
"signature": "def __init__(self, file_object, encoding='utf-8')"
},
{
"docstring": "Writes a string to the output. Ar... | 2 | null | Implement the Python class `FileObjectOutputWriter` described below.
Class description:
File object command line interface output writer. This output writer relies on the file-like object having a write method.
Method signatures and docstrings:
- def __init__(self, file_object, encoding='utf-8'): Initializes a file o... | Implement the Python class `FileObjectOutputWriter` described below.
Class description:
File object command line interface output writer. This output writer relies on the file-like object having a write method.
Method signatures and docstrings:
- def __init__(self, file_object, encoding='utf-8'): Initializes a file o... | 28756d910e951a22c5f0b2bcf5184f055a19d544 | <|skeleton|>
class FileObjectOutputWriter:
"""File object command line interface output writer. This output writer relies on the file-like object having a write method."""
def __init__(self, file_object, encoding='utf-8'):
"""Initializes a file object output writer. Args: file_object (file): file-like ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileObjectOutputWriter:
"""File object command line interface output writer. This output writer relies on the file-like object having a write method."""
def __init__(self, file_object, encoding='utf-8'):
"""Initializes a file object output writer. Args: file_object (file): file-like object to rea... | the_stack_v2_python_sparse | dfvfs/helpers/command_line.py | log2timeline/dfvfs | train | 197 |
4cf8b8f58572406d62b286f382a289a28e5d022a | [
"res = []\npath = []\ntmp = 0\nend = (target + 1) // 2 + 1\nfor i in range(1, end):\n tmp += i\n path.append(i)\n while tmp > target:\n tmp -= path.pop(0)\n if tmp == target:\n res.append(deepcopy(path))\nreturn res",
"i, j, tmp = (1, 2, 3)\nres = []\nwhile i < j:\n j += 1\n tmp +=... | <|body_start_0|>
res = []
path = []
tmp = 0
end = (target + 1) // 2 + 1
for i in range(1, end):
tmp += i
path.append(i)
while tmp > target:
tmp -= path.pop(0)
if tmp == target:
res.append(deepcopy(pat... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findContinuousSequence(self, target):
""":type target: int :rtype: List[List[int]]"""
<|body_0|>
def findContinuousSequence0(self, target):
""":type target: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
re... | stack_v2_sparse_classes_36k_train_004296 | 1,547 | no_license | [
{
"docstring": ":type target: int :rtype: List[List[int]]",
"name": "findContinuousSequence",
"signature": "def findContinuousSequence(self, target)"
},
{
"docstring": ":type target: int :rtype: List[List[int]]",
"name": "findContinuousSequence0",
"signature": "def findContinuousSequence... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findContinuousSequence(self, target): :type target: int :rtype: List[List[int]]
- def findContinuousSequence0(self, target): :type target: int :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findContinuousSequence(self, target): :type target: int :rtype: List[List[int]]
- def findContinuousSequence0(self, target): :type target: int :rtype: List[List[int]]
<|skel... | 6e18c5d257840489cc3fb1079ae3804c743982a4 | <|skeleton|>
class Solution:
def findContinuousSequence(self, target):
""":type target: int :rtype: List[List[int]]"""
<|body_0|>
def findContinuousSequence0(self, target):
""":type target: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findContinuousSequence(self, target):
""":type target: int :rtype: List[List[int]]"""
res = []
path = []
tmp = 0
end = (target + 1) // 2 + 1
for i in range(1, end):
tmp += i
path.append(i)
while tmp > target:
... | the_stack_v2_python_sparse | 剑指 Offer 57 - II. 和为s的连续正数序列.py | yangyuxiang1996/leetcode | train | 0 | |
9db7794d7fad0e0ae313b8ce0d41928331e4c460 | [
"timestamp = self._GetRowValue(query_hash, row, value_name)\nif timestamp is None:\n return None\nreturn dfdatetime_webkit_time.WebKitTime(timestamp=timestamp)",
"query_hash = hash(query)\ncookie_name = self._GetRowValue(query_hash, row, 'name')\ncookie_data = self._GetRowValue(query_hash, row, 'value')\nhostn... | <|body_start_0|>
timestamp = self._GetRowValue(query_hash, row, value_name)
if timestamp is None:
return None
return dfdatetime_webkit_time.WebKitTime(timestamp=timestamp)
<|end_body_0|>
<|body_start_1|>
query_hash = hash(query)
cookie_name = self._GetRowValue(query_... | SQLite parser plugin for Google Chrome cookies database files. | BaseChromeCookiePlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseChromeCookiePlugin:
"""SQLite parser plugin for Google Chrome cookies database files."""
def _GetDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query tha... | stack_v2_sparse_classes_36k_train_004297 | 7,358 | permissive | [
{
"docstring": "Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row. row (sqlite3.Row): row. value_name (str): name of the value. Returns: dfdatetime.WebKitTime: date and time value or None if not available.",
"nam... | 2 | stack_v2_sparse_classes_30k_train_005534 | Implement the Python class `BaseChromeCookiePlugin` described below.
Class description:
SQLite parser plugin for Google Chrome cookies database files.
Method signatures and docstrings:
- def _GetDateTimeRowValue(self, query_hash, row, value_name): Retrieves a date and time value from the row. Args: query_hash (int): ... | Implement the Python class `BaseChromeCookiePlugin` described below.
Class description:
SQLite parser plugin for Google Chrome cookies database files.
Method signatures and docstrings:
- def _GetDateTimeRowValue(self, query_hash, row, value_name): Retrieves a date and time value from the row. Args: query_hash (int): ... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class BaseChromeCookiePlugin:
"""SQLite parser plugin for Google Chrome cookies database files."""
def _GetDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query tha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseChromeCookiePlugin:
"""SQLite parser plugin for Google Chrome cookies database files."""
def _GetDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced th... | the_stack_v2_python_sparse | plaso/parsers/sqlite_plugins/chrome_cookies.py | log2timeline/plaso | train | 1,506 |
c3ba88be45c9f72d8981313b479991319e52cc2b | [
"m = len(matrix)\nif m == 0:\n return False\nn = len(matrix[0])\nif n == 0:\n return False\ni = 0\nwhile i < m:\n arr = matrix[i]\n if arr[0] <= target and arr[-1] >= target:\n j = 0\n while j <= n:\n mid = (j + n) // 2\n if arr[mid] > target:\n n = mid... | <|body_start_0|>
m = len(matrix)
if m == 0:
return False
n = len(matrix[0])
if n == 0:
return False
i = 0
while i < m:
arr = matrix[i]
if arr[0] <= target and arr[-1] >= target:
j = 0
while j ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchMatrix1(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_004298 | 1,415 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix1",
"signature": "def searchMatrix1(self, matrix, target)"
},
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix",
"signature": "def searc... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix1(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :typ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix1(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :typ... | e5b018493bbd12edcdcd0434f35d9c358106d391 | <|skeleton|>
class Solution:
def searchMatrix1(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def searchMatrix1(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
m = len(matrix)
if m == 0:
return False
n = len(matrix[0])
if n == 0:
return False
i = 0
while i < m:
... | the_stack_v2_python_sparse | py/leetcode/240.py | wfeng1991/learnpy | train | 0 | |
efc1a33e3038e48869ff36655ad6f45dd0ee05a2 | [
"super().__init__()\nself.input_size = hidden_size\nself.hidden_size = hidden_size\nself.conv1 = nn.Conv2d(self.input_size, self.hidden_size, kernel_size=(3, 3), stride=1, padding=0)\nself.bn1 = nn.BatchNorm2d(self.hidden_size)\nself.relu = nn.ReLU()\nself.fc1 = nn.Linear(6 * 23, 1)",
"batch_size = x.size(0)\nx =... | <|body_start_0|>
super().__init__()
self.input_size = hidden_size
self.hidden_size = hidden_size
self.conv1 = nn.Conv2d(self.input_size, self.hidden_size, kernel_size=(3, 3), stride=1, padding=0)
self.bn1 = nn.BatchNorm2d(self.hidden_size)
self.relu = nn.ReLU()
se... | Track branch in Text Recommender head Structure | TrackBranch | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrackBranch:
"""Track branch in Text Recommender head Structure"""
def __init__(self, hidden_size):
"""Args: hidden_size (int): hidden state num"""
<|body_0|>
def forward(self, x):
"""Args: x (Torch.Tensor): lower contextual_feature [batch x hidden size x H/4 x W... | stack_v2_sparse_classes_36k_train_004299 | 15,467 | permissive | [
{
"docstring": "Args: hidden_size (int): hidden state num",
"name": "__init__",
"signature": "def __init__(self, hidden_size)"
},
{
"docstring": "Args: x (Torch.Tensor): lower contextual_feature [batch x hidden size x H/4 x W/4] Returns: Torch.Tensor: the learned discriminative track feature",
... | 2 | null | Implement the Python class `TrackBranch` described below.
Class description:
Track branch in Text Recommender head Structure
Method signatures and docstrings:
- def __init__(self, hidden_size): Args: hidden_size (int): hidden state num
- def forward(self, x): Args: x (Torch.Tensor): lower contextual_feature [batch x ... | Implement the Python class `TrackBranch` described below.
Class description:
Track branch in Text Recommender head Structure
Method signatures and docstrings:
- def __init__(self, hidden_size): Args: hidden_size (int): hidden state num
- def forward(self, x): Args: x (Torch.Tensor): lower contextual_feature [batch x ... | fb47a96d1a38f5ce634c6f12d710ed5300cc89fc | <|skeleton|>
class TrackBranch:
"""Track branch in Text Recommender head Structure"""
def __init__(self, hidden_size):
"""Args: hidden_size (int): hidden state num"""
<|body_0|>
def forward(self, x):
"""Args: x (Torch.Tensor): lower contextual_feature [batch x hidden size x H/4 x W... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TrackBranch:
"""Track branch in Text Recommender head Structure"""
def __init__(self, hidden_size):
"""Args: hidden_size (int): hidden state num"""
super().__init__()
self.input_size = hidden_size
self.hidden_size = hidden_size
self.conv1 = nn.Conv2d(self.input_siz... | the_stack_v2_python_sparse | davarocr/davarocr/davar_videotext/models/seg_heads/yoro_recommender_head.py | OCRWorld/DAVAR-Lab-OCR | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.