blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8c7aa92aa4ca212a63b1552454663ab55879021f | [
"self.is_breaking = is_breaking\nself.lease_break_type = lease_break_type\nself.lease_tye = lease_tye",
"if dictionary is None:\n return None\nis_breaking = dictionary.get('isBreaking')\nlease_break_type = dictionary.get('leaseBreakType')\nlease_tye = dictionary.get('leaseTye')\nreturn cls(is_breaking, lease_b... | <|body_start_0|>
self.is_breaking = is_breaking
self.lease_break_type = lease_break_type
self.lease_tye = lease_tye
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
is_breaking = dictionary.get('isBreaking')
lease_break_type = dictionary.get... | Implementation of the 'SmbLeaseInfo' model. TODO: type description here. Attributes: is_breaking (bool): Whether lease break is in progress lease_break_type (list of string): Lease type that is attempted to being broken. lease_tye (list of string): Lease type granted for open. | SmbLeaseInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SmbLeaseInfo:
"""Implementation of the 'SmbLeaseInfo' model. TODO: type description here. Attributes: is_breaking (bool): Whether lease break is in progress lease_break_type (list of string): Lease type that is attempted to being broken. lease_tye (list of string): Lease type granted for open."""... | stack_v2_sparse_classes_10k_train_005000 | 1,876 | permissive | [
{
"docstring": "Constructor for the SmbLeaseInfo class",
"name": "__init__",
"signature": "def __init__(self, is_breaking=None, lease_break_type=None, lease_tye=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representatio... | 2 | null | Implement the Python class `SmbLeaseInfo` described below.
Class description:
Implementation of the 'SmbLeaseInfo' model. TODO: type description here. Attributes: is_breaking (bool): Whether lease break is in progress lease_break_type (list of string): Lease type that is attempted to being broken. lease_tye (list of s... | Implement the Python class `SmbLeaseInfo` described below.
Class description:
Implementation of the 'SmbLeaseInfo' model. TODO: type description here. Attributes: is_breaking (bool): Whether lease break is in progress lease_break_type (list of string): Lease type that is attempted to being broken. lease_tye (list of s... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class SmbLeaseInfo:
"""Implementation of the 'SmbLeaseInfo' model. TODO: type description here. Attributes: is_breaking (bool): Whether lease break is in progress lease_break_type (list of string): Lease type that is attempted to being broken. lease_tye (list of string): Lease type granted for open."""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SmbLeaseInfo:
"""Implementation of the 'SmbLeaseInfo' model. TODO: type description here. Attributes: is_breaking (bool): Whether lease break is in progress lease_break_type (list of string): Lease type that is attempted to being broken. lease_tye (list of string): Lease type granted for open."""
def __i... | the_stack_v2_python_sparse | cohesity_management_sdk/models/smb_lease_info.py | cohesity/management-sdk-python | train | 24 |
f105f222d58f033bddb76f730e75dd63895e1fea | [
"if not email:\n raise ValueError('Users must have an email address')\nuser = self.model(email=MyUserManager.normalize_email(email), date_of_birth=date_of_birth, type_of=t)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"u = self.create_user(username, password=password, date_of_birth=da... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=MyUserManager.normalize_email(email), date_of_birth=date_of_birth, type_of=t)
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
... | MyUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyUserManager:
def create_user(self, email, date_of_birth, t, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, t, username, date_of_birth, password):
"""Creates and saves a superuse... | stack_v2_sparse_classes_10k_train_005001 | 13,331 | no_license | [
{
"docstring": "Creates and saves a User with the given email, date of birth and password.",
"name": "create_user",
"signature": "def create_user(self, email, date_of_birth, t, password=None)"
},
{
"docstring": "Creates and saves a superuser with the given email, date of birth and password.",
... | 2 | stack_v2_sparse_classes_30k_train_001098 | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, email, date_of_birth, t, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, t... | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, email, date_of_birth, t, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, t... | e6d052ef8998b3e495a64e41b191c124a0a53d6b | <|skeleton|>
class MyUserManager:
def create_user(self, email, date_of_birth, t, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, t, username, date_of_birth, password):
"""Creates and saves a superuse... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MyUserManager:
def create_user(self, email, date_of_birth, t, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=MyUserManager.normalize_... | the_stack_v2_python_sparse | agritrade/models.py | Django-Nawaz/hello_world | train | 0 | |
eae4089a43a2dcbe6b7c68a01ce7d96711c48aba | [
"self.bit = x\nfor i in range(len(x)):\n j = i | i + 1\n if j < len(x):\n x[j] += x[i]",
"while idx < len(self.bit):\n self.bit[idx] += x\n idx |= idx + 1",
"x = 0\nwhile end:\n x += self.bit[end - 1]\n end &= end - 1\nreturn x",
"idx = -1\nfor d in reversed(range(len(self.bit).bit_le... | <|body_start_0|>
self.bit = x
for i in range(len(x)):
j = i | i + 1
if j < len(x):
x[j] += x[i]
<|end_body_0|>
<|body_start_1|>
while idx < len(self.bit):
self.bit[idx] += x
idx |= idx + 1
<|end_body_1|>
<|body_start_2|>
x... | FenwickTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FenwickTree:
def __init__(self, x):
"""transform list into BIT"""
<|body_0|>
def update(self, idx, x):
"""updates bit[idx] += x"""
<|body_1|>
def query(self, end):
"""calc sum(bit[:end])"""
<|body_2|>
def find_kth_smallest(self, k):
... | stack_v2_sparse_classes_10k_train_005002 | 2,618 | no_license | [
{
"docstring": "transform list into BIT",
"name": "__init__",
"signature": "def __init__(self, x)"
},
{
"docstring": "updates bit[idx] += x",
"name": "update",
"signature": "def update(self, idx, x)"
},
{
"docstring": "calc sum(bit[:end])",
"name": "query",
"signature": "... | 4 | stack_v2_sparse_classes_30k_train_003904 | Implement the Python class `FenwickTree` described below.
Class description:
Implement the FenwickTree class.
Method signatures and docstrings:
- def __init__(self, x): transform list into BIT
- def update(self, idx, x): updates bit[idx] += x
- def query(self, end): calc sum(bit[:end])
- def find_kth_smallest(self, k... | Implement the Python class `FenwickTree` described below.
Class description:
Implement the FenwickTree class.
Method signatures and docstrings:
- def __init__(self, x): transform list into BIT
- def update(self, idx, x): updates bit[idx] += x
- def query(self, end): calc sum(bit[:end])
- def find_kth_smallest(self, k... | 57f473ca84735f9312913967e20a3ac0da32baa8 | <|skeleton|>
class FenwickTree:
def __init__(self, x):
"""transform list into BIT"""
<|body_0|>
def update(self, idx, x):
"""updates bit[idx] += x"""
<|body_1|>
def query(self, end):
"""calc sum(bit[:end])"""
<|body_2|>
def find_kth_smallest(self, k):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FenwickTree:
def __init__(self, x):
"""transform list into BIT"""
self.bit = x
for i in range(len(x)):
j = i | i + 1
if j < len(x):
x[j] += x[i]
def update(self, idx, x):
"""updates bit[idx] += x"""
while idx < len(self.bit):... | the_stack_v2_python_sparse | codeforces/current/c1354d/task.py | x3mka/code-contests-python | train | 0 | |
a7b124276b1dc7c6ca5f4e3e3290831a0c33f2bb | [
"self.AddSubDialog(GADGET_ID_SUBDIALOG, c4d.BFH_SCALEFIT | c4d.BFV_SCALEFIT, 100, 100)\nself.AttachSubDialog(self.subDialog, GADGET_ID_SUBDIALOG)\nself.AddButton(GADGET_ID_BUTTON_SWITCH_SUBDIALOG, c4d.BFH_SCALEFIT | c4d.BFV_SCALEFIT, name='Switch SubDialog')\nreturn True",
"if messageId == GADGET_ID_BUTTON_SWITCH... | <|body_start_0|>
self.AddSubDialog(GADGET_ID_SUBDIALOG, c4d.BFH_SCALEFIT | c4d.BFV_SCALEFIT, 100, 100)
self.AttachSubDialog(self.subDialog, GADGET_ID_SUBDIALOG)
self.AddButton(GADGET_ID_BUTTON_SWITCH_SUBDIALOG, c4d.BFH_SCALEFIT | c4d.BFV_SCALEFIT, name='Switch SubDialog')
return True
<|e... | ExampleDialog | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExampleDialog:
def CreateLayout(self):
"""This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog."""
<|body_0|>
def Command(self, messageId, bc):
"""This Method is called automatically when the user clicks on a gadget and/or chan... | stack_v2_sparse_classes_10k_train_005003 | 3,182 | permissive | [
{
"docstring": "This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog.",
"name": "CreateLayout",
"signature": "def CreateLayout(self)"
},
{
"docstring": "This Method is called automatically when the user clicks on a gadget and/or changes its value this func... | 2 | null | Implement the Python class `ExampleDialog` described below.
Class description:
Implement the ExampleDialog class.
Method signatures and docstrings:
- def CreateLayout(self): This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog.
- def Command(self, messageId, bc): This Method is... | Implement the Python class `ExampleDialog` described below.
Class description:
Implement the ExampleDialog class.
Method signatures and docstrings:
- def CreateLayout(self): This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog.
- def Command(self, messageId, bc): This Method is... | b1ea3fce533df34094bc3d0bd6460dfb84306e53 | <|skeleton|>
class ExampleDialog:
def CreateLayout(self):
"""This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog."""
<|body_0|>
def Command(self, messageId, bc):
"""This Method is called automatically when the user clicks on a gadget and/or chan... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ExampleDialog:
def CreateLayout(self):
"""This Method is called automatically when Cinema 4D Create the Layout (display) of the Dialog."""
self.AddSubDialog(GADGET_ID_SUBDIALOG, c4d.BFH_SCALEFIT | c4d.BFV_SCALEFIT, 100, 100)
self.AttachSubDialog(self.subDialog, GADGET_ID_SUBDIALOG)
... | the_stack_v2_python_sparse | scripts/03_application_development/gui/dialog/gedialog_subdialog_r19.py | PluginCafe/cinema4d_py_sdk_extended | train | 112 | |
2185f568dfc58b57aa889ecf6b3751374db57d2f | [
"self.etf_symbol = etfSymbol\nself.universe_settings = universeSettings\nself.universe_filter_function = universeFilterFunc\nself.universe = None",
"if self.universe is None:\n self.universe = algorithm.Universe.ETF(self.etf_symbol, self.universe_settings, self.universe_filter_function)\nreturn [self.universe]... | <|body_start_0|>
self.etf_symbol = etfSymbol
self.universe_settings = universeSettings
self.universe_filter_function = universeFilterFunc
self.universe = None
<|end_body_0|>
<|body_start_1|>
if self.universe is None:
self.universe = algorithm.Universe.ETF(self.etf_sy... | Universe selection model that selects the constituents of an ETF. | ETFConstituentsUniverseSelectionModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ETFConstituentsUniverseSelectionModel:
"""Universe selection model that selects the constituents of an ETF."""
def __init__(self, etfSymbol, universeSettings=None, universeFilterFunc=None):
"""Initializes a new instance of the ETFConstituentsUniverseSelectionModel class Args: etfSymb... | stack_v2_sparse_classes_10k_train_005004 | 2,049 | permissive | [
{
"docstring": "Initializes a new instance of the ETFConstituentsUniverseSelectionModel class Args: etfSymbol: Symbol of the ETF to get constituents for universeSettings: Universe settings universeFilterFunc: Function to filter universe results",
"name": "__init__",
"signature": "def __init__(self, etfS... | 2 | stack_v2_sparse_classes_30k_train_002943 | Implement the Python class `ETFConstituentsUniverseSelectionModel` described below.
Class description:
Universe selection model that selects the constituents of an ETF.
Method signatures and docstrings:
- def __init__(self, etfSymbol, universeSettings=None, universeFilterFunc=None): Initializes a new instance of the ... | Implement the Python class `ETFConstituentsUniverseSelectionModel` described below.
Class description:
Universe selection model that selects the constituents of an ETF.
Method signatures and docstrings:
- def __init__(self, etfSymbol, universeSettings=None, universeFilterFunc=None): Initializes a new instance of the ... | b33dd3bc140e14b883f39ecf848a793cf7292277 | <|skeleton|>
class ETFConstituentsUniverseSelectionModel:
"""Universe selection model that selects the constituents of an ETF."""
def __init__(self, etfSymbol, universeSettings=None, universeFilterFunc=None):
"""Initializes a new instance of the ETFConstituentsUniverseSelectionModel class Args: etfSymb... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ETFConstituentsUniverseSelectionModel:
"""Universe selection model that selects the constituents of an ETF."""
def __init__(self, etfSymbol, universeSettings=None, universeFilterFunc=None):
"""Initializes a new instance of the ETFConstituentsUniverseSelectionModel class Args: etfSymbol: Symbol of... | the_stack_v2_python_sparse | Algorithm.Framework/Selection/ETFConstituentsUniverseSelectionModel.py | Capnode/Algoloop | train | 87 |
8b45521141ccdbb54aff80605ac945d79988821a | [
"logger.info('Check 角色管理 begin')\nAPI().assertElementByName(self.testcase, self.driver, self.logger, Name.role_management)\nlogger.info('Check 角色管理 end')",
"logger.info('Check 角色列表 begin')\nname = API().getTextByXpath(self.testcase, self.driver, self.logger, Xpath.role_management_name)\ncreator = API().getTextByX... | <|body_start_0|>
logger.info('Check 角色管理 begin')
API().assertElementByName(self.testcase, self.driver, self.logger, Name.role_management)
logger.info('Check 角色管理 end')
<|end_body_0|>
<|body_start_1|>
logger.info('Check 角色列表 begin')
name = API().getTextByXpath(self.testcase, self... | RoleManagementPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoleManagementPage:
def validSelf(self):
"""验证角色列表页面 :return:"""
<|body_0|>
def checkRoleList(self):
"""检查角色列表是否为空 :return:"""
<|body_1|>
def clickOnNewRoleButton(self):
"""点击新建角色按钮 :return:"""
<|body_2|>
def validNewRolePage(self):
... | stack_v2_sparse_classes_10k_train_005005 | 4,182 | no_license | [
{
"docstring": "验证角色列表页面 :return:",
"name": "validSelf",
"signature": "def validSelf(self)"
},
{
"docstring": "检查角色列表是否为空 :return:",
"name": "checkRoleList",
"signature": "def checkRoleList(self)"
},
{
"docstring": "点击新建角色按钮 :return:",
"name": "clickOnNewRoleButton",
"sig... | 5 | stack_v2_sparse_classes_30k_test_000319 | Implement the Python class `RoleManagementPage` described below.
Class description:
Implement the RoleManagementPage class.
Method signatures and docstrings:
- def validSelf(self): 验证角色列表页面 :return:
- def checkRoleList(self): 检查角色列表是否为空 :return:
- def clickOnNewRoleButton(self): 点击新建角色按钮 :return:
- def validNewRolePa... | Implement the Python class `RoleManagementPage` described below.
Class description:
Implement the RoleManagementPage class.
Method signatures and docstrings:
- def validSelf(self): 验证角色列表页面 :return:
- def checkRoleList(self): 检查角色列表是否为空 :return:
- def clickOnNewRoleButton(self): 点击新建角色按钮 :return:
- def validNewRolePa... | 67e2acc9a99da81022e286e8d8ec7ccb12636ff3 | <|skeleton|>
class RoleManagementPage:
def validSelf(self):
"""验证角色列表页面 :return:"""
<|body_0|>
def checkRoleList(self):
"""检查角色列表是否为空 :return:"""
<|body_1|>
def clickOnNewRoleButton(self):
"""点击新建角色按钮 :return:"""
<|body_2|>
def validNewRolePage(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RoleManagementPage:
def validSelf(self):
"""验证角色列表页面 :return:"""
logger.info('Check 角色管理 begin')
API().assertElementByName(self.testcase, self.driver, self.logger, Name.role_management)
logger.info('Check 角色管理 end')
def checkRoleList(self):
"""检查角色列表是否为空 :return:""... | the_stack_v2_python_sparse | pages/ios/shanghu/roleManagementPage.py | liu111xiao111/UItest | train | 1 | |
ff9694ad78dfb898ae3265f5f52c650e13633d35 | [
"self.data = data\nself.event = event\nself.id = id\nself.retry = retry\nself.comment = comment\nself.DEFAULT_SEPARATOR = '\\r\\n'\nself.LINE_SEP_EXPR = re.compile('\\\\r\\\\n|\\\\r|\\\\n')\nself._sep = sep if sep is not None else self.DEFAULT_SEPARATOR",
"buffer = io.StringIO()\nif self.comment is not None:\n ... | <|body_start_0|>
self.data = data
self.event = event
self.id = id
self.retry = retry
self.comment = comment
self.DEFAULT_SEPARATOR = '\r\n'
self.LINE_SEP_EXPR = re.compile('\\r\\n|\\r|\\n')
self._sep = sep if sep is not None else self.DEFAULT_SEPARATOR
<|e... | Class to manage Server-Sent Events | ServerSentEvent | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServerSentEvent:
"""Class to manage Server-Sent Events"""
def __init__(self, data: Optional[Any]=None, *, event: Optional[str]=None, id: Optional[int]=None, retry: Optional[int]=None, comment: Optional[str]=None, sep: Optional[str]=None) -> None:
"""Send data using EventSource protoc... | stack_v2_sparse_classes_10k_train_005006 | 13,447 | permissive | [
{
"docstring": "Send data using EventSource protocol # noqa: DAR101 :param data: The data field for the message. :param event: The event's type. If this is specified, an event will be dispatched on the browser to the listener for the specified event name; the web site would use addEventListener() to listen for ... | 2 | stack_v2_sparse_classes_30k_train_005009 | Implement the Python class `ServerSentEvent` described below.
Class description:
Class to manage Server-Sent Events
Method signatures and docstrings:
- def __init__(self, data: Optional[Any]=None, *, event: Optional[str]=None, id: Optional[int]=None, retry: Optional[int]=None, comment: Optional[str]=None, sep: Option... | Implement the Python class `ServerSentEvent` described below.
Class description:
Class to manage Server-Sent Events
Method signatures and docstrings:
- def __init__(self, data: Optional[Any]=None, *, event: Optional[str]=None, id: Optional[int]=None, retry: Optional[int]=None, comment: Optional[str]=None, sep: Option... | 23c7b8c78fc4ad67d16d83fc0c9f0eae9e935e71 | <|skeleton|>
class ServerSentEvent:
"""Class to manage Server-Sent Events"""
def __init__(self, data: Optional[Any]=None, *, event: Optional[str]=None, id: Optional[int]=None, retry: Optional[int]=None, comment: Optional[str]=None, sep: Optional[str]=None) -> None:
"""Send data using EventSource protoc... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ServerSentEvent:
"""Class to manage Server-Sent Events"""
def __init__(self, data: Optional[Any]=None, *, event: Optional[str]=None, id: Optional[int]=None, retry: Optional[int]=None, comment: Optional[str]=None, sep: Optional[str]=None) -> None:
"""Send data using EventSource protocol # noqa: DA... | the_stack_v2_python_sparse | jina/serve/networking/sse.py | jina-ai/jina | train | 20,687 |
9245ee49519a383f37c2562e1b192473e28e7025 | [
"if not spec.act_space.flat_dim % 2 == 0:\n raise pyrado.ShapeErr(msg='DualRBFLinearPolicy only works with an even number of actions, since we are using the time derivative of the features to create the second half of the outputs. This is done to use forward() in order to obtain the joint position and the joint ... | <|body_start_0|>
if not spec.act_space.flat_dim % 2 == 0:
raise pyrado.ShapeErr(msg='DualRBFLinearPolicy only works with an even number of actions, since we are using the time derivative of the features to create the second half of the outputs. This is done to use forward() in order to obtain the jo... | A linear policy with RBF features which are also used to get the derivative of the features. The use-case in mind is a simple policy which generates the joint position and joint velocity commands for the internal PD-controller of a robot (e.g. Barrett WAM). By re-using the RBF, we reduce the number of parameters, while... | DualRBFLinearPolicy | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DualRBFLinearPolicy:
"""A linear policy with RBF features which are also used to get the derivative of the features. The use-case in mind is a simple policy which generates the joint position and joint velocity commands for the internal PD-controller of a robot (e.g. Barrett WAM). By re-using the... | stack_v2_sparse_classes_10k_train_005007 | 6,470 | permissive | [
{
"docstring": "Constructor :param spec: specification of environment :param rbf_hparam: hyper-parameters for the RBF-features, see `RBFFeat` :param dim_mask: number of RBF features to mask out at the beginning and the end of every dimension, pass 1 to remove the first and the last features for the policy, pass... | 2 | null | Implement the Python class `DualRBFLinearPolicy` described below.
Class description:
A linear policy with RBF features which are also used to get the derivative of the features. The use-case in mind is a simple policy which generates the joint position and joint velocity commands for the internal PD-controller of a ro... | Implement the Python class `DualRBFLinearPolicy` described below.
Class description:
A linear policy with RBF features which are also used to get the derivative of the features. The use-case in mind is a simple policy which generates the joint position and joint velocity commands for the internal PD-controller of a ro... | d7e9cd191ccb318d5f1e580babc2fc38b5b3675a | <|skeleton|>
class DualRBFLinearPolicy:
"""A linear policy with RBF features which are also used to get the derivative of the features. The use-case in mind is a simple policy which generates the joint position and joint velocity commands for the internal PD-controller of a robot (e.g. Barrett WAM). By re-using the... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DualRBFLinearPolicy:
"""A linear policy with RBF features which are also used to get the derivative of the features. The use-case in mind is a simple policy which generates the joint position and joint velocity commands for the internal PD-controller of a robot (e.g. Barrett WAM). By re-using the RBF, we redu... | the_stack_v2_python_sparse | Pyrado/pyrado/policies/feed_back/dual_rfb.py | 1abner1/SimuRLacra | train | 0 |
15297ba52e6b0e0daecf1743890059a7c2088174 | [
"assert isinstance(name, str), 'Invalid name %s' % name\nassert isinstance(description, str), 'Invalid description %s' % description\nself.name = name.strip()\nself.description = description.strip()\nself._rights = {}\nself._defaults = []",
"if isinstance(names, str):\n names = (names,)\nassert isinstance(name... | <|body_start_0|>
assert isinstance(name, str), 'Invalid name %s' % name
assert isinstance(description, str), 'Invalid description %s' % description
self.name = name.strip()
self.description = description.strip()
self._rights = {}
self._defaults = []
<|end_body_0|>
<|body... | The ACL type model. | TypeAcl | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TypeAcl:
"""The ACL type model."""
def __init__(self, name, description):
"""Construct the type model. @param name: string The type name. @param description: string The description for the type."""
<|body_0|>
def rightsFor(self, names):
"""Provides the rights for... | stack_v2_sparse_classes_10k_train_005008 | 5,791 | no_license | [
{
"docstring": "Construct the type model. @param name: string The type name. @param description: string The description for the type.",
"name": "__init__",
"signature": "def __init__(self, name, description)"
},
{
"docstring": "Provides the rights for the provided name(s). @param names: string|I... | 4 | stack_v2_sparse_classes_30k_train_007227 | Implement the Python class `TypeAcl` described below.
Class description:
The ACL type model.
Method signatures and docstrings:
- def __init__(self, name, description): Construct the type model. @param name: string The type name. @param description: string The description for the type.
- def rightsFor(self, names): Pr... | Implement the Python class `TypeAcl` described below.
Class description:
The ACL type model.
Method signatures and docstrings:
- def __init__(self, name, description): Construct the type model. @param name: string The type name. @param description: string The description for the type.
- def rightsFor(self, names): Pr... | a10cb774c8cbc5010950eed9342413846734fea7 | <|skeleton|>
class TypeAcl:
"""The ACL type model."""
def __init__(self, name, description):
"""Construct the type model. @param name: string The type name. @param description: string The description for the type."""
<|body_0|>
def rightsFor(self, names):
"""Provides the rights for... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TypeAcl:
"""The ACL type model."""
def __init__(self, name, description):
"""Construct the type model. @param name: string The type name. @param description: string The description for the type."""
assert isinstance(name, str), 'Invalid name %s' % name
assert isinstance(descriptio... | the_stack_v2_python_sparse | plugins/support-acl/acl/spec.py | bonomali/Ally-Py | train | 0 |
275fa2c7e5d4e146c26456ec9769dc22ac47e764 | [
"n = len(arr)\nbest_i = 0\ndist = sum([abs(arr[i] - x) for i in range(k)])\nfor i in range(1, n - k + 1):\n new_dist = dist - abs(arr[i - 1] - x) + abs(arr[i + (k - 1)] - x)\n if new_dist < dist:\n dist = new_dist\n best_i = i\nreturn arr[best_i:best_i + k]",
"n = len(arr)\nl, r = (0, n)\nwhil... | <|body_start_0|>
n = len(arr)
best_i = 0
dist = sum([abs(arr[i] - x) for i in range(k)])
for i in range(1, n - k + 1):
new_dist = dist - abs(arr[i - 1] - x) + abs(arr[i + (k - 1)] - x)
if new_dist < dist:
dist = new_dist
best_i = i
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
"""Sliding Window, Time: O(n), Space: O(k) for returns"""
<|body_0|>
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
"""Binary Search, Time: O(logn+k), S... | stack_v2_sparse_classes_10k_train_005009 | 1,595 | no_license | [
{
"docstring": "Sliding Window, Time: O(n), Space: O(k) for returns",
"name": "findClosestElements",
"signature": "def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]"
},
{
"docstring": "Binary Search, Time: O(logn+k), Space: O(k) for returns",
"name": "findClosestElem... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: Sliding Window, Time: O(n), Space: O(k) for returns
- def findClosestElements(self, arr: List[int], k:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: Sliding Window, Time: O(n), Space: O(k) for returns
- def findClosestElements(self, arr: List[int], k:... | 72136e3487d239f5b37e2d6393e034262a6bf599 | <|skeleton|>
class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
"""Sliding Window, Time: O(n), Space: O(k) for returns"""
<|body_0|>
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
"""Binary Search, Time: O(logn+k), S... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
"""Sliding Window, Time: O(n), Space: O(k) for returns"""
n = len(arr)
best_i = 0
dist = sum([abs(arr[i] - x) for i in range(k)])
for i in range(1, n - k + 1):
new_dist = d... | the_stack_v2_python_sparse | python/658-Find K Closest Elements.py | cwza/leetcode | train | 0 | |
5b438eb08862e916099a0a789fa411f3c93badb8 | [
"def preorder(root):\n res = []\n if root:\n res += [str(root.val)]\n res += preorder(root.left)\n res += preorder(root.right)\n return res\nreturn ','.join(preorder(root))",
"if not data:\n return None\n\ndef build_tree(pre_o, in_o):\n if not pre_o:\n return None\n m... | <|body_start_0|>
def preorder(root):
res = []
if root:
res += [str(root.val)]
res += preorder(root.left)
res += preorder(root.right)
return res
return ','.join(preorder(root))
<|end_body_0|>
<|body_start_1|>
if ... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def preorder(r... | stack_v2_sparse_classes_10k_train_005010 | 1,118 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_004645 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | 33eb204b1c7229ecb42651b17287d39164967e44 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
def preorder(root):
res = []
if root:
res += [str(root.val)]
res += preorder(root.left)
res += preorder(root.right)
re... | the_stack_v2_python_sparse | Binary_tree/449. Serialize and Deserialize BST.py | WujiaShi/Leetcode | train | 0 | |
1520a971329c4150b93b3ff3ce58efa576077087 | [
"super().__init__(epsilon, 0, max_string_length, fragment_length, alphabet, index_mapper, fo_client, padding_char)\nself.hash_length = 256\nself.hash_256 = lambda x: generate_256_hash()(x) % self.hash_length\nself.word_client = self.client\nif frag_client is not None:\n self.fragment_client = copy.deepcopy(self.... | <|body_start_0|>
super().__init__(epsilon, 0, max_string_length, fragment_length, alphabet, index_mapper, fo_client, padding_char)
self.hash_length = 256
self.hash_256 = lambda x: generate_256_hash()(x) % self.hash_length
self.word_client = self.client
if frag_client is not None:... | SFPClient | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SFPClient:
def __init__(self, epsilon, fragment_length, max_string_length, alphabet=None, index_mapper=None, fo_client=None, frag_client=None, padding_char='*'):
"""Args: epsilon: float privacy budget fragment_length (int): The length to increase the fragment by on each iteration max_str... | stack_v2_sparse_classes_10k_train_005011 | 3,799 | permissive | [
{
"docstring": "Args: epsilon: float privacy budget fragment_length (int): The length to increase the fragment by on each iteration max_string_length (int): maximum size of the strings to find alphabet (optional list): The alphabet over which we are privatising strings index_mapper (optional func): Index map fu... | 3 | stack_v2_sparse_classes_30k_train_007156 | Implement the Python class `SFPClient` described below.
Class description:
Implement the SFPClient class.
Method signatures and docstrings:
- def __init__(self, epsilon, fragment_length, max_string_length, alphabet=None, index_mapper=None, fo_client=None, frag_client=None, padding_char='*'): Args: epsilon: float priv... | Implement the Python class `SFPClient` described below.
Class description:
Implement the SFPClient class.
Method signatures and docstrings:
- def __init__(self, epsilon, fragment_length, max_string_length, alphabet=None, index_mapper=None, fo_client=None, frag_client=None, padding_char='*'): Args: epsilon: float priv... | d0fe2a8ce29515a638d6964419b72b58046dcc44 | <|skeleton|>
class SFPClient:
def __init__(self, epsilon, fragment_length, max_string_length, alphabet=None, index_mapper=None, fo_client=None, frag_client=None, padding_char='*'):
"""Args: epsilon: float privacy budget fragment_length (int): The length to increase the fragment by on each iteration max_str... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SFPClient:
def __init__(self, epsilon, fragment_length, max_string_length, alphabet=None, index_mapper=None, fo_client=None, frag_client=None, padding_char='*'):
"""Args: epsilon: float privacy budget fragment_length (int): The length to increase the fragment by on each iteration max_string_length (in... | the_stack_v2_python_sparse | pure_ldp/heavy_hitters/apple_sfp/sfp_client.py | hbcbh1999/pure-LDP | train | 0 | |
0f375f0f5bc5ff81b28b2302bee2d5b5a5954aac | [
"if not root:\n return []\ncurr_lvl = [root]\nres = [root.val]\nwhile curr_lvl:\n nxt_lvl = []\n for node in curr_lvl:\n if node.left:\n nxt_lvl.append(node.left)\n res.append(node.left.val)\n else:\n res.append(None)\n if node.right:\n nxt_l... | <|body_start_0|>
if not root:
return []
curr_lvl = [root]
res = [root.val]
while curr_lvl:
nxt_lvl = []
for node in curr_lvl:
if node.left:
nxt_lvl.append(node.left)
res.append(node.left.val)
... | 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_10k_train_005012 | 4,842 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_002186 | 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:... | 63120dbaabd7c3c19633ebe952bcee4cf826b0e0 | <|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_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return []
curr_lvl = [root]
res = [root.val]
while curr_lvl:
nxt_lvl = []
for node in curr_lvl:
i... | the_stack_v2_python_sparse | 297. Serialize and Deserialize Binary Tree _ tee.py | CaizhiXu/LeetCode-Python-Solutions | train | 0 | |
dff422604925852beb33243f2541cb8ced386921 | [
"if x < 0:\n return False\nx_str = str(x)\ny_str = x_str[::-1]\nif y_str == x_str:\n return True\nelse:\n return False",
"if x < 0:\n return False\nelif x == 0:\n return True\nori_x = x\ntemp = 0\nwhile x != 0:\n temp = temp * 10 + x % 10\n x //= 10\nreturn temp == ori_x"
] | <|body_start_0|>
if x < 0:
return False
x_str = str(x)
y_str = x_str[::-1]
if y_str == x_str:
return True
else:
return False
<|end_body_0|>
<|body_start_1|>
if x < 0:
return False
elif x == 0:
return Tru... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindromeByStr(self, x: int) -> bool:
"""使用字符串转置的方法 :param x: :return:"""
<|body_0|>
def isPalindromeByNum(self, x: int) -> bool:
"""使用数字运算的方法 :param x: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if x < 0:
... | stack_v2_sparse_classes_10k_train_005013 | 784 | no_license | [
{
"docstring": "使用字符串转置的方法 :param x: :return:",
"name": "isPalindromeByStr",
"signature": "def isPalindromeByStr(self, x: int) -> bool"
},
{
"docstring": "使用数字运算的方法 :param x: :return:",
"name": "isPalindromeByNum",
"signature": "def isPalindromeByNum(self, x: int) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_train_005013 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindromeByStr(self, x: int) -> bool: 使用字符串转置的方法 :param x: :return:
- def isPalindromeByNum(self, x: int) -> bool: 使用数字运算的方法 :param x: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindromeByStr(self, x: int) -> bool: 使用字符串转置的方法 :param x: :return:
- def isPalindromeByNum(self, x: int) -> bool: 使用数字运算的方法 :param x: :return:
<|skeleton|>
class Solutio... | 976d9185eca401587000dab56b6330542bc8437c | <|skeleton|>
class Solution:
def isPalindromeByStr(self, x: int) -> bool:
"""使用字符串转置的方法 :param x: :return:"""
<|body_0|>
def isPalindromeByNum(self, x: int) -> bool:
"""使用数字运算的方法 :param x: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isPalindromeByStr(self, x: int) -> bool:
"""使用字符串转置的方法 :param x: :return:"""
if x < 0:
return False
x_str = str(x)
y_str = x_str[::-1]
if y_str == x_str:
return True
else:
return False
def isPalindromeByNum(... | the_stack_v2_python_sparse | leetcode/algorithm/9.py | baiasuka/PyhtonStudy | train | 0 | |
3dd91cc93c8bc86f00eac0d0ee85f03854951643 | [
"if not prices:\n return 0\nlowest_buy, max_profit = (prices[0], 0)\nfor i in range(len(prices)):\n lowest_buy = min(prices[i], lowest_buy)\n max_profit = max(prices[i] - lowest_buy, max_profit)\nreturn max_profit",
"lowest_buy, max_profit = (2147483647, 0)\nfor price in prices:\n if price < lowest_bu... | <|body_start_0|>
if not prices:
return 0
lowest_buy, max_profit = (prices[0], 0)
for i in range(len(prices)):
lowest_buy = min(prices[i], lowest_buy)
max_profit = max(prices[i] - lowest_buy, max_profit)
return max_profit
<|end_body_0|>
<|body_start_1|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit1(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not prices:
return 0
... | stack_v2_sparse_classes_10k_train_005014 | 1,138 | no_license | [
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit1",
"signature": "def maxProfit1(self, prices)"
},
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000214 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit1(self, prices): :type prices: List[int] :rtype: int
- def maxProfit(self, prices): :type prices: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit1(self, prices): :type prices: List[int] :rtype: int
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxPro... | 4a1747b6497305f3821612d9c358a6795b1690da | <|skeleton|>
class Solution:
def maxProfit1(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit1(self, prices):
""":type prices: List[int] :rtype: int"""
if not prices:
return 0
lowest_buy, max_profit = (prices[0], 0)
for i in range(len(prices)):
lowest_buy = min(prices[i], lowest_buy)
max_profit = max(prices[i] ... | the_stack_v2_python_sparse | DynamicProgramming/q121_best_time_to_buy_and_sell_stock.py | sevenhe716/LeetCode | train | 0 | |
2a0f1758b49a14d0ea3e0886e74fd3e3e7f18c6b | [
"username = self.cleaned_data['username']\nif User.objects.filter(username=username).exists():\n raise forms.ValidationError('用户名已存在')\nreturn username",
"email = self.cleaned_data['email']\nif User.objects.filter(email=email).exists():\n raise forms.ValidationError('邮箱已存在')\nreturn email",
"password = se... | <|body_start_0|>
username = self.cleaned_data['username']
if User.objects.filter(username=username).exists():
raise forms.ValidationError('用户名已存在')
return username
<|end_body_0|>
<|body_start_1|>
email = self.cleaned_data['email']
if User.objects.filter(email=email).... | 注册表单 | RegisterForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegisterForm:
"""注册表单"""
def clean_username(self):
"""验证用户名 :return:"""
<|body_0|>
def clean_email(self):
"""验证邮箱 :return:"""
<|body_1|>
def clean_password_again(self):
"""验证两次输入的密码是否一致 :return:"""
<|body_2|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_10k_train_005015 | 10,740 | no_license | [
{
"docstring": "验证用户名 :return:",
"name": "clean_username",
"signature": "def clean_username(self)"
},
{
"docstring": "验证邮箱 :return:",
"name": "clean_email",
"signature": "def clean_email(self)"
},
{
"docstring": "验证两次输入的密码是否一致 :return:",
"name": "clean_password_again",
"s... | 3 | stack_v2_sparse_classes_30k_train_001513 | Implement the Python class `RegisterForm` described below.
Class description:
注册表单
Method signatures and docstrings:
- def clean_username(self): 验证用户名 :return:
- def clean_email(self): 验证邮箱 :return:
- def clean_password_again(self): 验证两次输入的密码是否一致 :return: | Implement the Python class `RegisterForm` described below.
Class description:
注册表单
Method signatures and docstrings:
- def clean_username(self): 验证用户名 :return:
- def clean_email(self): 验证邮箱 :return:
- def clean_password_again(self): 验证两次输入的密码是否一致 :return:
<|skeleton|>
class RegisterForm:
"""注册表单"""
def clea... | 01b949144ae55eab57d6da7054f061e31ba8457b | <|skeleton|>
class RegisterForm:
"""注册表单"""
def clean_username(self):
"""验证用户名 :return:"""
<|body_0|>
def clean_email(self):
"""验证邮箱 :return:"""
<|body_1|>
def clean_password_again(self):
"""验证两次输入的密码是否一致 :return:"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RegisterForm:
"""注册表单"""
def clean_username(self):
"""验证用户名 :return:"""
username = self.cleaned_data['username']
if User.objects.filter(username=username).exists():
raise forms.ValidationError('用户名已存在')
return username
def clean_email(self):
"""验证邮... | the_stack_v2_python_sparse | accounts/forms.py | oldestcrab/my_blog | train | 0 |
0ccd90e3cc0e4ba33dc54abaec43caa0ab161433 | [
"def f(txn: LoggingTransaction) -> None:\n txn.execute('SELECT 1 FROM erased_users WHERE user_id = ?', (user_id,))\n if txn.fetchone():\n return\n txn.execute('INSERT INTO erased_users (user_id) VALUES (?)', (user_id,))\n self._invalidate_cache_and_stream(txn, self.is_user_erased, (user_id,))\naw... | <|body_start_0|>
def f(txn: LoggingTransaction) -> None:
txn.execute('SELECT 1 FROM erased_users WHERE user_id = ?', (user_id,))
if txn.fetchone():
return
txn.execute('INSERT INTO erased_users (user_id) VALUES (?)', (user_id,))
self._invalidate_cac... | UserErasureStore | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserErasureStore:
async def mark_user_erased(self, user_id: str) -> None:
"""Indicate that user_id wishes their message history to be erased. Args: user_id: full user_id to be erased"""
<|body_0|>
async def mark_user_not_erased(self, user_id: str) -> None:
"""Indicat... | stack_v2_sparse_classes_10k_train_005016 | 3,689 | permissive | [
{
"docstring": "Indicate that user_id wishes their message history to be erased. Args: user_id: full user_id to be erased",
"name": "mark_user_erased",
"signature": "async def mark_user_erased(self, user_id: str) -> None"
},
{
"docstring": "Indicate that user_id is no longer erased. Args: user_i... | 2 | null | Implement the Python class `UserErasureStore` described below.
Class description:
Implement the UserErasureStore class.
Method signatures and docstrings:
- async def mark_user_erased(self, user_id: str) -> None: Indicate that user_id wishes their message history to be erased. Args: user_id: full user_id to be erased
... | Implement the Python class `UserErasureStore` described below.
Class description:
Implement the UserErasureStore class.
Method signatures and docstrings:
- async def mark_user_erased(self, user_id: str) -> None: Indicate that user_id wishes their message history to be erased. Args: user_id: full user_id to be erased
... | d35bed8369514fe727b4fe1afb68f48cc8b2655a | <|skeleton|>
class UserErasureStore:
async def mark_user_erased(self, user_id: str) -> None:
"""Indicate that user_id wishes their message history to be erased. Args: user_id: full user_id to be erased"""
<|body_0|>
async def mark_user_not_erased(self, user_id: str) -> None:
"""Indicat... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserErasureStore:
async def mark_user_erased(self, user_id: str) -> None:
"""Indicate that user_id wishes their message history to be erased. Args: user_id: full user_id to be erased"""
def f(txn: LoggingTransaction) -> None:
txn.execute('SELECT 1 FROM erased_users WHERE user_id = ... | the_stack_v2_python_sparse | synapse/storage/databases/main/user_erasure_store.py | matrix-org/synapse | train | 12,215 | |
8ff93e0fd27b5fdddda568536bf194d3b149792a | [
"unique_chars_in_pattern = len(set(pattern))\nunique_words_in_strings = len(set(strings.split(' ')))\nunique_pairs = len(set(zip(pattern, strings.split(' '))))\nreturn unique_chars_in_pattern == unique_words_in_strings == unique_pairs",
"unique_chars_in_p = len(set(p))\nunique_chars_in_q = len(set(q))\nunique_pai... | <|body_start_0|>
unique_chars_in_pattern = len(set(pattern))
unique_words_in_strings = len(set(strings.split(' ')))
unique_pairs = len(set(zip(pattern, strings.split(' '))))
return unique_chars_in_pattern == unique_words_in_strings == unique_pairs
<|end_body_0|>
<|body_start_1|>
... | Isomorphism | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Isomorphism:
def wordPattern(self, pattern, strings):
"""Purpose: Return whether or not there is a bijection between a letter in pattern, and a non-empty word in strings."""
<|body_0|>
def stringPattern(self, p, q):
"""Purpose: Return whether or not the characters in... | stack_v2_sparse_classes_10k_train_005017 | 818 | no_license | [
{
"docstring": "Purpose: Return whether or not there is a bijection between a letter in pattern, and a non-empty word in strings.",
"name": "wordPattern",
"signature": "def wordPattern(self, pattern, strings)"
},
{
"docstring": "Purpose: Return whether or not the characters in p can be replaced ... | 2 | stack_v2_sparse_classes_30k_train_000874 | Implement the Python class `Isomorphism` described below.
Class description:
Implement the Isomorphism class.
Method signatures and docstrings:
- def wordPattern(self, pattern, strings): Purpose: Return whether or not there is a bijection between a letter in pattern, and a non-empty word in strings.
- def stringPatte... | Implement the Python class `Isomorphism` described below.
Class description:
Implement the Isomorphism class.
Method signatures and docstrings:
- def wordPattern(self, pattern, strings): Purpose: Return whether or not there is a bijection between a letter in pattern, and a non-empty word in strings.
- def stringPatte... | 95a86cbbca28d0c0f6d72d28a2f1cb5a86327934 | <|skeleton|>
class Isomorphism:
def wordPattern(self, pattern, strings):
"""Purpose: Return whether or not there is a bijection between a letter in pattern, and a non-empty word in strings."""
<|body_0|>
def stringPattern(self, p, q):
"""Purpose: Return whether or not the characters in... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Isomorphism:
def wordPattern(self, pattern, strings):
"""Purpose: Return whether or not there is a bijection between a letter in pattern, and a non-empty word in strings."""
unique_chars_in_pattern = len(set(pattern))
unique_words_in_strings = len(set(strings.split(' ')))
uniqu... | the_stack_v2_python_sparse | isomorphism_str.py | tashakim/puzzles_python | train | 8 | |
bd4f9df349d897f13541cc77626cea225e17e552 | [
"super().__init__()\nself.ensemble = ensemble\nself.p_vae = p_vae\nself.q_vae = q_vae\nself.latent_size = latent_size",
"xs = []\nys = []\nws = []\nfor j in range(num_batches):\n z = tf.random.normal([num_samples, self.latent_size])\n q_dx = self.q_vae.decoder.get_distribution(z, training=False)\n p_dx =... | <|body_start_0|>
super().__init__()
self.ensemble = ensemble
self.p_vae = p_vae
self.q_vae = q_vae
self.latent_size = latent_size
<|end_body_0|>
<|body_start_1|>
xs = []
ys = []
ws = []
for j in range(num_batches):
z = tf.random.normal... | CBAS | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CBAS:
def __init__(self, ensemble, p_vae, q_vae, latent_size=20):
"""Build a trainer for an ensemble of probabilistic neural networks trained on bootstraps of a dataset Args: encoder: tf.keras.Model the encoder neural network that outputs parameters for a gaussian decoder: tf.keras.Model... | stack_v2_sparse_classes_10k_train_005018 | 19,704 | permissive | [
{
"docstring": "Build a trainer for an ensemble of probabilistic neural networks trained on bootstraps of a dataset Args: encoder: tf.keras.Model the encoder neural network that outputs parameters for a gaussian decoder: tf.keras.Model the decoder neural network that outputs parameters for a gaussian vae_optim:... | 4 | stack_v2_sparse_classes_30k_val_000204 | Implement the Python class `CBAS` described below.
Class description:
Implement the CBAS class.
Method signatures and docstrings:
- def __init__(self, ensemble, p_vae, q_vae, latent_size=20): Build a trainer for an ensemble of probabilistic neural networks trained on bootstraps of a dataset Args: encoder: tf.keras.Mo... | Implement the Python class `CBAS` described below.
Class description:
Implement the CBAS class.
Method signatures and docstrings:
- def __init__(self, ensemble, p_vae, q_vae, latent_size=20): Build a trainer for an ensemble of probabilistic neural networks trained on bootstraps of a dataset Args: encoder: tf.keras.Mo... | d46ff40d8b665953afb64a3332ddf1953b8a0766 | <|skeleton|>
class CBAS:
def __init__(self, ensemble, p_vae, q_vae, latent_size=20):
"""Build a trainer for an ensemble of probabilistic neural networks trained on bootstraps of a dataset Args: encoder: tf.keras.Model the encoder neural network that outputs parameters for a gaussian decoder: tf.keras.Model... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CBAS:
def __init__(self, ensemble, p_vae, q_vae, latent_size=20):
"""Build a trainer for an ensemble of probabilistic neural networks trained on bootstraps of a dataset Args: encoder: tf.keras.Model the encoder neural network that outputs parameters for a gaussian decoder: tf.keras.Model the decoder n... | the_stack_v2_python_sparse | design_baselines/autofocused_cbas/trainers.py | stjordanis/design-baselines | train | 0 | |
038049f3079be001499757f663419da2dfd6faeb | [
"def postorder(node):\n return postorder(node.left) + postorder(node.right) + [node.val] if node else []\nserialize_data = ' '.join(map(str, postorder(root)))\nreturn serialize_data",
"def helper(lower=float('-inf'), upper=float('inf')):\n if not data or data[-1] < lower or data[-1] > upper:\n return... | <|body_start_0|>
def postorder(node):
return postorder(node.left) + postorder(node.right) + [node.val] if node else []
serialize_data = ' '.join(map(str, postorder(root)))
return serialize_data
<|end_body_0|>
<|body_start_1|>
def helper(lower=float('-inf'), upper=float('inf'... | 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_10k_train_005019 | 1,609 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_001244 | 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:... | f93380721b8383817fe2b0d728deca1321c9ef45 | <|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_10k | 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 postorder(node):
return postorder(node.left) + postorder(node.right) + [node.val] if node else []
serialize_data = ' '.join(map(str, postorder(root)))
ret... | the_stack_v2_python_sparse | explore/2020/october/Serialize_and_Deserialize_BST.py | lixiang2017/leetcode | train | 5 | |
896f12c4ebce5364058372856784e381ffcd1d59 | [
"nums.sort()\nans = [[]]\nlast = [[]]\nfor i, n in enumerate(nums):\n pickFrom = ans\n if i != 0 and nums[i - 1] == n:\n pickFrom = last\n last = [a + [n] for a in pickFrom]\n ans += last\nreturn ans",
"lst = [[]]\nnums = sorted(nums)\n\ndef func(nums):\n if nums is None:\n return\n ... | <|body_start_0|>
nums.sort()
ans = [[]]
last = [[]]
for i, n in enumerate(nums):
pickFrom = ans
if i != 0 and nums[i - 1] == n:
pickFrom = last
last = [a + [n] for a in pickFrom]
ans += last
return ans
<|end_body_0|>... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subsetsWithDup(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def subsetsWithDup2(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
nums.sort()
... | stack_v2_sparse_classes_10k_train_005020 | 1,007 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "subsetsWithDup",
"signature": "def subsetsWithDup(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "subsetsWithDup2",
"signature": "def subsetsWithDup2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002242 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subsetsWithDup(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def subsetsWithDup2(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 subsetsWithDup(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def subsetsWithDup2(self, nums): :type nums: List[int] :rtype: List[List[int]]
<|skeleton|>
class... | 93cbb01487a61e37159e8bdd4bf40f623e131c19 | <|skeleton|>
class Solution:
def subsetsWithDup(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def subsetsWithDup2(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def subsetsWithDup(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
nums.sort()
ans = [[]]
last = [[]]
for i, n in enumerate(nums):
pickFrom = ans
if i != 0 and nums[i - 1] == n:
pickFrom = last
... | the_stack_v2_python_sparse | Leetcode_medium/backtracking/90.py | HenryBalthier/Python-Learning | train | 0 | |
c896618aad651d6ffb8ebff247c3d45e5b85bffe | [
"result_flag = self.check_element_displayed(self.home_footer_div)\nif result_flag == True:\n self.switch_page('dunzo main page')\nreturn result_flag",
"result_flag = self.check_element_displayed(self.redirect_footer_div)\nif result_flag == True:\n self.switch_page('dunzo main page')\nreturn result_flag"
] | <|body_start_0|>
result_flag = self.check_element_displayed(self.home_footer_div)
if result_flag == True:
self.switch_page('dunzo main page')
return result_flag
<|end_body_0|>
<|body_start_1|>
result_flag = self.check_element_displayed(self.redirect_footer_div)
if re... | Page Object for the header class | Dunzo_Footer_Object | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dunzo_Footer_Object:
"""Page Object for the header class"""
def check_home_page_footer_div(self):
"""Check whether proceed button is present"""
<|body_0|>
def check_redirect_page_footer_div(self):
"""Check whether proceed button is present"""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_005021 | 1,048 | permissive | [
{
"docstring": "Check whether proceed button is present",
"name": "check_home_page_footer_div",
"signature": "def check_home_page_footer_div(self)"
},
{
"docstring": "Check whether proceed button is present",
"name": "check_redirect_page_footer_div",
"signature": "def check_redirect_page... | 2 | stack_v2_sparse_classes_30k_train_005320 | Implement the Python class `Dunzo_Footer_Object` described below.
Class description:
Page Object for the header class
Method signatures and docstrings:
- def check_home_page_footer_div(self): Check whether proceed button is present
- def check_redirect_page_footer_div(self): Check whether proceed button is present | Implement the Python class `Dunzo_Footer_Object` described below.
Class description:
Page Object for the header class
Method signatures and docstrings:
- def check_home_page_footer_div(self): Check whether proceed button is present
- def check_redirect_page_footer_div(self): Check whether proceed button is present
<... | b905baaad68982230f8f5f6bfbd41043e6cade26 | <|skeleton|>
class Dunzo_Footer_Object:
"""Page Object for the header class"""
def check_home_page_footer_div(self):
"""Check whether proceed button is present"""
<|body_0|>
def check_redirect_page_footer_div(self):
"""Check whether proceed button is present"""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Dunzo_Footer_Object:
"""Page Object for the header class"""
def check_home_page_footer_div(self):
"""Check whether proceed button is present"""
result_flag = self.check_element_displayed(self.home_footer_div)
if result_flag == True:
self.switch_page('dunzo main page')
... | the_stack_v2_python_sparse | page_objects/dunzo_footer_object.py | Rajkumar-94/DunzoTest | train | 0 |
f1982f3a13007e1638159e23d6733e4f317d433b | [
"import bisect\nqueue = []\nres = []\nfor num in nums[::-1]:\n loc = bisect.bisect_left(queue, num)\n res.append(loc)\n queue.insert(loc, num)\nreturn res[::-1]",
"arr = []\nres = [0] * len(nums)\nfor idx, num in enumerate(nums):\n arr.append((idx, num))\n\ndef merge_sort(arr):\n if len(arr) <= 1:\... | <|body_start_0|>
import bisect
queue = []
res = []
for num in nums[::-1]:
loc = bisect.bisect_left(queue, num)
res.append(loc)
queue.insert(loc, num)
return res[::-1]
<|end_body_0|>
<|body_start_1|>
arr = []
res = [0] * len(num... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countSmaller_2div(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def countSmaller_merge_sort(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
def countSmaller_Fenwick_Tree(self, nums):
"""... | stack_v2_sparse_classes_10k_train_005022 | 5,177 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "countSmaller_2div",
"signature": "def countSmaller_2div(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "countSmaller_merge_sort",
"signature": "def countSmaller_merge_sort(self, nums)"
... | 5 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countSmaller_2div(self, nums): :type nums: List[int] :rtype: List[int]
- def countSmaller_merge_sort(self, nums): :type nums: List[int] :rtype: List[int]
- def countSmaller_F... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countSmaller_2div(self, nums): :type nums: List[int] :rtype: List[int]
- def countSmaller_merge_sort(self, nums): :type nums: List[int] :rtype: List[int]
- def countSmaller_F... | 3f4284330f9771037ca59e2e6a94122e51e58540 | <|skeleton|>
class Solution:
def countSmaller_2div(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def countSmaller_merge_sort(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
def countSmaller_Fenwick_Tree(self, nums):
"""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def countSmaller_2div(self, nums):
""":type nums: List[int] :rtype: List[int]"""
import bisect
queue = []
res = []
for num in nums[::-1]:
loc = bisect.bisect_left(queue, num)
res.append(loc)
queue.insert(loc, num)
re... | the_stack_v2_python_sparse | Leetcode/315.计算右侧小于当前元素的个数.py | myf-algorithm/Leetcode | train | 1 | |
bf4ca549cec0eefcc8df7d96e98d7a0933000892 | [
"super(DomainAliasAPITestCase, cls).setUpTestData()\nfactories.populate_database()\ncls.dom_alias1 = factories.DomainAliasFactory(name='dalias1.com', target__name='test.com')\ncls.dom_alias2 = factories.DomainAliasFactory(name='dalias2.com', target__name='test2.com')\ncls.da_token = Token.objects.create(user=core_m... | <|body_start_0|>
super(DomainAliasAPITestCase, cls).setUpTestData()
factories.populate_database()
cls.dom_alias1 = factories.DomainAliasFactory(name='dalias1.com', target__name='test.com')
cls.dom_alias2 = factories.DomainAliasFactory(name='dalias2.com', target__name='test2.com')
... | Check DomainAlias API. | DomainAliasAPITestCase | [
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DomainAliasAPITestCase:
"""Check DomainAlias API."""
def setUpTestData(cls):
"""Create test data."""
<|body_0|>
def test_get(self):
"""Retrieve a list of domain aliases."""
<|body_1|>
def test_post(self):
"""Try to create a new domain alias."... | stack_v2_sparse_classes_10k_train_005023 | 33,144 | permissive | [
{
"docstring": "Create test data.",
"name": "setUpTestData",
"signature": "def setUpTestData(cls)"
},
{
"docstring": "Retrieve a list of domain aliases.",
"name": "test_get",
"signature": "def test_get(self)"
},
{
"docstring": "Try to create a new domain alias.",
"name": "tes... | 5 | stack_v2_sparse_classes_30k_train_003368 | Implement the Python class `DomainAliasAPITestCase` described below.
Class description:
Check DomainAlias API.
Method signatures and docstrings:
- def setUpTestData(cls): Create test data.
- def test_get(self): Retrieve a list of domain aliases.
- def test_post(self): Try to create a new domain alias.
- def test_put(... | Implement the Python class `DomainAliasAPITestCase` described below.
Class description:
Check DomainAlias API.
Method signatures and docstrings:
- def setUpTestData(cls): Create test data.
- def test_get(self): Retrieve a list of domain aliases.
- def test_post(self): Try to create a new domain alias.
- def test_put(... | df699aab0799ec1725b6b89be38e56285821c889 | <|skeleton|>
class DomainAliasAPITestCase:
"""Check DomainAlias API."""
def setUpTestData(cls):
"""Create test data."""
<|body_0|>
def test_get(self):
"""Retrieve a list of domain aliases."""
<|body_1|>
def test_post(self):
"""Try to create a new domain alias."... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DomainAliasAPITestCase:
"""Check DomainAlias API."""
def setUpTestData(cls):
"""Create test data."""
super(DomainAliasAPITestCase, cls).setUpTestData()
factories.populate_database()
cls.dom_alias1 = factories.DomainAliasFactory(name='dalias1.com', target__name='test.com')
... | the_stack_v2_python_sparse | modoboa/admin/api/v1/tests.py | modoboa/modoboa | train | 2,201 |
a9085eaf7a446c54f2a7226b5c8e7ae9a6661930 | [
"super(RelPositionalEncoding, self).__init__()\nself.d_model = d_model\nself.xscale = math.sqrt(self.d_model)\nself.dropout = torch.nn.Dropout(p=dropout_rate)\nself.pe = None\nself.extend_pe(torch.tensor(0.0).expand(1, max_len))",
"if self.pe is not None:\n if self.pe.size(1) >= x.size(1) * 2 - 1:\n if ... | <|body_start_0|>
super(RelPositionalEncoding, self).__init__()
self.d_model = d_model
self.xscale = math.sqrt(self.d_model)
self.dropout = torch.nn.Dropout(p=dropout_rate)
self.pe = None
self.extend_pe(torch.tensor(0.0).expand(1, max_len))
<|end_body_0|>
<|body_start_1|>... | Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. | RelPositionalEncoding | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelPositionalEncoding:
"""Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int):... | stack_v2_sparse_classes_10k_train_005024 | 12,758 | permissive | [
{
"docstring": "Construct an PositionalEncoding object.",
"name": "__init__",
"signature": "def __init__(self, d_model, dropout_rate, max_len=5000)"
},
{
"docstring": "Reset the positional encodings.",
"name": "extend_pe",
"signature": "def extend_pe(self, x)"
},
{
"docstring": "... | 3 | stack_v2_sparse_classes_30k_train_006123 | Implement the Python class `RelPositionalEncoding` described below.
Class description:
Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rat... | Implement the Python class `RelPositionalEncoding` described below.
Class description:
Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rat... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class RelPositionalEncoding:
"""Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int):... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RelPositionalEncoding:
"""Relative positional encoding module (new implementation). Details can be found in https://github.com/espnet/espnet/pull/2816. See : Appendix B in https://arxiv.org/abs/1901.02860 Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum inpu... | the_stack_v2_python_sparse | espnet/nets/pytorch_backend/transformer/embedding.py | espnet/espnet | train | 7,242 |
4ae1bfd0f4ffa051b92d3188993bb0d667edc03a | [
"info = {}\ntry:\n if obj.teacher:\n info['teacher'] = obj.teacher.pen_name\nexcept Sensei.DoesNotExist as e:\n info['teacher'] = str(e)\ntry:\n info_problems = OrderedDict({})\n for index, value in enumerate(obj.problems.all()):\n info_problems[value.pk] = value.get_data()\n info['prob... | <|body_start_0|>
info = {}
try:
if obj.teacher:
info['teacher'] = obj.teacher.pen_name
except Sensei.DoesNotExist as e:
info['teacher'] = str(e)
try:
info_problems = OrderedDict({})
for index, value in enumerate(obj.problems... | Serialize the Exam Problem with link and info. | ExamProblemsSerializers | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExamProblemsSerializers:
"""Serialize the Exam Problem with link and info."""
def get_info_data(self, obj, *args, **kwargs):
"""Get information data. :param obj: :param args: :param kwargs: :return:"""
<|body_0|>
def get_links_url(self, obj, *args, **kwargs):
"""... | stack_v2_sparse_classes_10k_train_005025 | 7,433 | no_license | [
{
"docstring": "Get information data. :param obj: :param args: :param kwargs: :return:",
"name": "get_info_data",
"signature": "def get_info_data(self, obj, *args, **kwargs)"
},
{
"docstring": "Get link url :param obj: :param args: :param kwargs: :return:",
"name": "get_links_url",
"sign... | 2 | stack_v2_sparse_classes_30k_test_000075 | Implement the Python class `ExamProblemsSerializers` described below.
Class description:
Serialize the Exam Problem with link and info.
Method signatures and docstrings:
- def get_info_data(self, obj, *args, **kwargs): Get information data. :param obj: :param args: :param kwargs: :return:
- def get_links_url(self, ob... | Implement the Python class `ExamProblemsSerializers` described below.
Class description:
Serialize the Exam Problem with link and info.
Method signatures and docstrings:
- def get_info_data(self, obj, *args, **kwargs): Get information data. :param obj: :param args: :param kwargs: :return:
- def get_links_url(self, ob... | acd31a2f43d7ea83fc9bb34627f5dca94763eade | <|skeleton|>
class ExamProblemsSerializers:
"""Serialize the Exam Problem with link and info."""
def get_info_data(self, obj, *args, **kwargs):
"""Get information data. :param obj: :param args: :param kwargs: :return:"""
<|body_0|>
def get_links_url(self, obj, *args, **kwargs):
"""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ExamProblemsSerializers:
"""Serialize the Exam Problem with link and info."""
def get_info_data(self, obj, *args, **kwargs):
"""Get information data. :param obj: :param args: :param kwargs: :return:"""
info = {}
try:
if obj.teacher:
info['teacher'] = ob... | the_stack_v2_python_sparse | classroom/serializers.py | JoenyBui/mywaterbuffalo | train | 0 |
aca1ca176e186147cd154092535529a837d984a3 | [
"super().__init__()\nself.in_channels = in_channels\nself.out_channels = out_channels\nself.stride = stride",
"for p in self.parameters():\n p.requires_grad = False\nFrozenBatchNorm2d.convert_frozen_batchnorm(self)\nreturn self"
] | <|body_start_0|>
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.stride = stride
<|end_body_0|>
<|body_start_1|>
for p in self.parameters():
p.requires_grad = False
FrozenBatchNorm2d.convert_frozen_batchnorm(self)
... | A CNN block is assumed to have input channels, output channels and a stride. The input and output of `forward()` method must be NCHW tensors. The method can perform arbitrary computation but must match the given channels and stride specification. Attribute: in_channels (int): out_channels (int): stride (int): | CNNBlockBase | [
"GPL-1.0-or-later",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CNNBlockBase:
"""A CNN block is assumed to have input channels, output channels and a stride. The input and output of `forward()` method must be NCHW tensors. The method can perform arbitrary computation but must match the given channels and stride specification. Attribute: in_channels (int): out... | stack_v2_sparse_classes_10k_train_005026 | 4,708 | permissive | [
{
"docstring": "The `__init__` method of any subclass should also contain these arguments. Args: in_channels (int): out_channels (int): stride (int):",
"name": "__init__",
"signature": "def __init__(self, in_channels, out_channels, stride)"
},
{
"docstring": "Make this block not trainable. This ... | 2 | stack_v2_sparse_classes_30k_train_006926 | Implement the Python class `CNNBlockBase` described below.
Class description:
A CNN block is assumed to have input channels, output channels and a stride. The input and output of `forward()` method must be NCHW tensors. The method can perform arbitrary computation but must match the given channels and stride specifica... | Implement the Python class `CNNBlockBase` described below.
Class description:
A CNN block is assumed to have input channels, output channels and a stride. The input and output of `forward()` method must be NCHW tensors. The method can perform arbitrary computation but must match the given channels and stride specifica... | 92acc188d3a0f634de58463b6676e70df83ef808 | <|skeleton|>
class CNNBlockBase:
"""A CNN block is assumed to have input channels, output channels and a stride. The input and output of `forward()` method must be NCHW tensors. The method can perform arbitrary computation but must match the given channels and stride specification. Attribute: in_channels (int): out... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CNNBlockBase:
"""A CNN block is assumed to have input channels, output channels and a stride. The input and output of `forward()` method must be NCHW tensors. The method can perform arbitrary computation but must match the given channels and stride specification. Attribute: in_channels (int): out_channels (in... | the_stack_v2_python_sparse | PyTorch/dev/cv/image_classification/SlowFast_ID0646_for_PyTorch/detectron2/detectron2/layers/blocks.py | Ascend/ModelZoo-PyTorch | train | 23 |
fd2b7a6bc7d5fbf8ef7998d1699889532d000d03 | [
"intervals = sorted(intervals, key=lambda Interval: Interval.start)\nret = []\nfor interval in intervals:\n if not ret or interval.start > ret[-1].end:\n ret.append(interval)\n elif interval.start <= ret[-1].end < interval.end:\n ret[-1].end = interval.end\nreturn ret",
"intervals = sorted(int... | <|body_start_0|>
intervals = sorted(intervals, key=lambda Interval: Interval.start)
ret = []
for interval in intervals:
if not ret or interval.start > ret[-1].end:
ret.append(interval)
elif interval.start <= ret[-1].end < interval.end:
ret[... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def merge(self, intervals):
""":type intervals: List[Interval] :rtype: List[Interval]"""
<|body_0|>
def merge1(self, intervals):
""":type intervals: List[Interval] :rtype: List[Interval]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
inte... | stack_v2_sparse_classes_10k_train_005027 | 1,424 | no_license | [
{
"docstring": ":type intervals: List[Interval] :rtype: List[Interval]",
"name": "merge",
"signature": "def merge(self, intervals)"
},
{
"docstring": ":type intervals: List[Interval] :rtype: List[Interval]",
"name": "merge1",
"signature": "def merge1(self, intervals)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge(self, intervals): :type intervals: List[Interval] :rtype: List[Interval]
- def merge1(self, intervals): :type intervals: List[Interval] :rtype: List[Interval] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge(self, intervals): :type intervals: List[Interval] :rtype: List[Interval]
- def merge1(self, intervals): :type intervals: List[Interval] :rtype: List[Interval]
<|skelet... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def merge(self, intervals):
""":type intervals: List[Interval] :rtype: List[Interval]"""
<|body_0|>
def merge1(self, intervals):
""":type intervals: List[Interval] :rtype: List[Interval]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def merge(self, intervals):
""":type intervals: List[Interval] :rtype: List[Interval]"""
intervals = sorted(intervals, key=lambda Interval: Interval.start)
ret = []
for interval in intervals:
if not ret or interval.start > ret[-1].end:
ret.... | the_stack_v2_python_sparse | python/leetcode_bak/56_Merge_Intervals.py | bobcaoge/my-code | train | 0 | |
4e1e867ce5b564f944423487e76af73c8a4a6a73 | [
"self.q = collections.deque([])\nfor i in range(0, len(A), 2):\n if A[i] > 0:\n self.q.append((A[i], A[i + 1]))",
"while n > 0 and self.q:\n count, number = self.q.popleft()\n if count >= n:\n count -= n\n if count > 0:\n self.q.appendleft((count, number))\n return ... | <|body_start_0|>
self.q = collections.deque([])
for i in range(0, len(A), 2):
if A[i] > 0:
self.q.append((A[i], A[i + 1]))
<|end_body_0|>
<|body_start_1|>
while n > 0 and self.q:
count, number = self.q.popleft()
if count >= n:
... | RLEIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RLEIterator:
def __init__(self, A):
""":type A: List[int]"""
<|body_0|>
def next(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.q = collections.deque([])
for i in range(0, len(A), 2):
i... | stack_v2_sparse_classes_10k_train_005028 | 768 | no_license | [
{
"docstring": ":type A: List[int]",
"name": "__init__",
"signature": "def __init__(self, A)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "next",
"signature": "def next(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002601 | Implement the Python class `RLEIterator` described below.
Class description:
Implement the RLEIterator class.
Method signatures and docstrings:
- def __init__(self, A): :type A: List[int]
- def next(self, n): :type n: int :rtype: int | Implement the Python class `RLEIterator` described below.
Class description:
Implement the RLEIterator class.
Method signatures and docstrings:
- def __init__(self, A): :type A: List[int]
- def next(self, n): :type n: int :rtype: int
<|skeleton|>
class RLEIterator:
def __init__(self, A):
""":type A: Lis... | 20fe3c9adb0a6937ea6482b26f26fddfa04a64b8 | <|skeleton|>
class RLEIterator:
def __init__(self, A):
""":type A: List[int]"""
<|body_0|>
def next(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RLEIterator:
def __init__(self, A):
""":type A: List[int]"""
self.q = collections.deque([])
for i in range(0, len(A), 2):
if A[i] > 0:
self.q.append((A[i], A[i + 1]))
def next(self, n):
""":type n: int :rtype: int"""
while n > 0 and self... | the_stack_v2_python_sparse | 900. RLE Iterator.py | YuzhouPeng/LeetCode-Python | train | 0 | |
95f8d5cdb04db131eec782075bf3a3abf601f4e7 | [
"self.gamma = gamma\nself.eps = eps\ncache = dict()\nfor k, v in model.params.items():\n cache[k] = np.zeros_like(v)\nself.cache = cache",
"gamma = self.gamma\neps = self.eps\ncache = self.cache\nparams, grads = (model.params, model.grads)\nfor k in grads:\n cache[k] = gamma * cache[k] + (1 - gamma) * np.po... | <|body_start_0|>
self.gamma = gamma
self.eps = eps
cache = dict()
for k, v in model.params.items():
cache[k] = np.zeros_like(v)
self.cache = cache
<|end_body_0|>
<|body_start_1|>
gamma = self.gamma
eps = self.eps
cache = self.cache
par... | RMSpropOptim | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RMSpropOptim:
def __init__(self, model, gamma=0.9, eps=1e-12):
"""Inputs: :param model: a neural network class object :param gamma: (float) suggest to be 0.9 :param eps: (float) a small number"""
<|body_0|>
def step(self, model, learning_rate):
"""Implement a one-ste... | stack_v2_sparse_classes_10k_train_005029 | 9,004 | no_license | [
{
"docstring": "Inputs: :param model: a neural network class object :param gamma: (float) suggest to be 0.9 :param eps: (float) a small number",
"name": "__init__",
"signature": "def __init__(self, model, gamma=0.9, eps=1e-12)"
},
{
"docstring": "Implement a one-step RMSprop update on network's ... | 2 | stack_v2_sparse_classes_30k_train_001508 | Implement the Python class `RMSpropOptim` described below.
Class description:
Implement the RMSpropOptim class.
Method signatures and docstrings:
- def __init__(self, model, gamma=0.9, eps=1e-12): Inputs: :param model: a neural network class object :param gamma: (float) suggest to be 0.9 :param eps: (float) a small n... | Implement the Python class `RMSpropOptim` described below.
Class description:
Implement the RMSpropOptim class.
Method signatures and docstrings:
- def __init__(self, model, gamma=0.9, eps=1e-12): Inputs: :param model: a neural network class object :param gamma: (float) suggest to be 0.9 :param eps: (float) a small n... | a401d09c28432109e9ced10e5011bff97dda05b9 | <|skeleton|>
class RMSpropOptim:
def __init__(self, model, gamma=0.9, eps=1e-12):
"""Inputs: :param model: a neural network class object :param gamma: (float) suggest to be 0.9 :param eps: (float) a small number"""
<|body_0|>
def step(self, model, learning_rate):
"""Implement a one-ste... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RMSpropOptim:
def __init__(self, model, gamma=0.9, eps=1e-12):
"""Inputs: :param model: a neural network class object :param gamma: (float) suggest to be 0.9 :param eps: (float) a small number"""
self.gamma = gamma
self.eps = eps
cache = dict()
for k, v in model.params.... | the_stack_v2_python_sparse | assignment2/E4040.2017.Assign2.xw2501/E4040.2017.Assign2.xw2501/ecbm4040/optimizers.py | xw2501/Deep_Learning_study | train | 7 | |
bb3bc703cc345d0bb209484d039ea6468f5e953c | [
"stack = [root]\nwhile stack and root:\n cur = stack.pop()\n if cur.right:\n stack.append(cur.right)\n if cur.left:\n stack.append(cur.left)\n if cur != root:\n root.left, root.right = (None, TreeNode(cur.val))\n root = root.right",
"stack = [root]\nres = []\nwhile stack an... | <|body_start_0|>
stack = [root]
while stack and root:
cur = stack.pop()
if cur.right:
stack.append(cur.right)
if cur.left:
stack.append(cur.left)
if cur != root:
root.left, root.right = (None, TreeNode(cur.va... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def flatten(self, root: TreeNode) -> None:
"""前序遍历 :param root: :return:"""
<|body_0|>
def flatten2(self, root: TreeNode) -> None:
"""Do not return anything, modify root in-place instead."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sta... | stack_v2_sparse_classes_10k_train_005030 | 1,465 | no_license | [
{
"docstring": "前序遍历 :param root: :return:",
"name": "flatten",
"signature": "def flatten(self, root: TreeNode) -> None"
},
{
"docstring": "Do not return anything, modify root in-place instead.",
"name": "flatten2",
"signature": "def flatten2(self, root: TreeNode) -> None"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, root: TreeNode) -> None: 前序遍历 :param root: :return:
- def flatten2(self, root: TreeNode) -> None: Do not return anything, modify root in-place instead. | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, root: TreeNode) -> None: 前序遍历 :param root: :return:
- def flatten2(self, root: TreeNode) -> None: Do not return anything, modify root in-place instead.
<|skele... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def flatten(self, root: TreeNode) -> None:
"""前序遍历 :param root: :return:"""
<|body_0|>
def flatten2(self, root: TreeNode) -> None:
"""Do not return anything, modify root in-place instead."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def flatten(self, root: TreeNode) -> None:
"""前序遍历 :param root: :return:"""
stack = [root]
while stack and root:
cur = stack.pop()
if cur.right:
stack.append(cur.right)
if cur.left:
stack.append(cur.left)
... | the_stack_v2_python_sparse | 114_二叉树展开为链表.py | lovehhf/LeetCode | train | 0 | |
d54babd0d28b817fdbb273332e3e271dbf524ba0 | [
"for i in range(len(dataset)):\n self.print_example(np.matrix(dataset[i][0]))\n print()",
"for i in range(example.shape[0]):\n for j in range(example.shape[1]):\n cell = example.item(i, j)\n if cell > 0:\n print('# ', end='')\n else:\n print('. ', end='')\n p... | <|body_start_0|>
for i in range(len(dataset)):
self.print_example(np.matrix(dataset[i][0]))
print()
<|end_body_0|>
<|body_start_1|>
for i in range(example.shape[0]):
for j in range(example.shape[1]):
cell = example.item(i, j)
if cell >... | AdalineTools | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdalineTools:
def print_all(self, dataset):
"""Prints all examples"""
<|body_0|>
def print_example(self, example):
"""Prints an example"""
<|body_1|>
def build_input_dataset(self, inputs):
"""Converts the dataset into a bidimensional dataset wher... | stack_v2_sparse_classes_10k_train_005031 | 5,959 | no_license | [
{
"docstring": "Prints all examples",
"name": "print_all",
"signature": "def print_all(self, dataset)"
},
{
"docstring": "Prints an example",
"name": "print_example",
"signature": "def print_example(self, example)"
},
{
"docstring": "Converts the dataset into a bidimensional data... | 5 | stack_v2_sparse_classes_30k_train_004366 | Implement the Python class `AdalineTools` described below.
Class description:
Implement the AdalineTools class.
Method signatures and docstrings:
- def print_all(self, dataset): Prints all examples
- def print_example(self, example): Prints an example
- def build_input_dataset(self, inputs): Converts the dataset into... | Implement the Python class `AdalineTools` described below.
Class description:
Implement the AdalineTools class.
Method signatures and docstrings:
- def print_all(self, dataset): Prints all examples
- def print_example(self, example): Prints an example
- def build_input_dataset(self, inputs): Converts the dataset into... | 2a4adef88508c6d9b134920f758044dece09a58e | <|skeleton|>
class AdalineTools:
def print_all(self, dataset):
"""Prints all examples"""
<|body_0|>
def print_example(self, example):
"""Prints an example"""
<|body_1|>
def build_input_dataset(self, inputs):
"""Converts the dataset into a bidimensional dataset wher... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AdalineTools:
def print_all(self, dataset):
"""Prints all examples"""
for i in range(len(dataset)):
self.print_example(np.matrix(dataset[i][0]))
print()
def print_example(self, example):
"""Prints an example"""
for i in range(example.shape[0]):
... | the_stack_v2_python_sparse | SCC5809/ex1/src/adaline.py | damaresende/USP | train | 0 | |
ee3e1509b5b8c7c763a7f9bb29bf7a3e317fec5c | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AggregationOption()",
"from .bucket_aggregation_definition import BucketAggregationDefinition\nfrom .bucket_aggregation_definition import BucketAggregationDefinition\nfields: Dict[str, Callable[[Any], None]] = {'bucketDefinition': lamb... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AggregationOption()
<|end_body_0|>
<|body_start_1|>
from .bucket_aggregation_definition import BucketAggregationDefinition
from .bucket_aggregation_definition import BucketAggregationDef... | AggregationOption | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AggregationOption:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AggregationOption:
"""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... | stack_v2_sparse_classes_10k_train_005032 | 3,368 | 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: AggregationOption",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_v... | 3 | stack_v2_sparse_classes_30k_train_004565 | Implement the Python class `AggregationOption` described below.
Class description:
Implement the AggregationOption class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AggregationOption: Creates a new instance of the appropriate class based on discrim... | Implement the Python class `AggregationOption` described below.
Class description:
Implement the AggregationOption class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AggregationOption: Creates a new instance of the appropriate class based on discrim... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AggregationOption:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AggregationOption:
"""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... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AggregationOption:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AggregationOption:
"""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: Aggr... | the_stack_v2_python_sparse | msgraph/generated/models/aggregation_option.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
4f41c148c00d205e3c2f265881c54f13210a84f8 | [
"if sentencizer in ['en_core_sci_lg', 'en_core_sci_md', 'en_core_sci_sm', 'en_core_web_sm']:\n return SpacySentencizer(spacy_model=sentencizer)\nelif sentencizer == 'note':\n return NoteSentencizer()\nelse:\n raise ValueError('Invalid sentencizer - does not exist')",
"if tokenizer in ['en_core_sci_lg', '... | <|body_start_0|>
if sentencizer in ['en_core_sci_lg', 'en_core_sci_md', 'en_core_sci_sm', 'en_core_web_sm']:
return SpacySentencizer(spacy_model=sentencizer)
elif sentencizer == 'note':
return NoteSentencizer()
else:
raise ValueError('Invalid sentencizer - doe... | PreprocessingLoader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreprocessingLoader:
def get_sentencizer(sentencizer: str) -> Union[SpacySentencizer, NoteSentencizer]:
"""Get the desired the sentencizer We can either use the sci-spacy (en_core_sci_lg or en_core_web_sm) or consider the entire note as a single sentence. Args: sentencizer (str): Specify... | stack_v2_sparse_classes_10k_train_005033 | 2,229 | permissive | [
{
"docstring": "Get the desired the sentencizer We can either use the sci-spacy (en_core_sci_lg or en_core_web_sm) or consider the entire note as a single sentence. Args: sentencizer (str): Specify which sentencizer you want to use Returns: Union[SpacySentencizer, NoteSentencizer]: An object of the requested se... | 2 | stack_v2_sparse_classes_30k_test_000114 | Implement the Python class `PreprocessingLoader` described below.
Class description:
Implement the PreprocessingLoader class.
Method signatures and docstrings:
- def get_sentencizer(sentencizer: str) -> Union[SpacySentencizer, NoteSentencizer]: Get the desired the sentencizer We can either use the sci-spacy (en_core_... | Implement the Python class `PreprocessingLoader` described below.
Class description:
Implement the PreprocessingLoader class.
Method signatures and docstrings:
- def get_sentencizer(sentencizer: str) -> Union[SpacySentencizer, NoteSentencizer]: Get the desired the sentencizer We can either use the sci-spacy (en_core_... | 88751ab1f95d23d54ded39385adb8a27f57a6f72 | <|skeleton|>
class PreprocessingLoader:
def get_sentencizer(sentencizer: str) -> Union[SpacySentencizer, NoteSentencizer]:
"""Get the desired the sentencizer We can either use the sci-spacy (en_core_sci_lg or en_core_web_sm) or consider the entire note as a single sentence. Args: sentencizer (str): Specify... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PreprocessingLoader:
def get_sentencizer(sentencizer: str) -> Union[SpacySentencizer, NoteSentencizer]:
"""Get the desired the sentencizer We can either use the sci-spacy (en_core_sci_lg or en_core_web_sm) or consider the entire note as a single sentence. Args: sentencizer (str): Specify which sentenc... | the_stack_v2_python_sparse | src/robust_deid/ner_datasets/preprocessing/preprocessing_loader.py | obi-ml-public/ehr_deidentification | train | 28 | |
9c82e85aef149e48556d92afbf473b7c33b72592 | [
"errors: dict[str, str] = {}\nhost: str = data[CONF_HOST]\nport: int = data[CONF_PORT]\nusername: str = data[CONF_USERNAME]\npassword: str = data[CONF_PASSWORD]\nverify_ssl: bool = data[CONF_VERIFY_SSL]\nuptime_robot_api = UptimeKuma(async_get_clientsession(self.hass), f'{host}:{port}', username, password, verify_s... | <|body_start_0|>
errors: dict[str, str] = {}
host: str = data[CONF_HOST]
port: int = data[CONF_PORT]
username: str = data[CONF_USERNAME]
password: str = data[CONF_PASSWORD]
verify_ssl: bool = data[CONF_VERIFY_SSL]
uptime_robot_api = UptimeKuma(async_get_clientsess... | Handle a config flow for Uptime Kuma. | ConfigFlow | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigFlow:
"""Handle a config flow for Uptime Kuma."""
async def _validate_input(self, data: dict[str, Any]) -> tuple[dict[str, str], None]:
"""Validate the user input allows us to connect."""
<|body_0|>
async def async_step_user(self, user_input: dict[str, Any] | None=... | stack_v2_sparse_classes_10k_train_005034 | 2,760 | permissive | [
{
"docstring": "Validate the user input allows us to connect.",
"name": "_validate_input",
"signature": "async def _validate_input(self, data: dict[str, Any]) -> tuple[dict[str, str], None]"
},
{
"docstring": "Handle the initial step.",
"name": "async_step_user",
"signature": "async def ... | 2 | null | Implement the Python class `ConfigFlow` described below.
Class description:
Handle a config flow for Uptime Kuma.
Method signatures and docstrings:
- async def _validate_input(self, data: dict[str, Any]) -> tuple[dict[str, str], None]: Validate the user input allows us to connect.
- async def async_step_user(self, us... | Implement the Python class `ConfigFlow` described below.
Class description:
Handle a config flow for Uptime Kuma.
Method signatures and docstrings:
- async def _validate_input(self, data: dict[str, Any]) -> tuple[dict[str, str], None]: Validate the user input allows us to connect.
- async def async_step_user(self, us... | 8548d9999ddd54f13d6a307e013abcb8c897a74e | <|skeleton|>
class ConfigFlow:
"""Handle a config flow for Uptime Kuma."""
async def _validate_input(self, data: dict[str, Any]) -> tuple[dict[str, str], None]:
"""Validate the user input allows us to connect."""
<|body_0|>
async def async_step_user(self, user_input: dict[str, Any] | None=... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ConfigFlow:
"""Handle a config flow for Uptime Kuma."""
async def _validate_input(self, data: dict[str, Any]) -> tuple[dict[str, str], None]:
"""Validate the user input allows us to connect."""
errors: dict[str, str] = {}
host: str = data[CONF_HOST]
port: int = data[CONF_P... | the_stack_v2_python_sparse | custom_components/uptime_kuma/config_flow.py | bacco007/HomeAssistantConfig | train | 98 |
fbe84113b39a396850e5e214dbf81fbf1f002c25 | [
"l = 0\nfor s in S:\n if s.isdigit():\n l *= int(s)\n else:\n l += 1\nfor s in reversed(S):\n K %= l\n if K == 0 and s.isalpha():\n return s\n if s.isdigit():\n l //= int(s)\n else:\n l -= 1\nraise",
"K -= 1\ni = 0\nj = 0\nlast = None\nn = len(S)\nwhile j < n:\... | <|body_start_0|>
l = 0
for s in S:
if s.isdigit():
l *= int(s)
else:
l += 1
for s in reversed(S):
K %= l
if K == 0 and s.isalpha():
return s
if s.isdigit():
l //= int(s)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def decodeAtIndex(self, S: str, K: int) -> str:
"""walk backward"""
<|body_0|>
def decodeAtIndex_error(self, S: str, K: int) -> str:
"""don't generate the final string, too memory expensive two pointer understanding error, one digit will make the entire str... | stack_v2_sparse_classes_10k_train_005035 | 2,561 | no_license | [
{
"docstring": "walk backward",
"name": "decodeAtIndex",
"signature": "def decodeAtIndex(self, S: str, K: int) -> str"
},
{
"docstring": "don't generate the final string, too memory expensive two pointer understanding error, one digit will make the entire str repeated",
"name": "decodeAtInde... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def decodeAtIndex(self, S: str, K: int) -> str: walk backward
- def decodeAtIndex_error(self, S: str, K: int) -> str: don't generate the final string, too memory expensive two po... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def decodeAtIndex(self, S: str, K: int) -> str: walk backward
- def decodeAtIndex_error(self, S: str, K: int) -> str: don't generate the final string, too memory expensive two po... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def decodeAtIndex(self, S: str, K: int) -> str:
"""walk backward"""
<|body_0|>
def decodeAtIndex_error(self, S: str, K: int) -> str:
"""don't generate the final string, too memory expensive two pointer understanding error, one digit will make the entire str... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def decodeAtIndex(self, S: str, K: int) -> str:
"""walk backward"""
l = 0
for s in S:
if s.isdigit():
l *= int(s)
else:
l += 1
for s in reversed(S):
K %= l
if K == 0 and s.isalpha():
... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetCode/880 Decoded String at Index.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
56e4ef4c248796422637fe18700f4d37960c9834 | [
"self.output_name = output_name\nself.metric_name = metric_name\nself.split_name = split_name\nself.dataset_name = dataset_name\nself.minimum_metric = minimum_metric\nself.best_metric = 10000000000.0",
"if metric_value is not None and metric_value < self.minimum_metric and (metric_value < self.best_metric):\n ... | <|body_start_0|>
self.output_name = output_name
self.metric_name = metric_name
self.split_name = split_name
self.dataset_name = dataset_name
self.minimum_metric = minimum_metric
self.best_metric = 10000000000.0
<|end_body_0|>
<|body_start_1|>
if metric_value is n... | ModelWithLowestMetric | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelWithLowestMetric:
def __init__(self, dataset_name, split_name, output_name, metric_name, minimum_metric=0.2):
"""Args: dataset_name: the dataset name to be considered for the best model split_name: the split name to be considered for the best model metric_name: the metric name to be... | stack_v2_sparse_classes_10k_train_005036 | 9,199 | permissive | [
{
"docstring": "Args: dataset_name: the dataset name to be considered for the best model split_name: the split name to be considered for the best model metric_name: the metric name to be considered for the best model minimum_metric: consider only the metric lower than this threshold output_name: the output to b... | 2 | null | Implement the Python class `ModelWithLowestMetric` described below.
Class description:
Implement the ModelWithLowestMetric class.
Method signatures and docstrings:
- def __init__(self, dataset_name, split_name, output_name, metric_name, minimum_metric=0.2): Args: dataset_name: the dataset name to be considered for th... | Implement the Python class `ModelWithLowestMetric` described below.
Class description:
Implement the ModelWithLowestMetric class.
Method signatures and docstrings:
- def __init__(self, dataset_name, split_name, output_name, metric_name, minimum_metric=0.2): Args: dataset_name: the dataset name to be considered for th... | 11c59dea0072d940b036166be22b392bb9e3b066 | <|skeleton|>
class ModelWithLowestMetric:
def __init__(self, dataset_name, split_name, output_name, metric_name, minimum_metric=0.2):
"""Args: dataset_name: the dataset name to be considered for the best model split_name: the split name to be considered for the best model metric_name: the metric name to be... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ModelWithLowestMetric:
def __init__(self, dataset_name, split_name, output_name, metric_name, minimum_metric=0.2):
"""Args: dataset_name: the dataset name to be considered for the best model split_name: the split name to be considered for the best model metric_name: the metric name to be considered fo... | the_stack_v2_python_sparse | src/trw/callbacks/callback_save_last_model.py | civodlu/trw | train | 12 | |
27bdc6035c31eb562e1a96c5877f647de99af71a | [
"if root == None:\n return False\nreturn bool(self.helper(root, sum, 0))",
"pathSum += root.val\nif root.left:\n left = self.helper(root.left, target, pathSum)\n if left:\n return True\nif root.right:\n right = self.helper(root.right, target, pathSum)\n if right:\n return True\nif not... | <|body_start_0|>
if root == None:
return False
return bool(self.helper(root, sum, 0))
<|end_body_0|>
<|body_start_1|>
pathSum += root.val
if root.left:
left = self.helper(root.left, target, pathSum)
if left:
return True
if root... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hasPathSum(self, root, sum):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def helper(self, root, target, pathSum):
""":type root: TreeNode :type depth: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root == Non... | stack_v2_sparse_classes_10k_train_005037 | 1,704 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "hasPathSum",
"signature": "def hasPathSum(self, root, sum)"
},
{
"docstring": ":type root: TreeNode :type depth: int :rtype: int",
"name": "helper",
"signature": "def helper(self, root, target, pathSum)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001189 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasPathSum(self, root, sum): :type root: TreeNode :rtype: int
- def helper(self, root, target, pathSum): :type root: TreeNode :type depth: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasPathSum(self, root, sum): :type root: TreeNode :rtype: int
- def helper(self, root, target, pathSum): :type root: TreeNode :type depth: int :rtype: int
<|skeleton|>
class... | 61933e7c0b8d8ffef9bd9a4af4fddfdb77568b62 | <|skeleton|>
class Solution:
def hasPathSum(self, root, sum):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def helper(self, root, target, pathSum):
""":type root: TreeNode :type depth: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def hasPathSum(self, root, sum):
""":type root: TreeNode :rtype: int"""
if root == None:
return False
return bool(self.helper(root, sum, 0))
def helper(self, root, target, pathSum):
""":type root: TreeNode :type depth: int :rtype: int"""
pathS... | the_stack_v2_python_sparse | 112-Path-Sum.py | OhMesch/Algorithm-Problems | train | 0 | |
e6380e103209b26201de874a7b615e7fa1d6ebfd | [
"if not root1 and (not root2):\n return True\nif root1 and root2 and (root1.val == root2.val):\n return self.is_mirror(root1.left, root2.right) and self.is_mirror(root1.right, root2.left)\nreturn False",
"if not root:\n return 1\nif self.is_mirror(root.left, root.right):\n return 1\nreturn 0"
] | <|body_start_0|>
if not root1 and (not root2):
return True
if root1 and root2 and (root1.val == root2.val):
return self.is_mirror(root1.left, root2.right) and self.is_mirror(root1.right, root2.left)
return False
<|end_body_0|>
<|body_start_1|>
if not root:
... | SolutionInterviewBit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SolutionInterviewBit:
def is_mirror(self, root1, root2):
"""Returns True if two trees are mirror of one another, False otherwise."""
<|body_0|>
def isSymmetric(self, root):
"""Returns True if binary tree is symmetric, False otherwise. Time complexity: O(n). Space com... | stack_v2_sparse_classes_10k_train_005038 | 3,032 | no_license | [
{
"docstring": "Returns True if two trees are mirror of one another, False otherwise.",
"name": "is_mirror",
"signature": "def is_mirror(self, root1, root2)"
},
{
"docstring": "Returns True if binary tree is symmetric, False otherwise. Time complexity: O(n). Space complexity: O(n), n is number o... | 2 | stack_v2_sparse_classes_30k_train_005181 | Implement the Python class `SolutionInterviewBit` described below.
Class description:
Implement the SolutionInterviewBit class.
Method signatures and docstrings:
- def is_mirror(self, root1, root2): Returns True if two trees are mirror of one another, False otherwise.
- def isSymmetric(self, root): Returns True if bi... | Implement the Python class `SolutionInterviewBit` described below.
Class description:
Implement the SolutionInterviewBit class.
Method signatures and docstrings:
- def is_mirror(self, root1, root2): Returns True if two trees are mirror of one another, False otherwise.
- def isSymmetric(self, root): Returns True if bi... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class SolutionInterviewBit:
def is_mirror(self, root1, root2):
"""Returns True if two trees are mirror of one another, False otherwise."""
<|body_0|>
def isSymmetric(self, root):
"""Returns True if binary tree is symmetric, False otherwise. Time complexity: O(n). Space com... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SolutionInterviewBit:
def is_mirror(self, root1, root2):
"""Returns True if two trees are mirror of one another, False otherwise."""
if not root1 and (not root2):
return True
if root1 and root2 and (root1.val == root2.val):
return self.is_mirror(root1.left, root... | the_stack_v2_python_sparse | Trees/symmetric_binary_tree.py | vladn90/Algorithms | train | 0 | |
f45439be1eb9a030ef6790a49840485b15078c72 | [
"with open(filename, 'r') as file:\n num_nodes = None\n graph = {}\n for line in file:\n if num_nodes is None:\n num_nodes = int(line)\n graph = {id_: node_cls(id_) for id_ in range(1, num_nodes + 1)}\n else:\n m, n, dist = line.split(' ')\n m = int... | <|body_start_0|>
with open(filename, 'r') as file:
num_nodes = None
graph = {}
for line in file:
if num_nodes is None:
num_nodes = int(line)
graph = {id_: node_cls(id_) for id_ in range(1, num_nodes + 1)}
... | IOManager handles converting between dictionaries of GraphNode objects and .ecegraph files. | IOManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IOManager:
"""IOManager handles converting between dictionaries of GraphNode objects and .ecegraph files."""
def import_graph(cls, filename, node_cls=GraphNode):
"""Returns a dictionary of GraphNode objects. Parameters: filename: Name of .ecegraph file to import (ie. map.ecegraph) Re... | stack_v2_sparse_classes_10k_train_005039 | 2,331 | no_license | [
{
"docstring": "Returns a dictionary of GraphNode objects. Parameters: filename: Name of .ecegraph file to import (ie. map.ecegraph) Returns: Dictionary where keys are ids and values are GraphNode objects. Example: graph = IOManager.import_graph('g.ecegraph')",
"name": "import_graph",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_001107 | Implement the Python class `IOManager` described below.
Class description:
IOManager handles converting between dictionaries of GraphNode objects and .ecegraph files.
Method signatures and docstrings:
- def import_graph(cls, filename, node_cls=GraphNode): Returns a dictionary of GraphNode objects. Parameters: filenam... | Implement the Python class `IOManager` described below.
Class description:
IOManager handles converting between dictionaries of GraphNode objects and .ecegraph files.
Method signatures and docstrings:
- def import_graph(cls, filename, node_cls=GraphNode): Returns a dictionary of GraphNode objects. Parameters: filenam... | faf065e0aae8e242d05f6940ba98be102f6ff6e5 | <|skeleton|>
class IOManager:
"""IOManager handles converting between dictionaries of GraphNode objects and .ecegraph files."""
def import_graph(cls, filename, node_cls=GraphNode):
"""Returns a dictionary of GraphNode objects. Parameters: filename: Name of .ecegraph file to import (ie. map.ecegraph) Re... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class IOManager:
"""IOManager handles converting between dictionaries of GraphNode objects and .ecegraph files."""
def import_graph(cls, filename, node_cls=GraphNode):
"""Returns a dictionary of GraphNode objects. Parameters: filename: Name of .ecegraph file to import (ie. map.ecegraph) Returns: Dictio... | the_stack_v2_python_sparse | graph/iomanager.py | andrew-zhou/ece457a | train | 0 |
06a70b6dbc6b7f96f5f0e54756bb20f98e64dc00 | [
"if not root:\n return\nqueue = collections.deque()\nqueue.append(root)\nwhile queue:\n current = queue.popleft()\n left = current.left\n right = current.right\n current.left = right\n current.right = left\n if left:\n queue.append(left)\n if right:\n queue.append(right)\nretur... | <|body_start_0|>
if not root:
return
queue = collections.deque()
queue.append(root)
while queue:
current = queue.popleft()
left = current.left
right = current.right
current.left = right
current.right = left
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def invertTree(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_0|>
def invertTree_recursive(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
retu... | stack_v2_sparse_classes_10k_train_005040 | 1,080 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: TreeNode",
"name": "invertTree",
"signature": "def invertTree(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: TreeNode",
"name": "invertTree_recursive",
"signature": "def invertTree_recursive(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def invertTree(self, root): :type root: TreeNode :rtype: TreeNode
- def invertTree_recursive(self, root): :type root: TreeNode :rtype: TreeNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def invertTree(self, root): :type root: TreeNode :rtype: TreeNode
- def invertTree_recursive(self, root): :type root: TreeNode :rtype: TreeNode
<|skeleton|>
class Solution:
... | 1a3c1f4d6e9d3444039f087763b93241f4ba7892 | <|skeleton|>
class Solution:
def invertTree(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_0|>
def invertTree_recursive(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def invertTree(self, root):
""":type root: TreeNode :rtype: TreeNode"""
if not root:
return
queue = collections.deque()
queue.append(root)
while queue:
current = queue.popleft()
left = current.left
right = curren... | the_stack_v2_python_sparse | Algorithm/226_Invert_Binary_Tree.py | Gi1ia/TechNoteBook | train | 7 | |
a6dbc6762f06d3737c5208a951a025ebde172a3f | [
"super(ReducedConv, self).__init__()\nself.flat_conv1 = nn.Conv1d(1, 1, 31, stride=2, padding=15)\nself.linear = nn.Sequential(nn.Linear(embeddings_dim // 2, hidden_dim), nn.Dropout(dropout), nn.ReLU(), nn.BatchNorm1d(hidden_dim))\nself.output = nn.Linear(32, output_dim)",
"o = x[:, None, :]\no = F.relu(self.flat... | <|body_start_0|>
super(ReducedConv, self).__init__()
self.flat_conv1 = nn.Conv1d(1, 1, 31, stride=2, padding=15)
self.linear = nn.Sequential(nn.Linear(embeddings_dim // 2, hidden_dim), nn.Dropout(dropout), nn.ReLU(), nn.BatchNorm1d(hidden_dim))
self.output = nn.Linear(32, output_dim)
<|e... | ReducedConv | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReducedConv:
def __init__(self, embeddings_dim: int=1024, hidden_dim: int=32, output_dim: int=12, dropout: float=0.25):
"""Simple Feed forward model with default parameters like the network tha is ued in the SeqVec paper. Args: embeddings_dim: dimension of the input hidden_dim: dimension... | stack_v2_sparse_classes_10k_train_005041 | 1,460 | no_license | [
{
"docstring": "Simple Feed forward model with default parameters like the network tha is ued in the SeqVec paper. Args: embeddings_dim: dimension of the input hidden_dim: dimension of the hidden layers output_dim: output dimension (number of classes that should be classified) number_hidden_layers: number of hi... | 2 | stack_v2_sparse_classes_30k_test_000249 | Implement the Python class `ReducedConv` described below.
Class description:
Implement the ReducedConv class.
Method signatures and docstrings:
- def __init__(self, embeddings_dim: int=1024, hidden_dim: int=32, output_dim: int=12, dropout: float=0.25): Simple Feed forward model with default parameters like the networ... | Implement the Python class `ReducedConv` described below.
Class description:
Implement the ReducedConv class.
Method signatures and docstrings:
- def __init__(self, embeddings_dim: int=1024, hidden_dim: int=32, output_dim: int=12, dropout: float=0.25): Simple Feed forward model with default parameters like the networ... | cf294348cbb838cbbd33f27c3c58d29a88eb137e | <|skeleton|>
class ReducedConv:
def __init__(self, embeddings_dim: int=1024, hidden_dim: int=32, output_dim: int=12, dropout: float=0.25):
"""Simple Feed forward model with default parameters like the network tha is ued in the SeqVec paper. Args: embeddings_dim: dimension of the input hidden_dim: dimension... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ReducedConv:
def __init__(self, embeddings_dim: int=1024, hidden_dim: int=32, output_dim: int=12, dropout: float=0.25):
"""Simple Feed forward model with default parameters like the network tha is ued in the SeqVec paper. Args: embeddings_dim: dimension of the input hidden_dim: dimension of the hidden... | the_stack_v2_python_sparse | models/legacy/reduced_conv.py | bioinformatica/protein-localization | train | 0 | |
69ef8b95244ba262646f9a23e85ee544d12ee7ab | [
"self.grammar = cnf_grammar\nself.matrix = []\nself.i = self.k = self.j = 0",
"self.matrix = [None] * length\nfor x in range(0, length):\n self.matrix[x] = [None] * length\nself.i = self.k = self.j = 0",
"self.j += 1\nself.i = self.j - 1\nself.matrix[self.i][self.j] = {}\npossible_tags = self.grammar.product... | <|body_start_0|>
self.grammar = cnf_grammar
self.matrix = []
self.i = self.k = self.j = 0
<|end_body_0|>
<|body_start_1|>
self.matrix = [None] * length
for x in range(0, length):
self.matrix[x] = [None] * length
self.i = self.k = self.j = 0
<|end_body_1|>
<|... | This class parses a given sentence according the the given CNF grammar using a probabilistic CKY algorithm | PCKY | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PCKY:
"""This class parses a given sentence according the the given CNF grammar using a probabilistic CKY algorithm"""
def __init__(self, cnf_grammar):
"""Initialize the class by loading the grammar :param cnf_grammar: the given CNF grammar"""
<|body_0|>
def setup(self, ... | stack_v2_sparse_classes_10k_train_005042 | 5,674 | no_license | [
{
"docstring": "Initialize the class by loading the grammar :param cnf_grammar: the given CNF grammar",
"name": "__init__",
"signature": "def __init__(self, cnf_grammar)"
},
{
"docstring": "Set up the matrix and indices for a new parse :param length: the length of the sentence to parse :return: ... | 5 | stack_v2_sparse_classes_30k_val_000123 | Implement the Python class `PCKY` described below.
Class description:
This class parses a given sentence according the the given CNF grammar using a probabilistic CKY algorithm
Method signatures and docstrings:
- def __init__(self, cnf_grammar): Initialize the class by loading the grammar :param cnf_grammar: the give... | Implement the Python class `PCKY` described below.
Class description:
This class parses a given sentence according the the given CNF grammar using a probabilistic CKY algorithm
Method signatures and docstrings:
- def __init__(self, cnf_grammar): Initialize the class by loading the grammar :param cnf_grammar: the give... | 7af7b357347ed526de7a3d6f16652843d214dcbf | <|skeleton|>
class PCKY:
"""This class parses a given sentence according the the given CNF grammar using a probabilistic CKY algorithm"""
def __init__(self, cnf_grammar):
"""Initialize the class by loading the grammar :param cnf_grammar: the given CNF grammar"""
<|body_0|>
def setup(self, ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PCKY:
"""This class parses a given sentence according the the given CNF grammar using a probabilistic CKY algorithm"""
def __init__(self, cnf_grammar):
"""Initialize the class by loading the grammar :param cnf_grammar: the given CNF grammar"""
self.grammar = cnf_grammar
self.matri... | the_stack_v2_python_sparse | Parser/pcky.py | zoew2/Projects | train | 0 |
c27babc0057be0c31ec606289f469f2d26918727 | [
"with new_session() as session:\n for filter_ in filters:\n f = models.Filter_log_group(filter_id=filter_.id, filter_version=filter_.version, log_group_id=log_group_id)\n session.merge(f)\n try:\n session.commit()\n return True\n except IntegrityError as e:\n logging.exce... | <|body_start_0|>
with new_session() as session:
for filter_ in filters:
f = models.Filter_log_group(filter_id=filter_.id, filter_version=filter_.version, log_group_id=log_group_id)
session.merge(f)
try:
session.commit()
retu... | Log_group_filters | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Log_group_filters:
def add(cls, filters, log_group_id):
"""Creates a relation between a log_group and on or more filters. :param filter_: list of Filter :param log_group_id: int :returns: boolean"""
<|body_0|>
def get(cls, log_group_id):
"""Returns a list of filters ... | stack_v2_sparse_classes_10k_train_005043 | 10,222 | no_license | [
{
"docstring": "Creates a relation between a log_group and on or more filters. :param filter_: list of Filter :param log_group_id: int :returns: boolean",
"name": "add",
"signature": "def add(cls, filters, log_group_id)"
},
{
"docstring": "Returns a list of filters by `log_group_id`. :param log_... | 2 | stack_v2_sparse_classes_30k_val_000377 | Implement the Python class `Log_group_filters` described below.
Class description:
Implement the Log_group_filters class.
Method signatures and docstrings:
- def add(cls, filters, log_group_id): Creates a relation between a log_group and on or more filters. :param filter_: list of Filter :param log_group_id: int :ret... | Implement the Python class `Log_group_filters` described below.
Class description:
Implement the Log_group_filters class.
Method signatures and docstrings:
- def add(cls, filters, log_group_id): Creates a relation between a log_group and on or more filters. :param filter_: list of Filter :param log_group_id: int :ret... | 3f331c7169c90d1fac0d1922b011b56eebbd086a | <|skeleton|>
class Log_group_filters:
def add(cls, filters, log_group_id):
"""Creates a relation between a log_group and on or more filters. :param filter_: list of Filter :param log_group_id: int :returns: boolean"""
<|body_0|>
def get(cls, log_group_id):
"""Returns a list of filters ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Log_group_filters:
def add(cls, filters, log_group_id):
"""Creates a relation between a log_group and on or more filters. :param filter_: list of Filter :param log_group_id: int :returns: boolean"""
with new_session() as session:
for filter_ in filters:
f = models.F... | the_stack_v2_python_sparse | src/tlog/base/log_group.py | thomaserlang/TLog | train | 2 | |
7473c6611aa0f26ba76cffba3b0188d40e896a29 | [
"self.chrom = chrom\nself.taxon = taxon\nself.parser = Parser(species_string=species)\nself.out_dir = out_dir\nself.char_limit = char_limit\nself.maf_file = maf_file\nself.char_count = 0\nself.file_num = 1\nself.current_file = open(self.current_filename, 'w')\nself.maf_lines = gzopen(maf_file, 'r') if self.maf_file... | <|body_start_0|>
self.chrom = chrom
self.taxon = taxon
self.parser = Parser(species_string=species)
self.out_dir = out_dir
self.char_limit = char_limit
self.maf_file = maf_file
self.char_count = 0
self.file_num = 1
self.current_file = open(self.cur... | An class for splitting large MAF files into smaller subunits and removing unused lines. The split_file function is an iterator which writes files up to the specified sequence legnth and then yields the name of the just completed MAF file. | Splitter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Splitter:
"""An class for splitting large MAF files into smaller subunits and removing unused lines. The split_file function is an iterator which writes files up to the specified sequence legnth and then yields the name of the just completed MAF file."""
def __init__(self, chrom, taxon, spec... | stack_v2_sparse_classes_10k_train_005044 | 11,087 | no_license | [
{
"docstring": "Load input and ouput paths :param chrom: chromosome for the current data :param taxon: taxon name given to splitter output :param species: comma-separated string of species IDs used by Parser to select MAF lines :param out_dir: destination for MAF files :param char_limit: file size limit in char... | 5 | stack_v2_sparse_classes_30k_train_004434 | Implement the Python class `Splitter` described below.
Class description:
An class for splitting large MAF files into smaller subunits and removing unused lines. The split_file function is an iterator which writes files up to the specified sequence legnth and then yields the name of the just completed MAF file.
Metho... | Implement the Python class `Splitter` described below.
Class description:
An class for splitting large MAF files into smaller subunits and removing unused lines. The split_file function is an iterator which writes files up to the specified sequence legnth and then yields the name of the just completed MAF file.
Metho... | c09a98ac4c82e7d1c9c5d1cc7c283b13dca76db4 | <|skeleton|>
class Splitter:
"""An class for splitting large MAF files into smaller subunits and removing unused lines. The split_file function is an iterator which writes files up to the specified sequence legnth and then yields the name of the just completed MAF file."""
def __init__(self, chrom, taxon, spec... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Splitter:
"""An class for splitting large MAF files into smaller subunits and removing unused lines. The split_file function is an iterator which writes files up to the specified sequence legnth and then yields the name of the just completed MAF file."""
def __init__(self, chrom, taxon, species, out_dir,... | the_stack_v2_python_sparse | phast/maf_tools.py | sellalab/HumanLinkedSelectionMaps | train | 1 |
57580475ce1d52dc771dc3c9a1dfbf5e8ce72100 | [
"self.max_h = list()\nself.min_h = list()\nheapify(self.max_h)\nheapify(self.min_h)",
"heappush(self.min_h, num)\nheappush(self.max_h, -heappop(self.min_h))\nif len(self.max_h) > len(self.min_h):\n heappush(self.min_h, -heappop(self.max_h))",
"max_len = len(self.max_h)\nmin_len = len(self.min_h)\nif max_len ... | <|body_start_0|>
self.max_h = list()
self.min_h = list()
heapify(self.max_h)
heapify(self.min_h)
<|end_body_0|>
<|body_start_1|>
heappush(self.min_h, num)
heappush(self.max_h, -heappop(self.min_h))
if len(self.max_h) > len(self.min_h):
heappush(self.m... | MedianFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: None"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_10k_train_005045 | 2,010 | no_license | [
{
"docstring": "initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":type num: int :rtype: None",
"name": "addNum",
"signature": "def addNum(self, num)"
},
{
"docstring": ":rtype: float",
"name": "findMedian",
"s... | 3 | stack_v2_sparse_classes_30k_train_005837 | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def addNum(self, num): :type num: int :rtype: None
- def findMedian(self): :rtype: float | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def addNum(self, num): :type num: int :rtype: None
- def findMedian(self): :rtype: float
<|skeleton|>
class Me... | ce8b12735aa181a223eb3b8d6c6993cbafc2e467 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def addNum(self, num):
""":type num: int :rtype: None"""
<|body_1|>
def findMedian(self):
""":rtype: float"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MedianFinder:
def __init__(self):
"""initialize your data structure here."""
self.max_h = list()
self.min_h = list()
heapify(self.max_h)
heapify(self.min_h)
def addNum(self, num):
""":type num: int :rtype: None"""
heappush(self.min_h, num)
h... | the_stack_v2_python_sparse | 295. 数据流的中位数.py | hanzhenlei767/leetcode | train | 3 | |
2d9a5c3abedaa7198d3a77028afff933471f9fe9 | [
"for item in kdddx:\n if l0(item):\n return item",
"count = 0\nfor item in kdddx:\n if l3(item):\n count += 1\nreturn count",
"for i in kdddx1:\n if l(i):\n yield i",
"mins = l1(kdddx2[0])\nfor c in range(1, len(kdddx2)):\n if l1(kdddx2[c]) < mins:\n mins = l1(kdddx2[c]... | <|body_start_0|>
for item in kdddx:
if l0(item):
return item
<|end_body_0|>
<|body_start_1|>
count = 0
for item in kdddx:
if l3(item):
count += 1
return count
<|end_body_1|>
<|body_start_2|>
for i in kdddx1:
if... | Iterablehelper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Iterablehelper:
def find_singel01(kdddx, l0):
""":param kdddx: 输入可迭代对象 :param l0: 目标函数 :return: 返回单一值"""
<|body_0|>
def find_count(kdddx, l3):
""":param kdddx: 输入可迭代对象 :param l3: 目标函数 :return: 返回目标数量"""
<|body_1|>
def find_all(kdddx1, l):
""":par... | stack_v2_sparse_classes_10k_train_005046 | 1,646 | permissive | [
{
"docstring": ":param kdddx: 输入可迭代对象 :param l0: 目标函数 :return: 返回单一值",
"name": "find_singel01",
"signature": "def find_singel01(kdddx, l0)"
},
{
"docstring": ":param kdddx: 输入可迭代对象 :param l3: 目标函数 :return: 返回目标数量",
"name": "find_count",
"signature": "def find_count(kdddx, l3)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_001135 | Implement the Python class `Iterablehelper` described below.
Class description:
Implement the Iterablehelper class.
Method signatures and docstrings:
- def find_singel01(kdddx, l0): :param kdddx: 输入可迭代对象 :param l0: 目标函数 :return: 返回单一值
- def find_count(kdddx, l3): :param kdddx: 输入可迭代对象 :param l3: 目标函数 :return: 返回目标数量
... | Implement the Python class `Iterablehelper` described below.
Class description:
Implement the Iterablehelper class.
Method signatures and docstrings:
- def find_singel01(kdddx, l0): :param kdddx: 输入可迭代对象 :param l0: 目标函数 :return: 返回单一值
- def find_count(kdddx, l3): :param kdddx: 输入可迭代对象 :param l3: 目标函数 :return: 返回目标数量
... | d8ba30ea4bc2b662a2d6a87d247f813e5680d63e | <|skeleton|>
class Iterablehelper:
def find_singel01(kdddx, l0):
""":param kdddx: 输入可迭代对象 :param l0: 目标函数 :return: 返回单一值"""
<|body_0|>
def find_count(kdddx, l3):
""":param kdddx: 输入可迭代对象 :param l3: 目标函数 :return: 返回目标数量"""
<|body_1|>
def find_all(kdddx1, l):
""":par... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Iterablehelper:
def find_singel01(kdddx, l0):
""":param kdddx: 输入可迭代对象 :param l0: 目标函数 :return: 返回单一值"""
for item in kdddx:
if l0(item):
return item
def find_count(kdddx, l3):
""":param kdddx: 输入可迭代对象 :param l3: 目标函数 :return: 返回目标数量"""
count = 0... | the_stack_v2_python_sparse | 1-mouth01/gongju/gongjuren.py | gary-gggggg/gary | train | 4 | |
a6a51bbc03f0eac56ac1767f12f96ed18ad8ff50 | [
"super(DownloadWorkerThread, self).__init__(worker_queue, result_queue)\nself._job = job\nself._num_retries = num_retries\nself._time_between_retries = time_between_retries\nself._retry_exceptions = retry_exceptions",
"result = None\nfor _ in range(self._num_retries):\n try:\n result = self._download_ch... | <|body_start_0|>
super(DownloadWorkerThread, self).__init__(worker_queue, result_queue)
self._job = job
self._num_retries = num_retries
self._time_between_retries = time_between_retries
self._retry_exceptions = retry_exceptions
<|end_body_0|>
<|body_start_1|>
result = No... | DownloadWorkerThread | [
"CC-BY-3.0",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-unknown-license-reference",
"ZPL-2.0",
"Unlicense",
"LGPL-3.0-only",
"CC0-1.0",
"LicenseRef-scancode-other-permissive",
"CNRI-Python",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-2.0-or-later",
"Python-2.0",
"GPL-3.0... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DownloadWorkerThread:
def __init__(self, job, worker_queue, result_queue, num_retries=5, time_between_retries=5, retry_exceptions=Exception):
"""Individual download thread that will download parts of the file from Glacier. Parts to download stored in work queue. Parts download to a temp ... | stack_v2_sparse_classes_10k_train_005047 | 17,241 | permissive | [
{
"docstring": "Individual download thread that will download parts of the file from Glacier. Parts to download stored in work queue. Parts download to a temp dir with each part a separate file :param job: Glacier job object :param work_queue: A queue of tuples which include the part_number and part_size :param... | 3 | null | Implement the Python class `DownloadWorkerThread` described below.
Class description:
Implement the DownloadWorkerThread class.
Method signatures and docstrings:
- def __init__(self, job, worker_queue, result_queue, num_retries=5, time_between_retries=5, retry_exceptions=Exception): Individual download thread that wi... | Implement the Python class `DownloadWorkerThread` described below.
Class description:
Implement the DownloadWorkerThread class.
Method signatures and docstrings:
- def __init__(self, job, worker_queue, result_queue, num_retries=5, time_between_retries=5, retry_exceptions=Exception): Individual download thread that wi... | dccb9467675c67b9c3399fc76c5de6d31bfb8255 | <|skeleton|>
class DownloadWorkerThread:
def __init__(self, job, worker_queue, result_queue, num_retries=5, time_between_retries=5, retry_exceptions=Exception):
"""Individual download thread that will download parts of the file from Glacier. Parts to download stored in work queue. Parts download to a temp ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DownloadWorkerThread:
def __init__(self, job, worker_queue, result_queue, num_retries=5, time_between_retries=5, retry_exceptions=Exception):
"""Individual download thread that will download parts of the file from Glacier. Parts to download stored in work queue. Parts download to a temp dir with each ... | the_stack_v2_python_sparse | desktop/core/ext-py3/boto-2.49.0/boto/glacier/concurrent.py | cloudera/hue | train | 5,655 | |
ecc393ae1bed5f81482a5b70b2ab9ba42f2d07f0 | [
"x1 = u[0]\nx2 = u[1]\ndfdu = np.array([[0, 1], [-2 * self.params.mu * x1 * x2 - 1, self.params.mu * (1 - x1 ** 2)]])\nreturn dfdu",
"me = self.dtype_u(2)\nme[:] = spsolve(sp.eye(2) - factor * dfdu, rhs)\nreturn me"
] | <|body_start_0|>
x1 = u[0]
x2 = u[1]
dfdu = np.array([[0, 1], [-2 * self.params.mu * x1 * x2 - 1, self.params.mu * (1 - x1 ** 2)]])
return dfdu
<|end_body_0|>
<|body_start_1|>
me = self.dtype_u(2)
me[:] = spsolve(sp.eye(2) - factor * dfdu, rhs)
return me
<|end_bo... | vanderpol_jac | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class vanderpol_jac:
def eval_jacobian(self, u):
"""Evaluation of the Jacobian of the right-hand side Args: u: space values Returns: Jacobian matrix"""
<|body_0|>
def solve_system_jacobian(self, dfdu, rhs, factor, u0, t):
"""Simple linear solver for (I-dtA)u = rhs Args: df... | stack_v2_sparse_classes_10k_train_005048 | 1,228 | permissive | [
{
"docstring": "Evaluation of the Jacobian of the right-hand side Args: u: space values Returns: Jacobian matrix",
"name": "eval_jacobian",
"signature": "def eval_jacobian(self, u)"
},
{
"docstring": "Simple linear solver for (I-dtA)u = rhs Args: dfdu: the Jacobian of the RHS of the ODE rhs: rig... | 2 | null | Implement the Python class `vanderpol_jac` described below.
Class description:
Implement the vanderpol_jac class.
Method signatures and docstrings:
- def eval_jacobian(self, u): Evaluation of the Jacobian of the right-hand side Args: u: space values Returns: Jacobian matrix
- def solve_system_jacobian(self, dfdu, rhs... | Implement the Python class `vanderpol_jac` described below.
Class description:
Implement the vanderpol_jac class.
Method signatures and docstrings:
- def eval_jacobian(self, u): Evaluation of the Jacobian of the right-hand side Args: u: space values Returns: Jacobian matrix
- def solve_system_jacobian(self, dfdu, rhs... | 1a51834bedffd4472e344bed28f4d766614b1537 | <|skeleton|>
class vanderpol_jac:
def eval_jacobian(self, u):
"""Evaluation of the Jacobian of the right-hand side Args: u: space values Returns: Jacobian matrix"""
<|body_0|>
def solve_system_jacobian(self, dfdu, rhs, factor, u0, t):
"""Simple linear solver for (I-dtA)u = rhs Args: df... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class vanderpol_jac:
def eval_jacobian(self, u):
"""Evaluation of the Jacobian of the right-hand side Args: u: space values Returns: Jacobian matrix"""
x1 = u[0]
x2 = u[1]
dfdu = np.array([[0, 1], [-2 * self.params.mu * x1 * x2 - 1, self.params.mu * (1 - x1 ** 2)]])
return df... | the_stack_v2_python_sparse | pySDC/projects/parallelSDC/Van_der_Pol_implicit_Jac.py | Parallel-in-Time/pySDC | train | 30 | |
702f2e341bed5c738fa7933090cea88f6fef50cc | [
"self.head = head\nself.length = 0\nnode = head\nwhile node:\n node = node.next\n self.length += 1",
"index = random.randrange(0, self.length)\nnode = self.head\nwhile index:\n node = node.next\n index -= 1\nreturn node.val"
] | <|body_start_0|>
self.head = head
self.length = 0
node = head
while node:
node = node.next
self.length += 1
<|end_body_0|>
<|body_start_1|>
index = random.randrange(0, self.length)
node = self.head
while index:
node = node.next... | Solution1 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution1:
def __init__(self, head):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode"""
<|body_0|>
def getRandom(self):
"""Returns a random node's value. :rtype: int"""
... | stack_v2_sparse_classes_10k_train_005049 | 2,037 | permissive | [
{
"docstring": "@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode",
"name": "__init__",
"signature": "def __init__(self, head)"
},
{
"docstring": "Returns a random node's value. :rtype: int",
"name": "g... | 2 | stack_v2_sparse_classes_30k_test_000250 | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def __init__(self, head): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode
- def getR... | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def __init__(self, head): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode
- def getR... | 56b99c829921c534dead1563db726042bbd7155d | <|skeleton|>
class Solution1:
def __init__(self, head):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode"""
<|body_0|>
def getRandom(self):
"""Returns a random node's value. :rtype: int"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution1:
def __init__(self, head):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode"""
self.head = head
self.length = 0
node = head
while node:
node = node.next
... | the_stack_v2_python_sparse | python/problems/linked_list_random_node.py | vivaxy/algorithms | train | 1 | |
c8b2ca6de19c3c372573a4acf4791283971199ca | [
"self._host = host\nself._port = port\nif os.environ.get('TEST_MODE') != 'UNIT_TEST':\n self.connection = pika.BlockingConnection(pika.ConnectionParameters(host=self._host, port=self._port))\nself.sender_lock = threading.Lock()",
"while True:\n try:\n with self.sender_lock:\n with self.con... | <|body_start_0|>
self._host = host
self._port = port
if os.environ.get('TEST_MODE') != 'UNIT_TEST':
self.connection = pika.BlockingConnection(pika.ConnectionParameters(host=self._host, port=self._port))
self.sender_lock = threading.Lock()
<|end_body_0|>
<|body_start_1|>
... | The singleton - is a core API object for API class. | RabbitApi | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RabbitApi:
"""The singleton - is a core API object for API class."""
def __init__(self, host: str, port: int):
"""Constructor for RabbitApi class :param host (str): ip or hostname of Rabbitmq service :param port (int):port of Rabbitmq service"""
<|body_0|>
def emit(self,... | stack_v2_sparse_classes_10k_train_005050 | 2,095 | permissive | [
{
"docstring": "Constructor for RabbitApi class :param host (str): ip or hostname of Rabbitmq service :param port (int):port of Rabbitmq service",
"name": "__init__",
"signature": "def __init__(self, host: str, port: int)"
},
{
"docstring": "Function for sending events used by API.send() :param ... | 2 | stack_v2_sparse_classes_30k_train_006191 | Implement the Python class `RabbitApi` described below.
Class description:
The singleton - is a core API object for API class.
Method signatures and docstrings:
- def __init__(self, host: str, port: int): Constructor for RabbitApi class :param host (str): ip or hostname of Rabbitmq service :param port (int):port of R... | Implement the Python class `RabbitApi` described below.
Class description:
The singleton - is a core API object for API class.
Method signatures and docstrings:
- def __init__(self, host: str, port: int): Constructor for RabbitApi class :param host (str): ip or hostname of Rabbitmq service :param port (int):port of R... | 647ad6d7cc5f91c188aa45e403d9c1a33a7fe947 | <|skeleton|>
class RabbitApi:
"""The singleton - is a core API object for API class."""
def __init__(self, host: str, port: int):
"""Constructor for RabbitApi class :param host (str): ip or hostname of Rabbitmq service :param port (int):port of Rabbitmq service"""
<|body_0|>
def emit(self,... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RabbitApi:
"""The singleton - is a core API object for API class."""
def __init__(self, host: str, port: int):
"""Constructor for RabbitApi class :param host (str): ip or hostname of Rabbitmq service :param port (int):port of Rabbitmq service"""
self._host = host
self._port = port... | the_stack_v2_python_sparse | main_node/tools/rabbit_API_class.py | dpukhkaiev/BRISE2 | train | 6 |
4c49150e44a65c975db5dce11eb31f21578b8dba | [
"length = len(nums)\nmemo = [-1] * length\n\ndef helper(i):\n if i < 0:\n return 0\n if memo[i] != -1:\n return memo[i]\n rob = nums[i] + helper(i - 2)\n dont_rob = helper(i - 1)\n best = max(rob, dont_rob)\n memo[i] = best\n return best\nreturn helper(length - 1)",
"length = le... | <|body_start_0|>
length = len(nums)
memo = [-1] * length
def helper(i):
if i < 0:
return 0
if memo[i] != -1:
return memo[i]
rob = nums[i] + helper(i - 2)
dont_rob = helper(i - 1)
best = max(rob, dont_rob... | Recursive--with memoization (from end to start) Stats: O(n) time, O(n) space Runtime: 20 ms, faster than 67.86% of Python online submissions for House Robber. Memory Usage: 12.9 MB, less than 17.05% of Python online submissions for House Robber. | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Recursive--with memoization (from end to start) Stats: O(n) time, O(n) space Runtime: 20 ms, faster than 67.86% of Python online submissions for House Robber. Memory Usage: 12.9 MB, less than 17.05% of Python online submissions for House Robber."""
def rob(self, nums):
"... | stack_v2_sparse_classes_10k_train_005051 | 3,898 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob",
"signature": "def rob(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob",
"signature": "def rob(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob",... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Recursive--with memoization (from end to start) Stats: O(n) time, O(n) space Runtime: 20 ms, faster than 67.86% of Python online submissions for House Robber. Memory Usage: 12.9 MB, less than 17.05% of Python online submissions for House Robber.... | Implement the Python class `Solution` described below.
Class description:
Recursive--with memoization (from end to start) Stats: O(n) time, O(n) space Runtime: 20 ms, faster than 67.86% of Python online submissions for House Robber. Memory Usage: 12.9 MB, less than 17.05% of Python online submissions for House Robber.... | 844f502da4d6fb9cd69cf0a1ef71da3385a4d2b4 | <|skeleton|>
class Solution:
"""Recursive--with memoization (from end to start) Stats: O(n) time, O(n) space Runtime: 20 ms, faster than 67.86% of Python online submissions for House Robber. Memory Usage: 12.9 MB, less than 17.05% of Python online submissions for House Robber."""
def rob(self, nums):
"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
"""Recursive--with memoization (from end to start) Stats: O(n) time, O(n) space Runtime: 20 ms, faster than 67.86% of Python online submissions for House Robber. Memory Usage: 12.9 MB, less than 17.05% of Python online submissions for House Robber."""
def rob(self, nums):
""":type nums:... | the_stack_v2_python_sparse | 198-house_robber.py | stevestar888/leetcode-problems | train | 2 |
d57b3824bdfca75f2c31c7c6116607f269eb7e22 | [
"if geo_opt:\n self.settings.input.ams.Task = 'GeometryOptimization'\nelse:\n self.settings.input.ams.Task = 'SinglePoint'\nself.settings.input.ams.Properties.NormalModes = 'Yes'\nself.settings.input.DFTB\nself.settings.input.DFTB.Model = 'GFN1-xTB'\nself.settings.input.DFTB.ResourcesDir = 'GFN1-xTB'\nself.se... | <|body_start_0|>
if geo_opt:
self.settings.input.ams.Task = 'GeometryOptimization'
else:
self.settings.input.ams.Task = 'SinglePoint'
self.settings.input.ams.Properties.NormalModes = 'Yes'
self.settings.input.DFTB
self.settings.input.DFTB.Model = 'GFN1-xTB... | Class used for geometry optimization + frequency jobs using DF tight binding methods | DFTBJob | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DFTBJob:
"""Class used for geometry optimization + frequency jobs using DF tight binding methods"""
def _set_std_settings(self, geo_opt=False):
"""Method that specifies standard settings for a DFTB geometry optimization + freqs job"""
<|body_0|>
def run(self, init=True, ... | stack_v2_sparse_classes_10k_train_005052 | 3,480 | no_license | [
{
"docstring": "Method that specifies standard settings for a DFTB geometry optimization + freqs job",
"name": "_set_std_settings",
"signature": "def _set_std_settings(self, geo_opt=False)"
},
{
"docstring": "Method that runs this job",
"name": "run",
"signature": "def run(self, init=Tru... | 2 | stack_v2_sparse_classes_30k_train_005716 | Implement the Python class `DFTBJob` described below.
Class description:
Class used for geometry optimization + frequency jobs using DF tight binding methods
Method signatures and docstrings:
- def _set_std_settings(self, geo_opt=False): Method that specifies standard settings for a DFTB geometry optimization + freqs... | Implement the Python class `DFTBJob` described below.
Class description:
Class used for geometry optimization + frequency jobs using DF tight binding methods
Method signatures and docstrings:
- def _set_std_settings(self, geo_opt=False): Method that specifies standard settings for a DFTB geometry optimization + freqs... | 30b64bd89023b8b7cdd37270bb8970b04c7a7081 | <|skeleton|>
class DFTBJob:
"""Class used for geometry optimization + frequency jobs using DF tight binding methods"""
def _set_std_settings(self, geo_opt=False):
"""Method that specifies standard settings for a DFTB geometry optimization + freqs job"""
<|body_0|>
def run(self, init=True, ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DFTBJob:
"""Class used for geometry optimization + frequency jobs using DF tight binding methods"""
def _set_std_settings(self, geo_opt=False):
"""Method that specifies standard settings for a DFTB geometry optimization + freqs job"""
if geo_opt:
self.settings.input.ams.Task =... | the_stack_v2_python_sparse | comparion data and code/modules/jobs.py | YHordijk/bachelorproject | train | 0 |
c91b5275a9fe06c4aea878982c9309ba23598782 | [
"self.obj = obj\nfor arg in alias_names:\n self.register_key(arg)",
"if isinstance(key, str):\n key = sys.intern(key)\nself[key] = self.obj"
] | <|body_start_0|>
self.obj = obj
for arg in alias_names:
self.register_key(arg)
<|end_body_0|>
<|body_start_1|>
if isinstance(key, str):
key = sys.intern(key)
self[key] = self.obj
<|end_body_1|>
| AliasDict | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AliasDict:
def __init__(self, alias_names: Iterable[Hashable], obj: object) -> None:
"""AliasDict Create a dictionary of pointers to an object Args: alias_names (Iterable[Hashable]): keys to be used, assumed to be immutable i.e. hashable obj (object): object the keys must point to"""
... | stack_v2_sparse_classes_10k_train_005053 | 1,034 | no_license | [
{
"docstring": "AliasDict Create a dictionary of pointers to an object Args: alias_names (Iterable[Hashable]): keys to be used, assumed to be immutable i.e. hashable obj (object): object the keys must point to",
"name": "__init__",
"signature": "def __init__(self, alias_names: Iterable[Hashable], obj: o... | 2 | stack_v2_sparse_classes_30k_train_002559 | Implement the Python class `AliasDict` described below.
Class description:
Implement the AliasDict class.
Method signatures and docstrings:
- def __init__(self, alias_names: Iterable[Hashable], obj: object) -> None: AliasDict Create a dictionary of pointers to an object Args: alias_names (Iterable[Hashable]): keys to... | Implement the Python class `AliasDict` described below.
Class description:
Implement the AliasDict class.
Method signatures and docstrings:
- def __init__(self, alias_names: Iterable[Hashable], obj: object) -> None: AliasDict Create a dictionary of pointers to an object Args: alias_names (Iterable[Hashable]): keys to... | c8690379dd9ca383cf3257a281094e4851677faa | <|skeleton|>
class AliasDict:
def __init__(self, alias_names: Iterable[Hashable], obj: object) -> None:
"""AliasDict Create a dictionary of pointers to an object Args: alias_names (Iterable[Hashable]): keys to be used, assumed to be immutable i.e. hashable obj (object): object the keys must point to"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AliasDict:
def __init__(self, alias_names: Iterable[Hashable], obj: object) -> None:
"""AliasDict Create a dictionary of pointers to an object Args: alias_names (Iterable[Hashable]): keys to be used, assumed to be immutable i.e. hashable obj (object): object the keys must point to"""
self.obj ... | the_stack_v2_python_sparse | pymethods/utils/alias_dict.py | IFF-0303/pymethods | train | 0 | |
400594ef30b70c494f8249cae5ab982b4e25936c | [
"self.length = length\nself.mass = mass\nself.deck_space = deck_space",
"key = 'tower_section_fasten_time'\ntime = kwargs.get(key, pt[key])\nreturn ('Fasten Tower Section', time)",
"key = 'tower_section_release_time'\ntime = kwargs.get(key, pt[key])\nreturn ('Release Tower Section', time)"
] | <|body_start_0|>
self.length = length
self.mass = mass
self.deck_space = deck_space
<|end_body_0|>
<|body_start_1|>
key = 'tower_section_fasten_time'
time = kwargs.get(key, pt[key])
return ('Fasten Tower Section', time)
<|end_body_1|>
<|body_start_2|>
key = 'tow... | Tower Section Cargo | TowerSection | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TowerSection:
"""Tower Section Cargo"""
def __init__(self, length=None, mass=None, deck_space=None, **kwargs):
"""Creates an instance of `TowerSection`."""
<|body_0|>
def fasten(**kwargs):
"""Returns time required to fasten a tower section at port."""
<|b... | stack_v2_sparse_classes_10k_train_005054 | 7,645 | permissive | [
{
"docstring": "Creates an instance of `TowerSection`.",
"name": "__init__",
"signature": "def __init__(self, length=None, mass=None, deck_space=None, **kwargs)"
},
{
"docstring": "Returns time required to fasten a tower section at port.",
"name": "fasten",
"signature": "def fasten(**kwa... | 3 | stack_v2_sparse_classes_30k_train_003493 | Implement the Python class `TowerSection` described below.
Class description:
Tower Section Cargo
Method signatures and docstrings:
- def __init__(self, length=None, mass=None, deck_space=None, **kwargs): Creates an instance of `TowerSection`.
- def fasten(**kwargs): Returns time required to fasten a tower section at... | Implement the Python class `TowerSection` described below.
Class description:
Tower Section Cargo
Method signatures and docstrings:
- def __init__(self, length=None, mass=None, deck_space=None, **kwargs): Creates an instance of `TowerSection`.
- def fasten(**kwargs): Returns time required to fasten a tower section at... | d7270ebe1c554293a9d36730d67ab555c071cb17 | <|skeleton|>
class TowerSection:
"""Tower Section Cargo"""
def __init__(self, length=None, mass=None, deck_space=None, **kwargs):
"""Creates an instance of `TowerSection`."""
<|body_0|>
def fasten(**kwargs):
"""Returns time required to fasten a tower section at port."""
<|b... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TowerSection:
"""Tower Section Cargo"""
def __init__(self, length=None, mass=None, deck_space=None, **kwargs):
"""Creates an instance of `TowerSection`."""
self.length = length
self.mass = mass
self.deck_space = deck_space
def fasten(**kwargs):
"""Returns time... | the_stack_v2_python_sparse | wisdem/orbit/phases/install/turbine_install/common.py | WISDEM/WISDEM | train | 120 |
62da91a16ff40032e992fece978fb0533fee0e2b | [
"trie = lambda: defaultdict(trie)\n\ndef trie():\n return defaultdict(trie)\nself.trie = trie()",
"child = self.trie\nfor c in word:\n child = child[c]\nchild['is_word'] = True",
"child = self.trie\nfor c in word:\n if c in child:\n child = child[c]\n else:\n return False\nreturn child... | <|body_start_0|>
trie = lambda: defaultdict(trie)
def trie():
return defaultdict(trie)
self.trie = trie()
<|end_body_0|>
<|body_start_1|>
child = self.trie
for c in word:
child = child[c]
child['is_word'] = True
<|end_body_1|>
<|body_start_2|>
... | Trie | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trie:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, word: str) -> None:
"""Inserts a word into the trie."""
<|body_1|>
def search(self, word: str) -> bool:
"""Returns if the word is in the trie."""
... | stack_v2_sparse_classes_10k_train_005055 | 3,882 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a word into the trie.",
"name": "insert",
"signature": "def insert(self, word: str) -> None"
},
{
"docstring": "Returns if the word is in the tr... | 4 | null | Implement the Python class `Trie` described below.
Class description:
Implement the Trie class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, word: str) -> None: Inserts a word into the trie.
- def search(self, word: str) -> bool: Returns if the word i... | Implement the Python class `Trie` described below.
Class description:
Implement the Trie class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, word: str) -> None: Inserts a word into the trie.
- def search(self, word: str) -> bool: Returns if the word i... | 5d29bcf7ea1a9e489a92bc36d2158456de25829e | <|skeleton|>
class Trie:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, word: str) -> None:
"""Inserts a word into the trie."""
<|body_1|>
def search(self, word: str) -> bool:
"""Returns if the word is in the trie."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Trie:
def __init__(self):
"""Initialize your data structure here."""
trie = lambda: defaultdict(trie)
def trie():
return defaultdict(trie)
self.trie = trie()
def insert(self, word: str) -> None:
"""Inserts a word into the trie."""
child = self.... | the_stack_v2_python_sparse | 208.实现-trie-前缀树.py | oceanbei333/leetcode | train | 0 | |
179059de3a08256bcbca884f8cb24c47066e7ea0 | [
"from GoogleDrive import drives_list_command\nwith open('test_data/drives_list_response.json', encoding='utf-8') as data:\n mock_response = json.load(data)\nmocker_http_request.return_value = mock_response\nargs = {'use_domain_admin_access': True}\nresult = drives_list_command(gsuite_client, args)\nassert 'Googl... | <|body_start_0|>
from GoogleDrive import drives_list_command
with open('test_data/drives_list_response.json', encoding='utf-8') as data:
mock_response = json.load(data)
mocker_http_request.return_value = mock_response
args = {'use_domain_admin_access': True}
result = ... | TestDriveMethods | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDriveMethods:
def test_drives_list_command_success(self, mocker_http_request, gsuite_client):
"""Scenario: For google-drive-drives-list command successful run. Given: - Command args. When: - Calling google-drive-drives-list command with the parameters provided. Then: - Ensure command... | stack_v2_sparse_classes_10k_train_005056 | 33,071 | permissive | [
{
"docstring": "Scenario: For google-drive-drives-list command successful run. Given: - Command args. When: - Calling google-drive-drives-list command with the parameters provided. Then: - Ensure command's raw_response, outputs should be as expected.",
"name": "test_drives_list_command_success",
"signat... | 4 | null | Implement the Python class `TestDriveMethods` described below.
Class description:
Implement the TestDriveMethods class.
Method signatures and docstrings:
- def test_drives_list_command_success(self, mocker_http_request, gsuite_client): Scenario: For google-drive-drives-list command successful run. Given: - Command ar... | Implement the Python class `TestDriveMethods` described below.
Class description:
Implement the TestDriveMethods class.
Method signatures and docstrings:
- def test_drives_list_command_success(self, mocker_http_request, gsuite_client): Scenario: For google-drive-drives-list command successful run. Given: - Command ar... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestDriveMethods:
def test_drives_list_command_success(self, mocker_http_request, gsuite_client):
"""Scenario: For google-drive-drives-list command successful run. Given: - Command args. When: - Calling google-drive-drives-list command with the parameters provided. Then: - Ensure command... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestDriveMethods:
def test_drives_list_command_success(self, mocker_http_request, gsuite_client):
"""Scenario: For google-drive-drives-list command successful run. Given: - Command args. When: - Calling google-drive-drives-list command with the parameters provided. Then: - Ensure command's raw_respons... | the_stack_v2_python_sparse | Packs/GoogleDrive/Integrations/GoogleDrive/GoogleDrive_test.py | demisto/content | train | 1,023 | |
333bb71a0f464323e623b6126d50226f93b36e55 | [
"super(RecycleBinMetadataFile, self).__init__(debug=debug, output_writer=output_writer)\nself.deletion_time = None\nself.format_version = None\nself.original_filename = None\nself.original_file_size = None",
"data_type_map = self._GetDataTypeMap('recycle_bin_metadata_file_header')\nfile_header, _ = self._ReadStru... | <|body_start_0|>
super(RecycleBinMetadataFile, self).__init__(debug=debug, output_writer=output_writer)
self.deletion_time = None
self.format_version = None
self.original_filename = None
self.original_file_size = None
<|end_body_0|>
<|body_start_1|>
data_type_map = self.... | Windows Recycle.Bin metadata ($I) file. Attributes: deletion_time (int): FILETIME timestamp of the date and time the original file was deleted. format_version (int): format version of the metadata file. original_filename (str): original name of the deleted file. original_size (int): original size of the deleted file. | RecycleBinMetadataFile | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecycleBinMetadataFile:
"""Windows Recycle.Bin metadata ($I) file. Attributes: deletion_time (int): FILETIME timestamp of the date and time the original file was deleted. format_version (int): format version of the metadata file. original_filename (str): original name of the deleted file. origina... | stack_v2_sparse_classes_10k_train_005057 | 4,156 | permissive | [
{
"docstring": "Initializes a Windows Recycle.Bin metadata ($I) file. Args: debug (Optional[bool]): True if debug information should be written. output_writer (Optional[OutputWriter]): output writer.",
"name": "__init__",
"signature": "def __init__(self, debug=False, output_writer=None)"
},
{
"d... | 4 | stack_v2_sparse_classes_30k_train_001969 | Implement the Python class `RecycleBinMetadataFile` described below.
Class description:
Windows Recycle.Bin metadata ($I) file. Attributes: deletion_time (int): FILETIME timestamp of the date and time the original file was deleted. format_version (int): format version of the metadata file. original_filename (str): ori... | Implement the Python class `RecycleBinMetadataFile` described below.
Class description:
Windows Recycle.Bin metadata ($I) file. Attributes: deletion_time (int): FILETIME timestamp of the date and time the original file was deleted. format_version (int): format version of the metadata file. original_filename (str): ori... | 55007dcac48efff42c497e739208ebfb88e4048d | <|skeleton|>
class RecycleBinMetadataFile:
"""Windows Recycle.Bin metadata ($I) file. Attributes: deletion_time (int): FILETIME timestamp of the date and time the original file was deleted. format_version (int): format version of the metadata file. original_filename (str): original name of the deleted file. origina... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RecycleBinMetadataFile:
"""Windows Recycle.Bin metadata ($I) file. Attributes: deletion_time (int): FILETIME timestamp of the date and time the original file was deleted. format_version (int): format version of the metadata file. original_filename (str): original name of the deleted file. original_size (int):... | the_stack_v2_python_sparse | dtformats/recycle_bin.py | libyal/dtformats | train | 109 |
e96945fababa77d483574550ab01855da9d66d98 | [
"permission = AdministerOrganizationPermission(orgname)\nif permission.can():\n organization = model.organization.get_organization(orgname)\n return get_card(organization)\nraise Unauthorized()",
"permission = AdministerOrganizationPermission(orgname)\nif permission.can():\n organization = model.organiza... | <|body_start_0|>
permission = AdministerOrganizationPermission(orgname)
if permission.can():
organization = model.organization.get_organization(orgname)
return get_card(organization)
raise Unauthorized()
<|end_body_0|>
<|body_start_1|>
permission = AdministerOrga... | Resource for managing an organization's credit card. | OrganizationCard | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrganizationCard:
"""Resource for managing an organization's credit card."""
def get(self, orgname):
"""Get the organization's credit card."""
<|body_0|>
def post(self, orgname):
"""Update the orgnaization's credit card."""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_10k_train_005058 | 33,890 | permissive | [
{
"docstring": "Get the organization's credit card.",
"name": "get",
"signature": "def get(self, orgname)"
},
{
"docstring": "Update the orgnaization's credit card.",
"name": "post",
"signature": "def post(self, orgname)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003418 | Implement the Python class `OrganizationCard` described below.
Class description:
Resource for managing an organization's credit card.
Method signatures and docstrings:
- def get(self, orgname): Get the organization's credit card.
- def post(self, orgname): Update the orgnaization's credit card. | Implement the Python class `OrganizationCard` described below.
Class description:
Resource for managing an organization's credit card.
Method signatures and docstrings:
- def get(self, orgname): Get the organization's credit card.
- def post(self, orgname): Update the orgnaization's credit card.
<|skeleton|>
class O... | e400a0c22c5f89dd35d571654b13d262b1f6e3b3 | <|skeleton|>
class OrganizationCard:
"""Resource for managing an organization's credit card."""
def get(self, orgname):
"""Get the organization's credit card."""
<|body_0|>
def post(self, orgname):
"""Update the orgnaization's credit card."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OrganizationCard:
"""Resource for managing an organization's credit card."""
def get(self, orgname):
"""Get the organization's credit card."""
permission = AdministerOrganizationPermission(orgname)
if permission.can():
organization = model.organization.get_organization... | the_stack_v2_python_sparse | endpoints/api/billing.py | quay/quay | train | 2,363 |
1a17a1fb65e8aa5095a4d5390410177fd2aa74e6 | [
"if not hasattr(self, '_cfg'):\n raise ValueError('self._cfg must be set before calling _init_k2().')\nif not hasattr(self._cfg, 'graph_module_cfg') or self._cfg.graph_module_cfg is None:\n raise ValueError('self._cfg.graph_module_cfg must be set and cannot be None.')\nself.graph_module_cfg = self._cfg.graph_... | <|body_start_0|>
if not hasattr(self, '_cfg'):
raise ValueError('self._cfg must be set before calling _init_k2().')
if not hasattr(self._cfg, 'graph_module_cfg') or self._cfg.graph_module_cfg is None:
raise ValueError('self._cfg.graph_module_cfg must be set and cannot be None.')
... | k2 Mixin class that simplifies the construction of various models with k2-based losses. It does the following: - Sets up the graph loss and decoder (methods _init_k2 and update_k2_modules). - Registers external graphs, if needed. - Augments forward(...) with optional graph decoding to get accurate predictions. | ASRK2Mixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ASRK2Mixin:
"""k2 Mixin class that simplifies the construction of various models with k2-based losses. It does the following: - Sets up the graph loss and decoder (methods _init_k2 and update_k2_modules). - Registers external graphs, if needed. - Augments forward(...) with optional graph decoding... | stack_v2_sparse_classes_10k_train_005059 | 7,098 | permissive | [
{
"docstring": "k2-related initialization implementation. This method is expected to run after the __init__ which sets self._cfg self._cfg is expected to have the attribute graph_module_cfg",
"name": "_init_k2",
"signature": "def _init_k2(self)"
},
{
"docstring": "Helper function to initialize o... | 3 | null | Implement the Python class `ASRK2Mixin` described below.
Class description:
k2 Mixin class that simplifies the construction of various models with k2-based losses. It does the following: - Sets up the graph loss and decoder (methods _init_k2 and update_k2_modules). - Registers external graphs, if needed. - Augments fo... | Implement the Python class `ASRK2Mixin` described below.
Class description:
k2 Mixin class that simplifies the construction of various models with k2-based losses. It does the following: - Sets up the graph loss and decoder (methods _init_k2 and update_k2_modules). - Registers external graphs, if needed. - Augments fo... | c20a16ea8aa2a9d8e31a98eb22178ddb9d5935e7 | <|skeleton|>
class ASRK2Mixin:
"""k2 Mixin class that simplifies the construction of various models with k2-based losses. It does the following: - Sets up the graph loss and decoder (methods _init_k2 and update_k2_modules). - Registers external graphs, if needed. - Augments forward(...) with optional graph decoding... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ASRK2Mixin:
"""k2 Mixin class that simplifies the construction of various models with k2-based losses. It does the following: - Sets up the graph loss and decoder (methods _init_k2 and update_k2_modules). - Registers external graphs, if needed. - Augments forward(...) with optional graph decoding to get accur... | the_stack_v2_python_sparse | nemo/collections/asr/parts/k2/classes.py | NVIDIA/NeMo | train | 7,957 |
663a62b5eab366384fadf7e9f3b4e48215a2dfa1 | [
"self.name = name\nself.lan_ip = lan_ip\nself.uplink = uplink\nself.public_port = public_port\nself.local_port = local_port\nself.allowed_ips = allowed_ips\nself.protocol = protocol",
"if dictionary is None:\n return None\nname = dictionary.get('name')\nlan_ip = dictionary.get('lanIp')\nuplink = dictionary.get... | <|body_start_0|>
self.name = name
self.lan_ip = lan_ip
self.uplink = uplink
self.public_port = public_port
self.local_port = local_port
self.allowed_ips = allowed_ips
self.protocol = protocol
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
... | Implementation of the 'Rule9' model. TODO: type model description here. Attributes: name (string): A descriptive name for the rule lan_ip (string): The IP address of the server or device that hosts the internal resource that you wish to make available on the WAN uplink (string): The physical WAN interface on which the ... | Rule9Model | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rule9Model:
"""Implementation of the 'Rule9' model. TODO: type model description here. Attributes: name (string): A descriptive name for the rule lan_ip (string): The IP address of the server or device that hosts the internal resource that you wish to make available on the WAN uplink (string): Th... | stack_v2_sparse_classes_10k_train_005060 | 3,221 | permissive | [
{
"docstring": "Constructor for the Rule9Model class",
"name": "__init__",
"signature": "def __init__(self, name=None, lan_ip=None, uplink=None, public_port=None, local_port=None, allowed_ips=None, protocol=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dicti... | 2 | stack_v2_sparse_classes_30k_train_005017 | Implement the Python class `Rule9Model` described below.
Class description:
Implementation of the 'Rule9' model. TODO: type model description here. Attributes: name (string): A descriptive name for the rule lan_ip (string): The IP address of the server or device that hosts the internal resource that you wish to make a... | Implement the Python class `Rule9Model` described below.
Class description:
Implementation of the 'Rule9' model. TODO: type model description here. Attributes: name (string): A descriptive name for the rule lan_ip (string): The IP address of the server or device that hosts the internal resource that you wish to make a... | 9894089eb013318243ae48869cc5130eb37f80c0 | <|skeleton|>
class Rule9Model:
"""Implementation of the 'Rule9' model. TODO: type model description here. Attributes: name (string): A descriptive name for the rule lan_ip (string): The IP address of the server or device that hosts the internal resource that you wish to make available on the WAN uplink (string): Th... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Rule9Model:
"""Implementation of the 'Rule9' model. TODO: type model description here. Attributes: name (string): A descriptive name for the rule lan_ip (string): The IP address of the server or device that hosts the internal resource that you wish to make available on the WAN uplink (string): The physical WA... | the_stack_v2_python_sparse | meraki_sdk/models/rule_9_model.py | RaulCatalano/meraki-python-sdk | train | 1 |
28c0c57fef07c94ff880fe00eabff1d62060c27c | [
"if not api.cinder.is_volume_service_enabled(request):\n raise rest_utils.AjaxError(501, _('Service Cinder is disabled.'))\nquota_set = api.cinder.default_quota_get(request, request.user.tenant_id)\nresult = [{'display_name': quotas.QUOTA_NAMES.get(quota.name, quota.name.replace('_', ' ').title()) + '', 'name': ... | <|body_start_0|>
if not api.cinder.is_volume_service_enabled(request):
raise rest_utils.AjaxError(501, _('Service Cinder is disabled.'))
quota_set = api.cinder.default_quota_get(request, request.user.tenant_id)
result = [{'display_name': quotas.QUOTA_NAMES.get(quota.name, quota.name.... | API for getting default quotas for cinder | DefaultQuotaSets | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefaultQuotaSets:
"""API for getting default quotas for cinder"""
def get(self, request):
"""Get the values for Cinder specific quotas Example GET: http://localhost/api/cinder/quota-sets/defaults/"""
<|body_0|>
def patch(self, request):
"""Update the values for C... | stack_v2_sparse_classes_10k_train_005061 | 14,440 | permissive | [
{
"docstring": "Get the values for Cinder specific quotas Example GET: http://localhost/api/cinder/quota-sets/defaults/",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Update the values for Cinder specific quotas This method returns HTTP 204 (no content) on success.",
... | 2 | null | Implement the Python class `DefaultQuotaSets` described below.
Class description:
API for getting default quotas for cinder
Method signatures and docstrings:
- def get(self, request): Get the values for Cinder specific quotas Example GET: http://localhost/api/cinder/quota-sets/defaults/
- def patch(self, request): Up... | Implement the Python class `DefaultQuotaSets` described below.
Class description:
API for getting default quotas for cinder
Method signatures and docstrings:
- def get(self, request): Get the values for Cinder specific quotas Example GET: http://localhost/api/cinder/quota-sets/defaults/
- def patch(self, request): Up... | 7896fd8c77a6766a1156a520946efaf792b76ca5 | <|skeleton|>
class DefaultQuotaSets:
"""API for getting default quotas for cinder"""
def get(self, request):
"""Get the values for Cinder specific quotas Example GET: http://localhost/api/cinder/quota-sets/defaults/"""
<|body_0|>
def patch(self, request):
"""Update the values for C... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DefaultQuotaSets:
"""API for getting default quotas for cinder"""
def get(self, request):
"""Get the values for Cinder specific quotas Example GET: http://localhost/api/cinder/quota-sets/defaults/"""
if not api.cinder.is_volume_service_enabled(request):
raise rest_utils.AjaxEr... | the_stack_v2_python_sparse | openstack_dashboard/api/rest/cinder.py | openstack/horizon | train | 1,060 |
66fd1e94308a90fcc9030a979f26c054d3fe6061 | [
"super().__init__(**kwargs)\nself.label = label\nself.did = did\nself.recipient_keys = list(recipient_keys) if recipient_keys else None\nself.endpoint = endpoint\nself.routing_keys = list(routing_keys) if routing_keys else None\nself.image_url = image_url",
"c_json = self.to_json()\nc_i = bytes_to_b64(c_json.enco... | <|body_start_0|>
super().__init__(**kwargs)
self.label = label
self.did = did
self.recipient_keys = list(recipient_keys) if recipient_keys else None
self.endpoint = endpoint
self.routing_keys = list(routing_keys) if routing_keys else None
self.image_url = image_ur... | Class representing a connection invitation. | ConnectionInvitation | [
"LicenseRef-scancode-dco-1.1",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConnectionInvitation:
"""Class representing a connection invitation."""
def __init__(self, *, label: str=None, did: str=None, recipient_keys: Sequence[str]=None, endpoint: str=None, routing_keys: Sequence[str]=None, image_url: str=None, **kwargs):
"""Initialize connection invitation ... | stack_v2_sparse_classes_10k_train_005062 | 5,648 | permissive | [
{
"docstring": "Initialize connection invitation object. Args: label: Optional label for connection invitation did: DID for this connection invitation recipient_keys: List of recipient keys endpoint: Endpoint which this agent can be reached at routing_keys: List of routing keys image_url: Optional image URL for... | 3 | null | Implement the Python class `ConnectionInvitation` described below.
Class description:
Class representing a connection invitation.
Method signatures and docstrings:
- def __init__(self, *, label: str=None, did: str=None, recipient_keys: Sequence[str]=None, endpoint: str=None, routing_keys: Sequence[str]=None, image_ur... | Implement the Python class `ConnectionInvitation` described below.
Class description:
Class representing a connection invitation.
Method signatures and docstrings:
- def __init__(self, *, label: str=None, did: str=None, recipient_keys: Sequence[str]=None, endpoint: str=None, routing_keys: Sequence[str]=None, image_ur... | 39cac36d8937ce84a9307ce100aaefb8bc05ec04 | <|skeleton|>
class ConnectionInvitation:
"""Class representing a connection invitation."""
def __init__(self, *, label: str=None, did: str=None, recipient_keys: Sequence[str]=None, endpoint: str=None, routing_keys: Sequence[str]=None, image_url: str=None, **kwargs):
"""Initialize connection invitation ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ConnectionInvitation:
"""Class representing a connection invitation."""
def __init__(self, *, label: str=None, did: str=None, recipient_keys: Sequence[str]=None, endpoint: str=None, routing_keys: Sequence[str]=None, image_url: str=None, **kwargs):
"""Initialize connection invitation object. Args:... | the_stack_v2_python_sparse | aries_cloudagent/protocols/connections/v1_0/messages/connection_invitation.py | hyperledger/aries-cloudagent-python | train | 370 |
4408d3351401dc52435f2ab39e1f26ace725432a | [
"idx += 1\nself._idx = idx\nself._attr_name = f'{entry[CONF_NAME]} {idx}'\nself._attr_unique_id = entry.get(CONF_UNIQUE_ID)\nif self._attr_unique_id:\n self._attr_unique_id = f'{self._attr_unique_id}_{idx}'\nself._attr_native_unit_of_measurement = entry.get(CONF_UNIT_OF_MEASUREMENT)\nself._attr_state_class = ent... | <|body_start_0|>
idx += 1
self._idx = idx
self._attr_name = f'{entry[CONF_NAME]} {idx}'
self._attr_unique_id = entry.get(CONF_UNIQUE_ID)
if self._attr_unique_id:
self._attr_unique_id = f'{self._attr_unique_id}_{idx}'
self._attr_native_unit_of_measurement = ent... | Modbus slave register sensor. | SlaveSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SlaveSensor:
"""Modbus slave register sensor."""
def __init__(self, coordinator: DataUpdateCoordinator[list[int] | None], idx: int, entry: dict[str, Any]) -> None:
"""Initialize the Modbus register sensor."""
<|body_0|>
async def async_added_to_hass(self) -> None:
... | stack_v2_sparse_classes_10k_train_005063 | 6,226 | permissive | [
{
"docstring": "Initialize the Modbus register sensor.",
"name": "__init__",
"signature": "def __init__(self, coordinator: DataUpdateCoordinator[list[int] | None], idx: int, entry: dict[str, Any]) -> None"
},
{
"docstring": "Handle entity which will be added.",
"name": "async_added_to_hass",... | 3 | null | Implement the Python class `SlaveSensor` described below.
Class description:
Modbus slave register sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: DataUpdateCoordinator[list[int] | None], idx: int, entry: dict[str, Any]) -> None: Initialize the Modbus register sensor.
- async def async_add... | Implement the Python class `SlaveSensor` described below.
Class description:
Modbus slave register sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: DataUpdateCoordinator[list[int] | None], idx: int, entry: dict[str, Any]) -> None: Initialize the Modbus register sensor.
- async def async_add... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class SlaveSensor:
"""Modbus slave register sensor."""
def __init__(self, coordinator: DataUpdateCoordinator[list[int] | None], idx: int, entry: dict[str, Any]) -> None:
"""Initialize the Modbus register sensor."""
<|body_0|>
async def async_added_to_hass(self) -> None:
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SlaveSensor:
"""Modbus slave register sensor."""
def __init__(self, coordinator: DataUpdateCoordinator[list[int] | None], idx: int, entry: dict[str, Any]) -> None:
"""Initialize the Modbus register sensor."""
idx += 1
self._idx = idx
self._attr_name = f'{entry[CONF_NAME]} ... | the_stack_v2_python_sparse | homeassistant/components/modbus/sensor.py | home-assistant/core | train | 35,501 |
c886f53809179128f2c1587c8375019deaa81619 | [
"local_file = f'{local_path}system_logs.txt'\ncommand = f'sshpass -p {password} scp -o StrictHostKeyChecking=no {username}@{host}:{remote_file} {local_file}'\nprint(f'fetch command = {command}')\nos.system(command)\nreturn local_file",
"local_file = f'{local_path}secondary_system_logs.txt'\ncommand = f'sshpass -p... | <|body_start_0|>
local_file = f'{local_path}system_logs.txt'
command = f'sshpass -p {password} scp -o StrictHostKeyChecking=no {username}@{host}:{remote_file} {local_file}'
print(f'fetch command = {command}')
os.system(command)
return local_file
<|end_body_0|>
<|body_start_1|>
... | Copies system logs and access logs from server to local machine Methods: ---------- fetch_system_logs_from_server(host, username, password, remote_file, local_path="/tmp/") : fetches system logs from server and copies to local machine fetch_secondary_system_logs_from_server(host, username, password, remote_file, local_... | LogFetcher | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"WTFPL",
"GPL-2.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogFetcher:
"""Copies system logs and access logs from server to local machine Methods: ---------- fetch_system_logs_from_server(host, username, password, remote_file, local_path="/tmp/") : fetches system logs from server and copies to local machine fetch_secondary_system_logs_from_server(host, u... | stack_v2_sparse_classes_10k_train_005064 | 13,309 | permissive | [
{
"docstring": "Fetches system logs from server and copies to local machine :param host: str, ssh host :param username: str, ssh username :param password: str, ssh password :param remote_file: str, location of system logs on server :param local_path: str, local path to copy system logs to :return: local_file: s... | 3 | null | Implement the Python class `LogFetcher` described below.
Class description:
Copies system logs and access logs from server to local machine Methods: ---------- fetch_system_logs_from_server(host, username, password, remote_file, local_path="/tmp/") : fetches system logs from server and copies to local machine fetch_se... | Implement the Python class `LogFetcher` described below.
Class description:
Copies system logs and access logs from server to local machine Methods: ---------- fetch_system_logs_from_server(host, username, password, remote_file, local_path="/tmp/") : fetches system logs from server and copies to local machine fetch_se... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class LogFetcher:
"""Copies system logs and access logs from server to local machine Methods: ---------- fetch_system_logs_from_server(host, username, password, remote_file, local_path="/tmp/") : fetches system logs from server and copies to local machine fetch_secondary_system_logs_from_server(host, u... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LogFetcher:
"""Copies system logs and access logs from server to local machine Methods: ---------- fetch_system_logs_from_server(host, username, password, remote_file, local_path="/tmp/") : fetches system logs from server and copies to local machine fetch_secondary_system_logs_from_server(host, username, pass... | the_stack_v2_python_sparse | govern/data-security/ranger/ranger-tools/src/main/python/ranger_performance_tool/ranger_perf_utils/logging_utils.py | alldatacenter/alldata | train | 774 |
bfa466c23686fa68977400e011a6e42ccaacdf1a | [
"context = super(ProcesoNaatCreateView, self).get_context_data(**kwargs)\ncontext['proceso_list'] = naat_m.ProcesoNaat.objects.filter(capacitador=self.request.user)\nreturn context",
"try:\n form.instance.escuela = escuela_m.Escuela.objects.get(codigo=form.cleaned_data['udi'])\nexcept ObjectDoesNotExist:\n ... | <|body_start_0|>
context = super(ProcesoNaatCreateView, self).get_context_data(**kwargs)
context['proceso_list'] = naat_m.ProcesoNaat.objects.filter(capacitador=self.request.user)
return context
<|end_body_0|>
<|body_start_1|>
try:
form.instance.escuela = escuela_m.Escuela.o... | Vista para la creación de :class:`ProcesoNaat`. | ProcesoNaatCreateView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProcesoNaatCreateView:
"""Vista para la creación de :class:`ProcesoNaat`."""
def get_context_data(self, **kwargs):
"""Crea un listado de :class:`ProcesoNaat` asignados al usuario actual."""
<|body_0|>
def form_valid(self, form):
"""Asigna al usuario actual como `... | stack_v2_sparse_classes_10k_train_005065 | 7,670 | no_license | [
{
"docstring": "Crea un listado de :class:`ProcesoNaat` asignados al usuario actual.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
{
"docstring": "Asigna al usuario actual como `capacitador` del objeto.",
"name": "form_valid",
"signature": "def form... | 2 | null | Implement the Python class `ProcesoNaatCreateView` described below.
Class description:
Vista para la creación de :class:`ProcesoNaat`.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Crea un listado de :class:`ProcesoNaat` asignados al usuario actual.
- def form_valid(self, form): Asigna al ... | Implement the Python class `ProcesoNaatCreateView` described below.
Class description:
Vista para la creación de :class:`ProcesoNaat`.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Crea un listado de :class:`ProcesoNaat` asignados al usuario actual.
- def form_valid(self, form): Asigna al ... | 0e37786d7173abe820fd10b094ffcc2db9593a9c | <|skeleton|>
class ProcesoNaatCreateView:
"""Vista para la creación de :class:`ProcesoNaat`."""
def get_context_data(self, **kwargs):
"""Crea un listado de :class:`ProcesoNaat` asignados al usuario actual."""
<|body_0|>
def form_valid(self, form):
"""Asigna al usuario actual como `... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ProcesoNaatCreateView:
"""Vista para la creación de :class:`ProcesoNaat`."""
def get_context_data(self, **kwargs):
"""Crea un listado de :class:`ProcesoNaat` asignados al usuario actual."""
context = super(ProcesoNaatCreateView, self).get_context_data(**kwargs)
context['proceso_li... | the_stack_v2_python_sparse | src/apps/naat/views.py | jinchuika/app-suni | train | 7 |
295047fc94bc33bb6ef83c5a907a8d8daefc7077 | [
"res = []\nnums1.sort()\nnums2.sort()\ni, j = (0, 0)\nwhile i < len(nums1) and j < len(nums2):\n if nums1[i] < nums2[j]:\n i += 1\n elif nums1[i] > nums2[j]:\n j += 1\n else:\n res.append(nums1[i])\n i += 1\n j += 1\nreturn res",
"s, res = (set(), [])\nfor ele in nums1:... | <|body_start_0|>
res = []
nums1.sort()
nums2.sort()
i, j = (0, 0)
while i < len(nums1) and j < len(nums2):
if nums1[i] < nums2[j]:
i += 1
elif nums1[i] > nums2[j]:
j += 1
else:
res.append(nums1[i]... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> int:
"""求出两个数组的交集 Args: nums1: 数组1 nums2: 数组2 Returns: 数组的交集"""
<|body_0|>
def intersection2(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""两个数组求交集 Args: nums1: 数组1 nums2: 数组2 Returns... | stack_v2_sparse_classes_10k_train_005066 | 2,414 | permissive | [
{
"docstring": "求出两个数组的交集 Args: nums1: 数组1 nums2: 数组2 Returns: 数组的交集",
"name": "intersection",
"signature": "def intersection(self, nums1: List[int], nums2: List[int]) -> int"
},
{
"docstring": "两个数组求交集 Args: nums1: 数组1 nums2: 数组2 Returns: 数组交集",
"name": "intersection2",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_002799 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersection(self, nums1: List[int], nums2: List[int]) -> int: 求出两个数组的交集 Args: nums1: 数组1 nums2: 数组2 Returns: 数组的交集
- def intersection2(self, nums1: List[int], nums2: List[in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersection(self, nums1: List[int], nums2: List[int]) -> int: 求出两个数组的交集 Args: nums1: 数组1 nums2: 数组2 Returns: 数组的交集
- def intersection2(self, nums1: List[int], nums2: List[in... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> int:
"""求出两个数组的交集 Args: nums1: 数组1 nums2: 数组2 Returns: 数组的交集"""
<|body_0|>
def intersection2(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""两个数组求交集 Args: nums1: 数组1 nums2: 数组2 Returns... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> int:
"""求出两个数组的交集 Args: nums1: 数组1 nums2: 数组2 Returns: 数组的交集"""
res = []
nums1.sort()
nums2.sort()
i, j = (0, 0)
while i < len(nums1) and j < len(nums2):
if nums1[i] < nums2[j]:
... | the_stack_v2_python_sparse | src/leetcodepython/array/intersection_two_array_349.py | zhangyu345293721/leetcode | train | 101 | |
74fe1211a418eab461beca93dda90c74ade36697 | [
"super(Criterion, self).__init__()\nself.classifier = torch.nn.Linear(opt.network_feature_dim, 4, bias=False).to(opt.device)\nself.lr = opt.lr * 10\nself.name = 'imrot'",
"pred_batch = self.classifier(feature_batch)\nloss = torch.nn.CrossEntropyLoss()(pred_batch, imrot_labels.to(pred_batch.device))\nreturn loss"
... | <|body_start_0|>
super(Criterion, self).__init__()
self.classifier = torch.nn.Linear(opt.network_feature_dim, 4, bias=False).to(opt.device)
self.lr = opt.lr * 10
self.name = 'imrot'
<|end_body_0|>
<|body_start_1|>
pred_batch = self.classifier(feature_batch)
loss = torch.... | Criterion | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Criterion:
def __init__(self, opt):
"""Args: margin: Triplet Margin. nu: Regularisation Parameter for beta values if they are learned. beta: Class-Margin values. n_classes: Number of different classes during training."""
<|body_0|>
def forward(self, feature_batch, imrot_labe... | stack_v2_sparse_classes_10k_train_005067 | 1,471 | permissive | [
{
"docstring": "Args: margin: Triplet Margin. nu: Regularisation Parameter for beta values if they are learned. beta: Class-Margin values. n_classes: Number of different classes during training.",
"name": "__init__",
"signature": "def __init__(self, opt)"
},
{
"docstring": "Args: batch: torch.Te... | 2 | stack_v2_sparse_classes_30k_train_001242 | Implement the Python class `Criterion` described below.
Class description:
Implement the Criterion class.
Method signatures and docstrings:
- def __init__(self, opt): Args: margin: Triplet Margin. nu: Regularisation Parameter for beta values if they are learned. beta: Class-Margin values. n_classes: Number of differe... | Implement the Python class `Criterion` described below.
Class description:
Implement the Criterion class.
Method signatures and docstrings:
- def __init__(self, opt): Args: margin: Triplet Margin. nu: Regularisation Parameter for beta values if they are learned. beta: Class-Margin values. n_classes: Number of differe... | 01a7220bac7ebb1e70416ef663f3ba7cee9e8bf5 | <|skeleton|>
class Criterion:
def __init__(self, opt):
"""Args: margin: Triplet Margin. nu: Regularisation Parameter for beta values if they are learned. beta: Class-Margin values. n_classes: Number of different classes during training."""
<|body_0|>
def forward(self, feature_batch, imrot_labe... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Criterion:
def __init__(self, opt):
"""Args: margin: Triplet Margin. nu: Regularisation Parameter for beta values if they are learned. beta: Class-Margin values. n_classes: Number of different classes during training."""
super(Criterion, self).__init__()
self.classifier = torch.nn.Line... | the_stack_v2_python_sparse | criteria/imrot.py | chenyanlinzhugoushou/DCML | train | 0 | |
08fcec3b980c9b2c8b6d3ae532e08c5a1fae18b2 | [
"self._api_token = api_token\nself._client = GraphQLClient(api_server_url)\nif api_token:\n self._client.inject_token('bearer ' + api_token)",
"result = self._client.execute(query)\ndata = json.loads(result)\nreturn data"
] | <|body_start_0|>
self._api_token = api_token
self._client = GraphQLClient(api_server_url)
if api_token:
self._client.inject_token('bearer ' + api_token)
<|end_body_0|>
<|body_start_1|>
result = self._client.execute(query)
data = json.loads(result)
return data... | GithubClient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GithubClient:
def __init__(self, api_token, api_server_url='https://api.github.com/graphql'):
"""Client to interact with github graphql API Parameters ---------- api_token : str Github API token of user api_server_url : str Github API server url (default is 'https://api.github.com/graphq... | stack_v2_sparse_classes_10k_train_005068 | 987 | no_license | [
{
"docstring": "Client to interact with github graphql API Parameters ---------- api_token : str Github API token of user api_server_url : str Github API server url (default is 'https://api.github.com/graphql')",
"name": "__init__",
"signature": "def __init__(self, api_token, api_server_url='https://api... | 2 | stack_v2_sparse_classes_30k_train_006954 | Implement the Python class `GithubClient` described below.
Class description:
Implement the GithubClient class.
Method signatures and docstrings:
- def __init__(self, api_token, api_server_url='https://api.github.com/graphql'): Client to interact with github graphql API Parameters ---------- api_token : str Github AP... | Implement the Python class `GithubClient` described below.
Class description:
Implement the GithubClient class.
Method signatures and docstrings:
- def __init__(self, api_token, api_server_url='https://api.github.com/graphql'): Client to interact with github graphql API Parameters ---------- api_token : str Github AP... | 29d490ab1825594307097bdafa1a687bb9ddf80e | <|skeleton|>
class GithubClient:
def __init__(self, api_token, api_server_url='https://api.github.com/graphql'):
"""Client to interact with github graphql API Parameters ---------- api_token : str Github API token of user api_server_url : str Github API server url (default is 'https://api.github.com/graphq... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GithubClient:
def __init__(self, api_token, api_server_url='https://api.github.com/graphql'):
"""Client to interact with github graphql API Parameters ---------- api_token : str Github API token of user api_server_url : str Github API server url (default is 'https://api.github.com/graphql')"""
... | the_stack_v2_python_sparse | findcrashedcodedeveloper/githubapi/client.py | karambir252/findcrashedcodedeveloper | train | 0 | |
1dee58ad853b27fa553e17ac68436433645def6b | [
"stack = []\npreorder = ''\ncur = root\nstack.append(root)\nwhile cur or stack:\n cur = stack.pop()\n if cur:\n preorder += str(cur.val) + ','\n else:\n preorder += 'null' + ','\n if cur:\n stack.append(cur.right)\n stack.append(cur.left)\nreturn preorder",
"preorder_list =... | <|body_start_0|>
stack = []
preorder = ''
cur = root
stack.append(root)
while cur or stack:
cur = stack.pop()
if cur:
preorder += str(cur.val) + ','
else:
preorder += 'null' + ','
if cur:
... | 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_10k_train_005069 | 2,047 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_005865 | 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:... | 6e18c5d257840489cc3fb1079ae3804c743982a4 | <|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_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
stack = []
preorder = ''
cur = root
stack.append(root)
while cur or stack:
cur = stack.pop()
if cur:
preorder += s... | the_stack_v2_python_sparse | 剑指 Offer 37. 序列化二叉树.py | yangyuxiang1996/leetcode | train | 0 | |
f73e6f2de88634e45a4411e0a375430bc0ec99b6 | [
"t = 0\nwhile Y > X:\n if Y % 2 == 0:\n Y //= 2\n else:\n Y += 1\n t += 1\nreturn t + X - Y",
"q = [X]\nt = 0\nhas_larger = False\nwhile q:\n cur_q = []\n for e in q:\n if e == Y:\n return t\n cur = e * 2\n if cur >= 1:\n if cur > Y and (not ... | <|body_start_0|>
t = 0
while Y > X:
if Y % 2 == 0:
Y //= 2
else:
Y += 1
t += 1
return t + X - Y
<|end_body_0|>
<|body_start_1|>
q = [X]
t = 0
has_larger = False
while q:
cur_q = []
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def brokenCalc(self, X: int, Y: int) -> int:
"""004_greedy + work backward If Y is odd, we can do only Y = Y + 1 If Y is even, if we plus 1 to Y, then Y is odd, we need to plus another 1. And because (Y + 1 + 1) / 2 = (Y / 2) + 1, 3 operations are more than 2. We always choose ... | stack_v2_sparse_classes_10k_train_005070 | 2,145 | no_license | [
{
"docstring": "004_greedy + work backward If Y is odd, we can do only Y = Y + 1 If Y is even, if we plus 1 to Y, then Y is odd, we need to plus another 1. And because (Y + 1 + 1) / 2 = (Y / 2) + 1, 3 operations are more than 2. We always choose Y / 2 if Y is even.",
"name": "brokenCalc",
"signature": "... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def brokenCalc(self, X: int, Y: int) -> int: 004_greedy + work backward If Y is odd, we can do only Y = Y + 1 If Y is even, if we plus 1 to Y, then Y is odd, we need to plus anot... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def brokenCalc(self, X: int, Y: int) -> int: 004_greedy + work backward If Y is odd, we can do only Y = Y + 1 If Y is even, if we plus 1 to Y, then Y is odd, we need to plus anot... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def brokenCalc(self, X: int, Y: int) -> int:
"""004_greedy + work backward If Y is odd, we can do only Y = Y + 1 If Y is even, if we plus 1 to Y, then Y is odd, we need to plus another 1. And because (Y + 1 + 1) / 2 = (Y / 2) + 1, 3 operations are more than 2. We always choose ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def brokenCalc(self, X: int, Y: int) -> int:
"""004_greedy + work backward If Y is odd, we can do only Y = Y + 1 If Y is even, if we plus 1 to Y, then Y is odd, we need to plus another 1. And because (Y + 1 + 1) / 2 = (Y / 2) + 1, 3 operations are more than 2. We always choose Y / 2 if Y is ... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetCode/991 Broken Calculator.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
2b895cf4392273b689ddafc6f26c5ab11f737a5a | [
"super(CustomSmoothL1Loss, self).__init__()\nself.beta = beta\nself.reduction = reduction\nself.loss_weight = loss_weight",
"reduction = reduction_override if reduction_override else self.reduction\nif target.numel() > 0:\n loss_bbox = self.loss_weight * smooth_l1_loss(pred, target, weight, beta=self.beta, red... | <|body_start_0|>
super(CustomSmoothL1Loss, self).__init__()
self.beta = beta
self.reduction = reduction
self.loss_weight = loss_weight
<|end_body_0|>
<|body_start_1|>
reduction = reduction_override if reduction_override else self.reduction
if target.numel() > 0:
... | Smooth L1 Loss. | CustomSmoothL1Loss | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomSmoothL1Loss:
"""Smooth L1 Loss."""
def __init__(self, beta=1.0, reduction='mean', loss_weight=1.0):
"""Init smooth l1 loss."""
<|body_0|>
def forward(self, pred, target, weight=None, avg_factor=None, reduction_override=None, **kwargs):
"""Forward compute. ... | stack_v2_sparse_classes_10k_train_005071 | 13,829 | permissive | [
{
"docstring": "Init smooth l1 loss.",
"name": "__init__",
"signature": "def __init__(self, beta=1.0, reduction='mean', loss_weight=1.0)"
},
{
"docstring": "Forward compute. :param pred: predict :param target: target :param weight: weight :param avg_factor: avg factor :param reduction_override: ... | 2 | null | Implement the Python class `CustomSmoothL1Loss` described below.
Class description:
Smooth L1 Loss.
Method signatures and docstrings:
- def __init__(self, beta=1.0, reduction='mean', loss_weight=1.0): Init smooth l1 loss.
- def forward(self, pred, target, weight=None, avg_factor=None, reduction_override=None, **kwarg... | Implement the Python class `CustomSmoothL1Loss` described below.
Class description:
Smooth L1 Loss.
Method signatures and docstrings:
- def __init__(self, beta=1.0, reduction='mean', loss_weight=1.0): Init smooth l1 loss.
- def forward(self, pred, target, weight=None, avg_factor=None, reduction_override=None, **kwarg... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class CustomSmoothL1Loss:
"""Smooth L1 Loss."""
def __init__(self, beta=1.0, reduction='mean', loss_weight=1.0):
"""Init smooth l1 loss."""
<|body_0|>
def forward(self, pred, target, weight=None, avg_factor=None, reduction_override=None, **kwargs):
"""Forward compute. ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CustomSmoothL1Loss:
"""Smooth L1 Loss."""
def __init__(self, beta=1.0, reduction='mean', loss_weight=1.0):
"""Init smooth l1 loss."""
super(CustomSmoothL1Loss, self).__init__()
self.beta = beta
self.reduction = reduction
self.loss_weight = loss_weight
def forw... | the_stack_v2_python_sparse | built-in/TensorFlow/Research/cv/image_classification/Darts_for_TensorFlow/automl/vega/search_space/networks/pytorch/operator/rpn.py | Huawei-Ascend/modelzoo | train | 1 |
92a26ea192637dcdf422b462a446a22806887140 | [
"super().__init__()\nself.image_conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels // 2, **kwargs)\nself.kspace_conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels // 2, **kwargs)\nself.forward_operator = forward_operator\nself.backward_operator = backward_operator\nself._channels_d... | <|body_start_0|>
super().__init__()
self.image_conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels // 2, **kwargs)
self.kspace_conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels // 2, **kwargs)
self.forward_operator = forward_operator
self.backwar... | MultiDomainConv2d | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiDomainConv2d:
def __init__(self, forward_operator: Callable, backward_operator: Callable, in_channels: int, out_channels: int, **kwargs):
"""Inits :class:`MultiDomainConv2d`. Parameters ---------- forward_operator: Callable Forward Operator. backward_operator: Callable Backward Oper... | stack_v2_sparse_classes_10k_train_005072 | 11,794 | permissive | [
{
"docstring": "Inits :class:`MultiDomainConv2d`. Parameters ---------- forward_operator: Callable Forward Operator. backward_operator: Callable Backward Operator. in_channels: int Number of input channels. out_channels: int Number of output channels.",
"name": "__init__",
"signature": "def __init__(sel... | 2 | stack_v2_sparse_classes_30k_val_000361 | Implement the Python class `MultiDomainConv2d` described below.
Class description:
Implement the MultiDomainConv2d class.
Method signatures and docstrings:
- def __init__(self, forward_operator: Callable, backward_operator: Callable, in_channels: int, out_channels: int, **kwargs): Inits :class:`MultiDomainConv2d`. Pa... | Implement the Python class `MultiDomainConv2d` described below.
Class description:
Implement the MultiDomainConv2d class.
Method signatures and docstrings:
- def __init__(self, forward_operator: Callable, backward_operator: Callable, in_channels: int, out_channels: int, **kwargs): Inits :class:`MultiDomainConv2d`. Pa... | 2a4c29342bc52a404aae097bc2654fb4323e1ac8 | <|skeleton|>
class MultiDomainConv2d:
def __init__(self, forward_operator: Callable, backward_operator: Callable, in_channels: int, out_channels: int, **kwargs):
"""Inits :class:`MultiDomainConv2d`. Parameters ---------- forward_operator: Callable Forward Operator. backward_operator: Callable Backward Oper... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MultiDomainConv2d:
def __init__(self, forward_operator: Callable, backward_operator: Callable, in_channels: int, out_channels: int, **kwargs):
"""Inits :class:`MultiDomainConv2d`. Parameters ---------- forward_operator: Callable Forward Operator. backward_operator: Callable Backward Operator. in_chann... | the_stack_v2_python_sparse | direct/nn/multidomainnet/multidomain.py | NKI-AI/direct | train | 151 | |
472abe0395a624babf2be5b4f23a1877eda808c8 | [
"start_time = time.time()\nrequest_data = {'开始时间': start_time}\nif request.GET.dict():\n request_data['query_params'] = request.GET.dict()\nif request.body:\n try:\n request_data['data'] = json.loads(request.body.decode('utf8', 'ignore'))\n except:\n request_data['data'] = request.body.decode... | <|body_start_0|>
start_time = time.time()
request_data = {'开始时间': start_time}
if request.GET.dict():
request_data['query_params'] = request.GET.dict()
if request.body:
try:
request_data['data'] = json.loads(request.body.decode('utf8', 'ignore'))
... | 自定义日志中间件 | LoggerMiddleware | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoggerMiddleware:
"""自定义日志中间件"""
def process_request(self, request):
"""请求信息"""
<|body_0|>
def process_response(self, request, response):
"""响应信息"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
start_time = time.time()
request_data = {'开... | stack_v2_sparse_classes_10k_train_005073 | 1,946 | no_license | [
{
"docstring": "请求信息",
"name": "process_request",
"signature": "def process_request(self, request)"
},
{
"docstring": "响应信息",
"name": "process_response",
"signature": "def process_response(self, request, response)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002110 | Implement the Python class `LoggerMiddleware` described below.
Class description:
自定义日志中间件
Method signatures and docstrings:
- def process_request(self, request): 请求信息
- def process_response(self, request, response): 响应信息 | Implement the Python class `LoggerMiddleware` described below.
Class description:
自定义日志中间件
Method signatures and docstrings:
- def process_request(self, request): 请求信息
- def process_response(self, request, response): 响应信息
<|skeleton|>
class LoggerMiddleware:
"""自定义日志中间件"""
def process_request(self, request)... | 764df78c59d6e9c2dafee65e875b29df2635d33c | <|skeleton|>
class LoggerMiddleware:
"""自定义日志中间件"""
def process_request(self, request):
"""请求信息"""
<|body_0|>
def process_response(self, request, response):
"""响应信息"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LoggerMiddleware:
"""自定义日志中间件"""
def process_request(self, request):
"""请求信息"""
start_time = time.time()
request_data = {'开始时间': start_time}
if request.GET.dict():
request_data['query_params'] = request.GET.dict()
if request.body:
try:
... | the_stack_v2_python_sparse | utils/custom_middleware.py | shawnhuang90s/oms_test | train | 2 |
5e5f3f3f9e42bf5e4464012324a3c61083dc0816 | [
"self.id = id\nself.account_id = account_id\nself.audit_log_reference = audit_log_reference\nself.external_reference = external_reference\nself.oauth_client_id = oauth_client_id\nself.ip_address = ip_address\nself.xslt = xslt\nself.data_to_sign = data_to_sign\nself.result = result\nself.certificate = certificate\ns... | <|body_start_0|>
self.id = id
self.account_id = account_id
self.audit_log_reference = audit_log_reference
self.external_reference = external_reference
self.oauth_client_id = oauth_client_id
self.ip_address = ip_address
self.xslt = xslt
self.data_to_sign = ... | Implementation of the 'MerchantSignTransaction' model. TODO: type model description here. Attributes: id (uuid|string): Transaction Id account_id (uuid|string): Your account Id audit_log_reference (uuid|string): Audit log Id external_reference (string): External Reference oauth_client_id (string): The oauth client used... | MerchantSignTransaction | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MerchantSignTransaction:
"""Implementation of the 'MerchantSignTransaction' model. TODO: type model description here. Attributes: id (uuid|string): Transaction Id account_id (uuid|string): Your account Id audit_log_reference (uuid|string): Audit log Id external_reference (string): External Refere... | stack_v2_sparse_classes_10k_train_005074 | 4,518 | permissive | [
{
"docstring": "Constructor for the MerchantSignTransaction class",
"name": "__init__",
"signature": "def __init__(self, id=None, account_id=None, audit_log_reference=None, external_reference=None, oauth_client_id=None, ip_address=None, xslt=None, data_to_sign=None, result=None, certificate=None, time_s... | 2 | stack_v2_sparse_classes_30k_train_000507 | Implement the Python class `MerchantSignTransaction` described below.
Class description:
Implementation of the 'MerchantSignTransaction' model. TODO: type model description here. Attributes: id (uuid|string): Transaction Id account_id (uuid|string): Your account Id audit_log_reference (uuid|string): Audit log Id exter... | Implement the Python class `MerchantSignTransaction` described below.
Class description:
Implementation of the 'MerchantSignTransaction' model. TODO: type model description here. Attributes: id (uuid|string): Transaction Id account_id (uuid|string): Your account Id audit_log_reference (uuid|string): Audit log Id exter... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class MerchantSignTransaction:
"""Implementation of the 'MerchantSignTransaction' model. TODO: type model description here. Attributes: id (uuid|string): Transaction Id account_id (uuid|string): Your account Id audit_log_reference (uuid|string): Audit log Id external_reference (string): External Refere... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MerchantSignTransaction:
"""Implementation of the 'MerchantSignTransaction' model. TODO: type model description here. Attributes: id (uuid|string): Transaction Id account_id (uuid|string): Your account Id audit_log_reference (uuid|string): Audit log Id external_reference (string): External Reference oauth_cli... | the_stack_v2_python_sparse | idfy_rest_client/models/merchant_sign_transaction.py | dealflowteam/Idfy | train | 0 |
69746af90ba335af041a1de93b86eecf7a37a909 | [
"if balance < Decimal('0.00'):\n raise ValueError('Initial balance must be >= to 0.00.')\nself.name = name\nself.balance = balance",
"if amount < Decimal('0.00'):\n raise ValueError('amount must be positive.')\nself.balance += amount",
"if amount > self.balance:\n raise ValueError('amount must be <= to... | <|body_start_0|>
if balance < Decimal('0.00'):
raise ValueError('Initial balance must be >= to 0.00.')
self.name = name
self.balance = balance
<|end_body_0|>
<|body_start_1|>
if amount < Decimal('0.00'):
raise ValueError('amount must be positive.')
self.b... | Account class for maintaining a bank account balance. | Account | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Account:
"""Account class for maintaining a bank account balance."""
def __init__(self, name, balance):
"""Initialize an Account object."""
<|body_0|>
def deposit(self, amount):
"""Deposit money to the account."""
<|body_1|>
def withdraw(self, amount... | stack_v2_sparse_classes_10k_train_005075 | 1,081 | no_license | [
{
"docstring": "Initialize an Account object.",
"name": "__init__",
"signature": "def __init__(self, name, balance)"
},
{
"docstring": "Deposit money to the account.",
"name": "deposit",
"signature": "def deposit(self, amount)"
},
{
"docstring": "Withdraw money from the account."... | 3 | stack_v2_sparse_classes_30k_train_002259 | Implement the Python class `Account` described below.
Class description:
Account class for maintaining a bank account balance.
Method signatures and docstrings:
- def __init__(self, name, balance): Initialize an Account object.
- def deposit(self, amount): Deposit money to the account.
- def withdraw(self, amount): W... | Implement the Python class `Account` described below.
Class description:
Account class for maintaining a bank account balance.
Method signatures and docstrings:
- def __init__(self, name, balance): Initialize an Account object.
- def deposit(self, amount): Deposit money to the account.
- def withdraw(self, amount): W... | b36ce1c9029eab390f380563912ccc09f678c053 | <|skeleton|>
class Account:
"""Account class for maintaining a bank account balance."""
def __init__(self, name, balance):
"""Initialize an Account object."""
<|body_0|>
def deposit(self, amount):
"""Deposit money to the account."""
<|body_1|>
def withdraw(self, amount... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Account:
"""Account class for maintaining a bank account balance."""
def __init__(self, name, balance):
"""Initialize an Account object."""
if balance < Decimal('0.00'):
raise ValueError('Initial balance must be >= to 0.00.')
self.name = name
self.balance = bal... | the_stack_v2_python_sparse | Deitel P., Deitel H. - Intro to Python for Computer Science and Data Science - 2020/classes10/account.py | valex/PythonLearning | train | 0 |
0c5a3818a46339c70220d9992bbbad6e8f416941 | [
"if head is None and tail is None:\n return None\nif target.val < head.val:\n return None\nelif target.val >= tail.val:\n return tail\nelse:\n smaller = None\n node = head\n while node != target:\n if node.val <= target.val:\n smaller = node\n node = node.next\n return ... | <|body_start_0|>
if head is None and tail is None:
return None
if target.val < head.val:
return None
elif target.val >= tail.val:
return tail
else:
smaller = None
node = head
while node != target:
if ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def insertion_point(self, head, tail, target):
""">>> s = Solution() >>> head = LinkedList.fromList([7, 8]) >>> tail, target = head, head.next >>> point = s.insertion_point(head, tail, target) >>> point.val 7 >>> head = LinkedList.fromList([8, 7]) >>> tail, target = head, head.... | stack_v2_sparse_classes_10k_train_005076 | 3,754 | no_license | [
{
"docstring": ">>> s = Solution() >>> head = LinkedList.fromList([7, 8]) >>> tail, target = head, head.next >>> point = s.insertion_point(head, tail, target) >>> point.val 7 >>> head = LinkedList.fromList([8, 7]) >>> tail, target = head, head.next >>> point = s.insertion_point(head, tail, target) >>> point is ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def insertion_point(self, head, tail, target): >>> s = Solution() >>> head = LinkedList.fromList([7, 8]) >>> tail, target = head, head.next >>> point = s.insertion_point(head, ta... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def insertion_point(self, head, tail, target): >>> s = Solution() >>> head = LinkedList.fromList([7, 8]) >>> tail, target = head, head.next >>> point = s.insertion_point(head, ta... | 3b13a02f9c8273f9794a57b948d2655792707f37 | <|skeleton|>
class Solution:
def insertion_point(self, head, tail, target):
""">>> s = Solution() >>> head = LinkedList.fromList([7, 8]) >>> tail, target = head, head.next >>> point = s.insertion_point(head, tail, target) >>> point.val 7 >>> head = LinkedList.fromList([8, 7]) >>> tail, target = head, head.... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def insertion_point(self, head, tail, target):
""">>> s = Solution() >>> head = LinkedList.fromList([7, 8]) >>> tail, target = head, head.next >>> point = s.insertion_point(head, tail, target) >>> point.val 7 >>> head = LinkedList.fromList([8, 7]) >>> tail, target = head, head.next >>> point... | the_stack_v2_python_sparse | insertion_sort_list.py | gsy/leetcode | train | 1 | |
d733014a1e531a098d057a58d33201308abd1c0f | [
"model = model if isinstance(model, SpaceForDialogModeling) else Model.from_pretrained(model)\nself.model = model\nif preprocessor is None:\n preprocessor = DialogModelingPreprocessor(model.model_dir)\nsuper().__init__(model=model, preprocessor=preprocessor, **kwargs)\nself.preprocessor = preprocessor",
"sys_r... | <|body_start_0|>
model = model if isinstance(model, SpaceForDialogModeling) else Model.from_pretrained(model)
self.model = model
if preprocessor is None:
preprocessor = DialogModelingPreprocessor(model.model_dir)
super().__init__(model=model, preprocessor=preprocessor, **kwar... | DialogModelingPipeline | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DialogModelingPipeline:
def __init__(self, model: Union[SpaceForDialogModeling, str], preprocessor: DialogModelingPreprocessor=None, **kwargs):
"""Use `model` and `preprocessor` to create a dialog modeling pipeline for dialog response generation Args: model (str or SpaceForDialogModeling... | stack_v2_sparse_classes_10k_train_005077 | 2,107 | permissive | [
{
"docstring": "Use `model` and `preprocessor` to create a dialog modeling pipeline for dialog response generation Args: model (str or SpaceForDialogModeling): Supply either a local model dir or a model id from the model hub, or a SpaceForDialogModeling instance. preprocessor (DialogModelingPreprocessor): An op... | 2 | null | Implement the Python class `DialogModelingPipeline` described below.
Class description:
Implement the DialogModelingPipeline class.
Method signatures and docstrings:
- def __init__(self, model: Union[SpaceForDialogModeling, str], preprocessor: DialogModelingPreprocessor=None, **kwargs): Use `model` and `preprocessor`... | Implement the Python class `DialogModelingPipeline` described below.
Class description:
Implement the DialogModelingPipeline class.
Method signatures and docstrings:
- def __init__(self, model: Union[SpaceForDialogModeling, str], preprocessor: DialogModelingPreprocessor=None, **kwargs): Use `model` and `preprocessor`... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class DialogModelingPipeline:
def __init__(self, model: Union[SpaceForDialogModeling, str], preprocessor: DialogModelingPreprocessor=None, **kwargs):
"""Use `model` and `preprocessor` to create a dialog modeling pipeline for dialog response generation Args: model (str or SpaceForDialogModeling... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DialogModelingPipeline:
def __init__(self, model: Union[SpaceForDialogModeling, str], preprocessor: DialogModelingPreprocessor=None, **kwargs):
"""Use `model` and `preprocessor` to create a dialog modeling pipeline for dialog response generation Args: model (str or SpaceForDialogModeling): Supply eith... | the_stack_v2_python_sparse | ai/modelscope/modelscope/pipelines/nlp/dialog_modeling_pipeline.py | alldatacenter/alldata | train | 774 | |
efb8513451ff07317b4456adc0bc05d4546c727d | [
"from CortexDataLake import Client\nif exception:\n with pytest.raises(DemistoException):\n Client._backoff_strategy(integration_context)\nelse:\n Client._backoff_strategy(integration_context)",
"from CortexDataLake import Client\nupdated_ic = Client._cache_failure_times(integration_context.copy())\n... | <|body_start_0|>
from CortexDataLake import Client
if exception:
with pytest.raises(DemistoException):
Client._backoff_strategy(integration_context)
else:
Client._backoff_strategy(integration_context)
<|end_body_0|>
<|body_start_1|>
from CortexDat... | A class to test the backoff strategy mechanism | TestBackoffStrategy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestBackoffStrategy:
"""A class to test the backoff strategy mechanism"""
def test_backoff_strategy(self, integration_context, exception):
"""Given: - An integration context that represents a try to fetch in the 1st hour & 1st minute window - An integration context that represents a ... | stack_v2_sparse_classes_10k_train_005078 | 15,019 | permissive | [
{
"docstring": "Given: - An integration context that represents a try to fetch in the 1st hour & 1st minute window - An integration context that represents a try to fetch in the first 48 hours & 10 minutes window - An integration context that represents a try to fetch after 48 hours & 60 minutes window - An int... | 3 | stack_v2_sparse_classes_30k_train_002476 | Implement the Python class `TestBackoffStrategy` described below.
Class description:
A class to test the backoff strategy mechanism
Method signatures and docstrings:
- def test_backoff_strategy(self, integration_context, exception): Given: - An integration context that represents a try to fetch in the 1st hour & 1st ... | Implement the Python class `TestBackoffStrategy` described below.
Class description:
A class to test the backoff strategy mechanism
Method signatures and docstrings:
- def test_backoff_strategy(self, integration_context, exception): Given: - An integration context that represents a try to fetch in the 1st hour & 1st ... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestBackoffStrategy:
"""A class to test the backoff strategy mechanism"""
def test_backoff_strategy(self, integration_context, exception):
"""Given: - An integration context that represents a try to fetch in the 1st hour & 1st minute window - An integration context that represents a ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestBackoffStrategy:
"""A class to test the backoff strategy mechanism"""
def test_backoff_strategy(self, integration_context, exception):
"""Given: - An integration context that represents a try to fetch in the 1st hour & 1st minute window - An integration context that represents a try to fetch ... | the_stack_v2_python_sparse | Packs/CortexDataLake/Integrations/CortexDataLake/CortexDataLake_test.py | demisto/content | train | 1,023 |
b1bd9176ed8c7004b2fe625b5ced7b081418164c | [
"self.sigmoid_layers = []\nself.rbm_layers = []\nself.params = []\nself.n_layers = len(hidden_layers_sizes)\nassert self.n_layers > 0\nif not theano_rng:\n theano_rng = MRG_RandomStreams(numpy_rng.randint(2 ** 30))\nself.x = T.matrix('x')\nself.y = T.ivector('y')\nfor i in range(self.n_layers):\n if i == 0:\n... | <|body_start_0|>
self.sigmoid_layers = []
self.rbm_layers = []
self.params = []
self.n_layers = len(hidden_layers_sizes)
assert self.n_layers > 0
if not theano_rng:
theano_rng = MRG_RandomStreams(numpy_rng.randint(2 ** 30))
self.x = T.matrix('x')
... | Deep Belief Network | DBN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DBN:
"""Deep Belief Network"""
def __init__(self, numpy_rng, theano_rng=None, n_ins=784, hidden_layers_sizes=[500, 500], n_outs=10):
"""This class is made to support a variable number of layers. numpy_rng is the random state number. numpy_rng is the generator to draw initial weights.... | stack_v2_sparse_classes_10k_train_005079 | 9,191 | no_license | [
{
"docstring": "This class is made to support a variable number of layers. numpy_rng is the random state number. numpy_rng is the generator to draw initial weights. theano_rng is for tensor's theano rng. n_ins is an integer of the input dimension. hidden_layer_sizes is the intermediate layers size. n_outs is ou... | 3 | stack_v2_sparse_classes_30k_train_002911 | Implement the Python class `DBN` described below.
Class description:
Deep Belief Network
Method signatures and docstrings:
- def __init__(self, numpy_rng, theano_rng=None, n_ins=784, hidden_layers_sizes=[500, 500], n_outs=10): This class is made to support a variable number of layers. numpy_rng is the random state nu... | Implement the Python class `DBN` described below.
Class description:
Deep Belief Network
Method signatures and docstrings:
- def __init__(self, numpy_rng, theano_rng=None, n_ins=784, hidden_layers_sizes=[500, 500], n_outs=10): This class is made to support a variable number of layers. numpy_rng is the random state nu... | 6849cc891bbb9ac69cb20dfb13fe6bb5bd77d8c5 | <|skeleton|>
class DBN:
"""Deep Belief Network"""
def __init__(self, numpy_rng, theano_rng=None, n_ins=784, hidden_layers_sizes=[500, 500], n_outs=10):
"""This class is made to support a variable number of layers. numpy_rng is the random state number. numpy_rng is the generator to draw initial weights.... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DBN:
"""Deep Belief Network"""
def __init__(self, numpy_rng, theano_rng=None, n_ins=784, hidden_layers_sizes=[500, 500], n_outs=10):
"""This class is made to support a variable number of layers. numpy_rng is the random state number. numpy_rng is the generator to draw initial weights. theano_rng i... | the_stack_v2_python_sparse | algebra/linear/deepbeliefnetwork.py | HussainAther/mathematics | train | 2 |
710c87e625f42cfa640f04982a56062eb857a5c9 | [
"if verbose:\n print(\"-> Parsing symbol table from '{}' <-\".format(binary))\nwith open(binary, 'rb') as binfp:\n elf = ELFFile(binfp)\n symtabSection = elf.get_section_by_name('.symtab')\n assert symtabSection, 'No symbol table'\n self.symbols = {}\n self.addrs = {}\n for sym in symtabSection... | <|body_start_0|>
if verbose:
print("-> Parsing symbol table from '{}' <-".format(binary))
with open(binary, 'rb') as binfp:
elf = ELFFile(binfp)
symtabSection = elf.get_section_by_name('.symtab')
assert symtabSection, 'No symbol table'
self.sym... | A symbol table. Duh. | SymbolTable | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SymbolTable:
"""A symbol table. Duh."""
def __init__(self, binary, verbose):
"""Read the symbol table from a file. Return true if we parsed it correctly, false otherwise."""
<|body_0|>
def getSymbol(self, addr):
"""Look up the symbol containing the faulting addre... | stack_v2_sparse_classes_10k_train_005080 | 5,525 | no_license | [
{
"docstring": "Read the symbol table from a file. Return true if we parsed it correctly, false otherwise.",
"name": "__init__",
"signature": "def __init__(self, binary, verbose)"
},
{
"docstring": "Look up the symbol containing the faulting address. Because symbols occupy a range of memory, we ... | 2 | stack_v2_sparse_classes_30k_train_002882 | Implement the Python class `SymbolTable` described below.
Class description:
A symbol table. Duh.
Method signatures and docstrings:
- def __init__(self, binary, verbose): Read the symbol table from a file. Return true if we parsed it correctly, false otherwise.
- def getSymbol(self, addr): Look up the symbol containi... | Implement the Python class `SymbolTable` described below.
Class description:
A symbol table. Duh.
Method signatures and docstrings:
- def __init__(self, binary, verbose): Read the symbol table from a file. Return true if we parsed it correctly, false otherwise.
- def getSymbol(self, addr): Look up the symbol containi... | bc5fbea980af9cb300ab5742bad8a5cf06672b95 | <|skeleton|>
class SymbolTable:
"""A symbol table. Duh."""
def __init__(self, binary, verbose):
"""Read the symbol table from a file. Return true if we parsed it correctly, false otherwise."""
<|body_0|>
def getSymbol(self, addr):
"""Look up the symbol containing the faulting addre... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SymbolTable:
"""A symbol table. Duh."""
def __init__(self, binary, verbose):
"""Read the symbol table from a file. Return true if we parsed it correctly, false otherwise."""
if verbose:
print("-> Parsing symbol table from '{}' <-".format(binary))
with open(binary, 'rb'... | the_stack_v2_python_sparse | tool/page_access_trace/symtab.py | ssrg-vt/popcorn-compiler | train | 38 |
027df7c8114871c14f88518b1a06773991d39b54 | [
"forword = [(-1, 0), (0, 1), (1, 0), (0, -1), (-1, -1), (-1, 1), (1, 1), (1, -1)]\nrows = len(board)\ncols = len(board[0])\nfor r in range(rows):\n for c in range(cols):\n cnt = 0\n for i in forword:\n newx, newy = (r + i[0], c + i[1])\n if 0 <= newx < rows and 0 <= newy < col... | <|body_start_0|>
forword = [(-1, 0), (0, 1), (1, 0), (0, -1), (-1, -1), (-1, 1), (1, 1), (1, -1)]
rows = len(board)
cols = len(board[0])
for r in range(rows):
for c in range(cols):
cnt = 0
for i in forword:
newx, newy = (r +... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def gameOfLife2(self, board: List[List[int]]) -> None:
"""Do not return anything, modify board in-place instead."""
<|body_0|>
def gameOfLife(self, board: List[List[int]]) -> None:
"""Do not return anything, modify board in-place instead."""
<|body_... | stack_v2_sparse_classes_10k_train_005081 | 5,156 | no_license | [
{
"docstring": "Do not return anything, modify board in-place instead.",
"name": "gameOfLife2",
"signature": "def gameOfLife2(self, board: List[List[int]]) -> None"
},
{
"docstring": "Do not return anything, modify board in-place instead.",
"name": "gameOfLife",
"signature": "def gameOfL... | 2 | stack_v2_sparse_classes_30k_train_002840 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def gameOfLife2(self, board: List[List[int]]) -> None: Do not return anything, modify board in-place instead.
- def gameOfLife(self, board: List[List[int]]) -> None: Do not retur... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def gameOfLife2(self, board: List[List[int]]) -> None: Do not return anything, modify board in-place instead.
- def gameOfLife(self, board: List[List[int]]) -> None: Do not retur... | b0f498ebe84e46b7e17e94759dd462891dcc8f85 | <|skeleton|>
class Solution:
def gameOfLife2(self, board: List[List[int]]) -> None:
"""Do not return anything, modify board in-place instead."""
<|body_0|>
def gameOfLife(self, board: List[List[int]]) -> None:
"""Do not return anything, modify board in-place instead."""
<|body_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def gameOfLife2(self, board: List[List[int]]) -> None:
"""Do not return anything, modify board in-place instead."""
forword = [(-1, 0), (0, 1), (1, 0), (0, -1), (-1, -1), (-1, 1), (1, 1), (1, -1)]
rows = len(board)
cols = len(board[0])
for r in range(rows):
... | the_stack_v2_python_sparse | leetcode-vscode/289.生命游戏.py | wulinlw/leetcode_cn | train | 0 | |
75772a0ce689e28f494ed9caa33d43ade6411f11 | [
"self.settings = settings\nself.results = ResultSet()\nself.seq = SequenceNumber()\nself.exp_durations = collections.deque(maxlen=30)\nself.n_success = 0\nself.n_fail = 0\nself.summary_freq = summary_freq\nself._stop = False\nif self.settings.PARALLEL_EXECUTION:\n self.pool = mp.Pool(settings.N_PROCESSES)",
"l... | <|body_start_0|>
self.settings = settings
self.results = ResultSet()
self.seq = SequenceNumber()
self.exp_durations = collections.deque(maxlen=30)
self.n_success = 0
self.n_fail = 0
self.summary_freq = summary_freq
self._stop = False
if self.settin... | Orchestrator. It is responsible for orchestrating the execution of all experiments and aggregate results. | Orchestrator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Orchestrator:
"""Orchestrator. It is responsible for orchestrating the execution of all experiments and aggregate results."""
def __init__(self, settings, summary_freq=4):
"""Constructor Parameters ---------- settings : Settings The settings of the simulator summary_freq : int Freque... | stack_v2_sparse_classes_10k_train_005082 | 12,065 | permissive | [
{
"docstring": "Constructor Parameters ---------- settings : Settings The settings of the simulator summary_freq : int Frequency (in number of experiment) at which summary messages are displayed",
"name": "__init__",
"signature": "def __init__(self, settings, summary_freq=4)"
},
{
"docstring": "... | 4 | stack_v2_sparse_classes_30k_train_005128 | Implement the Python class `Orchestrator` described below.
Class description:
Orchestrator. It is responsible for orchestrating the execution of all experiments and aggregate results.
Method signatures and docstrings:
- def __init__(self, settings, summary_freq=4): Constructor Parameters ---------- settings : Setting... | Implement the Python class `Orchestrator` described below.
Class description:
Orchestrator. It is responsible for orchestrating the execution of all experiments and aggregate results.
Method signatures and docstrings:
- def __init__(self, settings, summary_freq=4): Constructor Parameters ---------- settings : Setting... | b7bb9f9b8d0f27b4b01469dcba9cfc0c4949d64b | <|skeleton|>
class Orchestrator:
"""Orchestrator. It is responsible for orchestrating the execution of all experiments and aggregate results."""
def __init__(self, settings, summary_freq=4):
"""Constructor Parameters ---------- settings : Settings The settings of the simulator summary_freq : int Freque... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Orchestrator:
"""Orchestrator. It is responsible for orchestrating the execution of all experiments and aggregate results."""
def __init__(self, settings, summary_freq=4):
"""Constructor Parameters ---------- settings : Settings The settings of the simulator summary_freq : int Frequency (in numbe... | the_stack_v2_python_sparse | icarus/orchestration.py | oascigil/IcarusEdgeSim | train | 7 |
d8e358028697cf503d7cafee7b67a629990a9e66 | [
"self.username = username\nself.first_name = first_name\nself.last_name = last_name\nself.application_id = application_id\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\nusername = dictionary.get('username')\nfirst_name = dictionary.get('firstName')\nlast_name = dic... | <|body_start_0|>
self.username = username
self.first_name = first_name
self.last_name = last_name
self.application_id = application_id
self.additional_properties = additional_properties
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
... | Implementation of the 'Add Customer Request' model. Request Structure For The Add Customer Endpoint and Add Testing Customer Endpoint Attributes: username (string): The customer’s username, assigned by the partner (a unique identifier), following these rules: minimum 6 characters maximum 255 characters any mix of upper... | AddCustomerRequest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddCustomerRequest:
"""Implementation of the 'Add Customer Request' model. Request Structure For The Add Customer Endpoint and Add Testing Customer Endpoint Attributes: username (string): The customer’s username, assigned by the partner (a unique identifier), following these rules: minimum 6 char... | stack_v2_sparse_classes_10k_train_005083 | 3,413 | permissive | [
{
"docstring": "Constructor for the AddCustomerRequest class",
"name": "__init__",
"signature": "def __init__(self, username=None, first_name=None, last_name=None, application_id=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: diction... | 2 | stack_v2_sparse_classes_30k_test_000045 | Implement the Python class `AddCustomerRequest` described below.
Class description:
Implementation of the 'Add Customer Request' model. Request Structure For The Add Customer Endpoint and Add Testing Customer Endpoint Attributes: username (string): The customer’s username, assigned by the partner (a unique identifier)... | Implement the Python class `AddCustomerRequest` described below.
Class description:
Implementation of the 'Add Customer Request' model. Request Structure For The Add Customer Endpoint and Add Testing Customer Endpoint Attributes: username (string): The customer’s username, assigned by the partner (a unique identifier)... | b2ab1ded435db75c78d42261f5e4acd2a3061487 | <|skeleton|>
class AddCustomerRequest:
"""Implementation of the 'Add Customer Request' model. Request Structure For The Add Customer Endpoint and Add Testing Customer Endpoint Attributes: username (string): The customer’s username, assigned by the partner (a unique identifier), following these rules: minimum 6 char... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AddCustomerRequest:
"""Implementation of the 'Add Customer Request' model. Request Structure For The Add Customer Endpoint and Add Testing Customer Endpoint Attributes: username (string): The customer’s username, assigned by the partner (a unique identifier), following these rules: minimum 6 characters maximu... | the_stack_v2_python_sparse | finicityapi/models/add_customer_request.py | monarchmoney/finicity-python | train | 0 |
4c800e9797b99902e085e8d2f0bc59be893c3afd | [
"print('deployment task data: %s' % validated_data)\naction = getattr(models.ApplicationDeploymentTask, validated_data.get('action', models.ApplicationDeploymentTask.HEALTH_CHECK))\nrequest = self.context.get('view').request\ndpk = self.context['view'].kwargs.get('deployment_pk')\ndpl = models.ApplicationDeployment... | <|body_start_0|>
print('deployment task data: %s' % validated_data)
action = getattr(models.ApplicationDeploymentTask, validated_data.get('action', models.ApplicationDeploymentTask.HEALTH_CHECK))
request = self.context.get('view').request
dpk = self.context['view'].kwargs.get('deployment... | DeploymentTaskSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeploymentTaskSerializer:
def create(self, validated_data):
"""Fire off a new task for the supplied action. Called automatically by the DRF following a POST request. :type validated_data: ``dict`` :param validated_data: Dict containing action the task should perform. Valid actions are `H... | stack_v2_sparse_classes_10k_train_005084 | 11,774 | no_license | [
{
"docstring": "Fire off a new task for the supplied action. Called automatically by the DRF following a POST request. :type validated_data: ``dict`` :param validated_data: Dict containing action the task should perform. Valid actions are `HEALTH_CHECK`, `DELETE`.",
"name": "create",
"signature": "def c... | 2 | stack_v2_sparse_classes_30k_train_003222 | Implement the Python class `DeploymentTaskSerializer` described below.
Class description:
Implement the DeploymentTaskSerializer class.
Method signatures and docstrings:
- def create(self, validated_data): Fire off a new task for the supplied action. Called automatically by the DRF following a POST request. :type val... | Implement the Python class `DeploymentTaskSerializer` described below.
Class description:
Implement the DeploymentTaskSerializer class.
Method signatures and docstrings:
- def create(self, validated_data): Fire off a new task for the supplied action. Called automatically by the DRF following a POST request. :type val... | a7fef384bc109fa9474e9b60d2d4a6357b5e2d49 | <|skeleton|>
class DeploymentTaskSerializer:
def create(self, validated_data):
"""Fire off a new task for the supplied action. Called automatically by the DRF following a POST request. :type validated_data: ``dict`` :param validated_data: Dict containing action the task should perform. Valid actions are `H... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DeploymentTaskSerializer:
def create(self, validated_data):
"""Fire off a new task for the supplied action. Called automatically by the DRF following a POST request. :type validated_data: ``dict`` :param validated_data: Dict containing action the task should perform. Valid actions are `HEALTH_CHECK`, ... | the_stack_v2_python_sparse | django-cloudlaunch/baselaunch/serializers.py | thobalose/cloudlaunch | train | 1 | |
83c0b70fcf56401f49bfb8cc4801d338245a861e | [
"parser = reqparse.RequestParser()\nparser.add_argument('name', type=str, required=True, help='This field cannot be left blank!')\nparser.add_argument('organization_ids', type=int, required=True, action='append')\nparser.add_argument('encrypted', type=int, required=False)\ndata = parser.parse_args()\nname = data['n... | <|body_start_0|>
parser = reqparse.RequestParser()
parser.add_argument('name', type=str, required=True, help='This field cannot be left blank!')
parser.add_argument('organization_ids', type=int, required=True, action='append')
parser.add_argument('encrypted', type=int, required=False)
... | Collaboration | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Collaboration:
def post(self):
"""create a new collaboration"""
<|body_0|>
def get(self, id=None):
"""collaboration or list of collaborations in case no id is provided"""
<|body_1|>
def patch(self, id):
"""update a collaboration"""
<|body... | stack_v2_sparse_classes_10k_train_005085 | 14,133 | permissive | [
{
"docstring": "create a new collaboration",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "collaboration or list of collaborations in case no id is provided",
"name": "get",
"signature": "def get(self, id=None)"
},
{
"docstring": "update a collaboration",
"... | 4 | stack_v2_sparse_classes_30k_train_005382 | Implement the Python class `Collaboration` described below.
Class description:
Implement the Collaboration class.
Method signatures and docstrings:
- def post(self): create a new collaboration
- def get(self, id=None): collaboration or list of collaborations in case no id is provided
- def patch(self, id): update a c... | Implement the Python class `Collaboration` described below.
Class description:
Implement the Collaboration class.
Method signatures and docstrings:
- def post(self): create a new collaboration
- def get(self, id=None): collaboration or list of collaborations in case no id is provided
- def patch(self, id): update a c... | a64827981db26b34dd1dcea1cb2282d03dd4545d | <|skeleton|>
class Collaboration:
def post(self):
"""create a new collaboration"""
<|body_0|>
def get(self, id=None):
"""collaboration or list of collaborations in case no id is provided"""
<|body_1|>
def patch(self, id):
"""update a collaboration"""
<|body... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Collaboration:
def post(self):
"""create a new collaboration"""
parser = reqparse.RequestParser()
parser.add_argument('name', type=str, required=True, help='This field cannot be left blank!')
parser.add_argument('organization_ids', type=int, required=True, action='append')
... | the_stack_v2_python_sparse | vantage6/server/resource/collaboration.py | mindrenee/vantage6-server | train | 0 | |
441a13a3359174644eab0deca73e2743880ee24e | [
"self._caffe = kwargs.pop('caffe')\nkwargs.setdefault('label_suffix', '')\nsuper(CompanyForm, self).__init__(*args, **kwargs)\nself.fields['name'].label = 'Nazwa'",
"name = self.cleaned_data['name']\nquery = Company.objects.filter(name=name, caffe=self._caffe)\nif query.exists():\n raise ValidationError(_('Naz... | <|body_start_0|>
self._caffe = kwargs.pop('caffe')
kwargs.setdefault('label_suffix', '')
super(CompanyForm, self).__init__(*args, **kwargs)
self.fields['name'].label = 'Nazwa'
<|end_body_0|>
<|body_start_1|>
name = self.cleaned_data['name']
query = Company.objects.filter... | Responsible for creating a Company. | CompanyForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompanyForm:
"""Responsible for creating a Company."""
def __init__(self, *args, **kwargs):
"""Initialize all Company's fields."""
<|body_0|>
def clean_name(self):
"""Check name field."""
<|body_1|>
def save(self, commit=True):
"""Override of... | stack_v2_sparse_classes_10k_train_005086 | 4,623 | permissive | [
{
"docstring": "Initialize all Company's fields.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Check name field.",
"name": "clean_name",
"signature": "def clean_name(self)"
},
{
"docstring": "Override of save method, to add Caffe rela... | 3 | stack_v2_sparse_classes_30k_train_002732 | Implement the Python class `CompanyForm` described below.
Class description:
Responsible for creating a Company.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize all Company's fields.
- def clean_name(self): Check name field.
- def save(self, commit=True): Override of save method, t... | Implement the Python class `CompanyForm` described below.
Class description:
Responsible for creating a Company.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize all Company's fields.
- def clean_name(self): Check name field.
- def save(self, commit=True): Override of save method, t... | cdb7f5edb29255c7e874eaa6231621063210a8b0 | <|skeleton|>
class CompanyForm:
"""Responsible for creating a Company."""
def __init__(self, *args, **kwargs):
"""Initialize all Company's fields."""
<|body_0|>
def clean_name(self):
"""Check name field."""
<|body_1|>
def save(self, commit=True):
"""Override of... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CompanyForm:
"""Responsible for creating a Company."""
def __init__(self, *args, **kwargs):
"""Initialize all Company's fields."""
self._caffe = kwargs.pop('caffe')
kwargs.setdefault('label_suffix', '')
super(CompanyForm, self).__init__(*args, **kwargs)
self.fields... | the_stack_v2_python_sparse | caffe/cash/forms.py | VirrageS/io-kawiarnie | train | 3 |
77b746b9e4c9476baeae6f71916a67c7136f0346 | [
"self.collection_summary = collection_summary\nself.collection_parent = collection_parent\nself.collection_item = collection_item",
"if dictionary is None:\n return None\ncollection_summary = awsecommerceservice.models.collection_summary.CollectionSummary.from_dictionary(dictionary.get('CollectionSummary')) if... | <|body_start_0|>
self.collection_summary = collection_summary
self.collection_parent = collection_parent
self.collection_item = collection_item
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
collection_summary = awsecommerceservice.models.collecti... | Implementation of the 'Collection' model. TODO: type model description here. Attributes: collection_summary (CollectionSummary): TODO: type description here. collection_parent (CollectionParent): TODO: type description here. collection_item (list of CollectionItem): TODO: type description here. | Collection | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Collection:
"""Implementation of the 'Collection' model. TODO: type model description here. Attributes: collection_summary (CollectionSummary): TODO: type description here. collection_parent (CollectionParent): TODO: type description here. collection_item (list of CollectionItem): TODO: type desc... | stack_v2_sparse_classes_10k_train_005087 | 2,741 | permissive | [
{
"docstring": "Constructor for the Collection class",
"name": "__init__",
"signature": "def __init__(self, collection_summary=None, collection_parent=None, collection_item=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary r... | 2 | stack_v2_sparse_classes_30k_test_000341 | Implement the Python class `Collection` described below.
Class description:
Implementation of the 'Collection' model. TODO: type model description here. Attributes: collection_summary (CollectionSummary): TODO: type description here. collection_parent (CollectionParent): TODO: type description here. collection_item (l... | Implement the Python class `Collection` described below.
Class description:
Implementation of the 'Collection' model. TODO: type model description here. Attributes: collection_summary (CollectionSummary): TODO: type description here. collection_parent (CollectionParent): TODO: type description here. collection_item (l... | 26ea1019115a1de3b1b37a4b830525e164ac55ce | <|skeleton|>
class Collection:
"""Implementation of the 'Collection' model. TODO: type model description here. Attributes: collection_summary (CollectionSummary): TODO: type description here. collection_parent (CollectionParent): TODO: type description here. collection_item (list of CollectionItem): TODO: type desc... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Collection:
"""Implementation of the 'Collection' model. TODO: type model description here. Attributes: collection_summary (CollectionSummary): TODO: type description here. collection_parent (CollectionParent): TODO: type description here. collection_item (list of CollectionItem): TODO: type description here.... | the_stack_v2_python_sparse | awsecommerceservice/models/collection.py | nidaizamir/Test-PY | train | 0 |
20bfdff837f91a53e7a3e0f6b4adf174d2d99eba | [
"installed = dpkg.installed()\nopenmpi = ('openmpi-bin', 'libopenmpi-dev')\nmissing = [pkg for pkg in openmpi if pkg not in installed]\nif not missing:\n yield (OpenMPI.flavor, openmpi)\nmpich = ('mpich', 'libmpich-dev')\nmissing = [pkg for pkg in mpich if pkg not in installed]\nif not missing:\n yield (MPICH... | <|body_start_0|>
installed = dpkg.installed()
openmpi = ('openmpi-bin', 'libopenmpi-dev')
missing = [pkg for pkg in openmpi if pkg not in installed]
if not missing:
yield (OpenMPI.flavor, openmpi)
mpich = ('mpich', 'libmpich-dev')
missing = [pkg for pkg in mpi... | The package manager for MPI packages | MPI | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MPI:
"""The package manager for MPI packages"""
def dpkgAlternatives(cls, dpkg):
"""Identify the default implementation of MPI on dpkg machines"""
<|body_0|>
def dpkgPackages(cls, packager):
"""Provide alternative compatible implementations of python on dpkg mach... | stack_v2_sparse_classes_10k_train_005088 | 10,213 | permissive | [
{
"docstring": "Identify the default implementation of MPI on dpkg machines",
"name": "dpkgAlternatives",
"signature": "def dpkgAlternatives(cls, dpkg)"
},
{
"docstring": "Provide alternative compatible implementations of python on dpkg machines, starting with the package the user has selected a... | 3 | null | Implement the Python class `MPI` described below.
Class description:
The package manager for MPI packages
Method signatures and docstrings:
- def dpkgAlternatives(cls, dpkg): Identify the default implementation of MPI on dpkg machines
- def dpkgPackages(cls, packager): Provide alternative compatible implementations o... | Implement the Python class `MPI` described below.
Class description:
The package manager for MPI packages
Method signatures and docstrings:
- def dpkgAlternatives(cls, dpkg): Identify the default implementation of MPI on dpkg machines
- def dpkgPackages(cls, packager): Provide alternative compatible implementations o... | d741c44ffb3e9e1f726bf492202ac8738bb4aa1c | <|skeleton|>
class MPI:
"""The package manager for MPI packages"""
def dpkgAlternatives(cls, dpkg):
"""Identify the default implementation of MPI on dpkg machines"""
<|body_0|>
def dpkgPackages(cls, packager):
"""Provide alternative compatible implementations of python on dpkg mach... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MPI:
"""The package manager for MPI packages"""
def dpkgAlternatives(cls, dpkg):
"""Identify the default implementation of MPI on dpkg machines"""
installed = dpkg.installed()
openmpi = ('openmpi-bin', 'libopenmpi-dev')
missing = [pkg for pkg in openmpi if pkg not in insta... | the_stack_v2_python_sparse | packages/pyre/externals/MPI.py | pyre/pyre | train | 27 |
4adce9c92d97b54309dca1911899980e9df91dbe | [
"function = LegacyFunctionSpecification()\nfunction.addParameter('input', dtype='int32', direction=function.IN, description='Typical input parameter, the argument is passed by value to the function.')\nfunction.addParameter('output', dtype='float64', direction=function.OUT, description='Typical output parameter, th... | <|body_start_0|>
function = LegacyFunctionSpecification()
function.addParameter('input', dtype='int32', direction=function.IN, description='Typical input parameter, the argument is passed by value to the function.')
function.addParameter('output', dtype='float64', direction=function.OUT, descrip... | ExampleInterface | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExampleInterface:
def example_function():
"""Example template for the other functions defined in this specification. All functions should follow this example.."""
<|body_0|>
def get_example_parameter():
"""Retrieve the current value of the parameter. Note, values can... | stack_v2_sparse_classes_10k_train_005089 | 3,439 | permissive | [
{
"docstring": "Example template for the other functions defined in this specification. All functions should follow this example..",
"name": "example_function",
"signature": "def example_function()"
},
{
"docstring": "Retrieve the current value of the parameter. Note, values can be any of the su... | 4 | stack_v2_sparse_classes_30k_train_006711 | Implement the Python class `ExampleInterface` described below.
Class description:
Implement the ExampleInterface class.
Method signatures and docstrings:
- def example_function(): Example template for the other functions defined in this specification. All functions should follow this example..
- def get_example_param... | Implement the Python class `ExampleInterface` described below.
Class description:
Implement the ExampleInterface class.
Method signatures and docstrings:
- def example_function(): Example template for the other functions defined in this specification. All functions should follow this example..
- def get_example_param... | b57c1e2fda1457d5025307be105c2aa59b19b574 | <|skeleton|>
class ExampleInterface:
def example_function():
"""Example template for the other functions defined in this specification. All functions should follow this example.."""
<|body_0|>
def get_example_parameter():
"""Retrieve the current value of the parameter. Note, values can... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ExampleInterface:
def example_function():
"""Example template for the other functions defined in this specification. All functions should follow this example.."""
function = LegacyFunctionSpecification()
function.addParameter('input', dtype='int32', direction=function.IN, description='... | the_stack_v2_python_sparse | src/amuse/community/interface/example.py | amusecode/amuse | train | 158 | |
7e2642811b17392adf07f375f495fd57aeb24639 | [
"super().__init__()\nself.last_batch = data.get('last_batch', None)\nself.batch_size: Optional[int] = data.get('batch_size')\nself.dataset: Optional[Dataset] = None\nif data.get('dataset'):\n self.set_dataset(data.get('dataset', {}))\nself.transform: OrderedDict = OrderedDict()\nif data.get('transform'):\n fo... | <|body_start_0|>
super().__init__()
self.last_batch = data.get('last_batch', None)
self.batch_size: Optional[int] = data.get('batch_size')
self.dataset: Optional[Dataset] = None
if data.get('dataset'):
self.set_dataset(data.get('dataset', {}))
self.transform: ... | Configuration Dataloader class. | Dataloader | [
"MIT",
"Intel",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dataloader:
"""Configuration Dataloader class."""
def __init__(self, data: Dict[str, Any]={}) -> None:
"""Initialize Configuration Dataloader class."""
<|body_0|>
def set_dataset(self, dataset_data: Dict[str, Any]) -> None:
"""Set dataset for dataloader."""
... | stack_v2_sparse_classes_10k_train_005090 | 4,560 | permissive | [
{
"docstring": "Initialize Configuration Dataloader class.",
"name": "__init__",
"signature": "def __init__(self, data: Dict[str, Any]={}) -> None"
},
{
"docstring": "Set dataset for dataloader.",
"name": "set_dataset",
"signature": "def set_dataset(self, dataset_data: Dict[str, Any]) ->... | 3 | stack_v2_sparse_classes_30k_train_000325 | Implement the Python class `Dataloader` described below.
Class description:
Configuration Dataloader class.
Method signatures and docstrings:
- def __init__(self, data: Dict[str, Any]={}) -> None: Initialize Configuration Dataloader class.
- def set_dataset(self, dataset_data: Dict[str, Any]) -> None: Set dataset for... | Implement the Python class `Dataloader` described below.
Class description:
Configuration Dataloader class.
Method signatures and docstrings:
- def __init__(self, data: Dict[str, Any]={}) -> None: Initialize Configuration Dataloader class.
- def set_dataset(self, dataset_data: Dict[str, Any]) -> None: Set dataset for... | 3976edc4215398e69ce0213f87ec295f5dc96e0e | <|skeleton|>
class Dataloader:
"""Configuration Dataloader class."""
def __init__(self, data: Dict[str, Any]={}) -> None:
"""Initialize Configuration Dataloader class."""
<|body_0|>
def set_dataset(self, dataset_data: Dict[str, Any]) -> None:
"""Set dataset for dataloader."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Dataloader:
"""Configuration Dataloader class."""
def __init__(self, data: Dict[str, Any]={}) -> None:
"""Initialize Configuration Dataloader class."""
super().__init__()
self.last_batch = data.get('last_batch', None)
self.batch_size: Optional[int] = data.get('batch_size')... | the_stack_v2_python_sparse | neural_compressor/ux/utils/workload/dataloader.py | Skp80/neural-compressor | train | 0 |
ef42eda96574711369ea418e2bb8fbcf69f8b620 | [
"Gtk.Grid.__init__(self)\nself._position = position\nself._displayedChar = Gtk.Button()\nself._displayedChar.set_size_request(30, 40)\nself._displayedChar.add(Gtk.Label())\nself.attach(self._displayedChar, 0, 0, 2, 3)\nself._displayedChar.connect('clicked', self._onCellClicked)\nself.dot7 = BrlDot(7)\nself.dot8 = B... | <|body_start_0|>
Gtk.Grid.__init__(self)
self._position = position
self._displayedChar = Gtk.Button()
self._displayedChar.set_size_request(30, 40)
self._displayedChar.add(Gtk.Label())
self.attach(self._displayedChar, 0, 0, 2, 3)
self._displayedChar.connect('clicke... | A single graphical braille cell with cursor routing capability. | BrlCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BrlCell:
"""A single graphical braille cell with cursor routing capability."""
def __init__(self, position):
"""Create a new BrlCell. Arguments: - position: The location of the cell with respect to the monitor."""
<|body_0|>
def _onCellClicked(self, widget):
"""C... | stack_v2_sparse_classes_10k_train_005091 | 7,254 | no_license | [
{
"docstring": "Create a new BrlCell. Arguments: - position: The location of the cell with respect to the monitor.",
"name": "__init__",
"signature": "def __init__(self, position)"
},
{
"docstring": "Callback for the 'clicked' signal on the push button. Synthesizes a fake brlapi command to route... | 4 | stack_v2_sparse_classes_30k_train_000176 | Implement the Python class `BrlCell` described below.
Class description:
A single graphical braille cell with cursor routing capability.
Method signatures and docstrings:
- def __init__(self, position): Create a new BrlCell. Arguments: - position: The location of the cell with respect to the monitor.
- def _onCellCli... | Implement the Python class `BrlCell` described below.
Class description:
A single graphical braille cell with cursor routing capability.
Method signatures and docstrings:
- def __init__(self, position): Create a new BrlCell. Arguments: - position: The location of the cell with respect to the monitor.
- def _onCellCli... | 6976d7e1d8af45b1432cbf4f1461076ca04349e0 | <|skeleton|>
class BrlCell:
"""A single graphical braille cell with cursor routing capability."""
def __init__(self, position):
"""Create a new BrlCell. Arguments: - position: The location of the cell with respect to the monitor."""
<|body_0|>
def _onCellClicked(self, widget):
"""C... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BrlCell:
"""A single graphical braille cell with cursor routing capability."""
def __init__(self, position):
"""Create a new BrlCell. Arguments: - position: The location of the cell with respect to the monitor."""
Gtk.Grid.__init__(self)
self._position = position
self._dis... | the_stack_v2_python_sparse | rootfs/usr/lib64/python2.7/site-packages/orca/brlmon.py | outstanding-mjy/make_rootfs | train | 0 |
3832d334c7325c4ce003717b4629333256828956 | [
"def memoize(i):\n if i == 0:\n return 1\n if cache[i] != 0:\n return cache[i]\n cache[i] = 1\n for j in range(i):\n if nums[i] > nums[j]:\n cache[i] = max(cache[i], memoize(j) + 1)\n return cache[i]\nn = len(nums)\nif n <= 0:\n return 0\ncache = [0] * n\ncache[0] =... | <|body_start_0|>
def memoize(i):
if i == 0:
return 1
if cache[i] != 0:
return cache[i]
cache[i] = 1
for j in range(i):
if nums[i] > nums[j]:
cache[i] = max(cache[i], memoize(j) + 1)
re... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
"""带备忘录的递归算法:自顶向下 递归+动态规划+二分:https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/chao-xiang-xi-tu-jie-di-gui-dong-tai-gui-hua-er-fe/"""
<|body_0|>
def lengthOfLIS1(self, nums: List[int]) -> int:
... | stack_v2_sparse_classes_10k_train_005092 | 2,863 | permissive | [
{
"docstring": "带备忘录的递归算法:自顶向下 递归+动态规划+二分:https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/chao-xiang-xi-tu-jie-di-gui-dong-tai-gui-hua-er-fe/",
"name": "lengthOfLIS",
"signature": "def lengthOfLIS(self, nums: List[int]) -> int"
},
{
"docstring": "状态转移方程:dp[i] 的值代表 nums 前... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums: List[int]) -> int: 带备忘录的递归算法:自顶向下 递归+动态规划+二分:https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/chao-xiang-xi-tu-jie-di-gui-dong... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums: List[int]) -> int: 带备忘录的递归算法:自顶向下 递归+动态规划+二分:https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/chao-xiang-xi-tu-jie-di-gui-dong... | e8a1c6cae6547cbcb6e8494be6df685f3e7c837c | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
"""带备忘录的递归算法:自顶向下 递归+动态规划+二分:https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/chao-xiang-xi-tu-jie-di-gui-dong-tai-gui-hua-er-fe/"""
<|body_0|>
def lengthOfLIS1(self, nums: List[int]) -> int:
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
"""带备忘录的递归算法:自顶向下 递归+动态规划+二分:https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/chao-xiang-xi-tu-jie-di-gui-dong-tai-gui-hua-er-fe/"""
def memoize(i):
if i == 0:
return 1
if c... | the_stack_v2_python_sparse | 300-longest-increasing-subsequence.py | yuenliou/leetcode | train | 0 | |
2a06cf1341322e2c8efa87523974debe7f763dd1 | [
"ans = 0\nn = len(s)\n\ndef count(l, r):\n cnt = 0\n while l >= 0 and r < n and (s[l] == s[r]):\n cnt += 1\n l -= 1\n r += 1\n return cnt\nfor i in range(n):\n ans += count(i, i)\n ans += count(i - 1, i)\nreturn ans",
"n, res = (len(s), 0)\ndp = [[False for _ in range(n)] for _... | <|body_start_0|>
ans = 0
n = len(s)
def count(l, r):
cnt = 0
while l >= 0 and r < n and (s[l] == s[r]):
cnt += 1
l -= 1
r += 1
return cnt
for i in range(n):
ans += count(i, i)
ans... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countSubstrings(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def countSubstringsDP(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ans = 0
n = len(s)
def count(l, r):
... | stack_v2_sparse_classes_10k_train_005093 | 1,573 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "countSubstrings",
"signature": "def countSubstrings(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "countSubstringsDP",
"signature": "def countSubstringsDP(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countSubstrings(self, s): :type s: str :rtype: int
- def countSubstringsDP(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countSubstrings(self, s): :type s: str :rtype: int
- def countSubstringsDP(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def countSubstrings(self, s):... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def countSubstrings(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def countSubstringsDP(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def countSubstrings(self, s):
""":type s: str :rtype: int"""
ans = 0
n = len(s)
def count(l, r):
cnt = 0
while l >= 0 and r < n and (s[l] == s[r]):
cnt += 1
l -= 1
r += 1
return cnt
... | the_stack_v2_python_sparse | P/PalindromicSubstrings.py | bssrdf/pyleet | train | 2 | |
be1739099bff7d7a5fb7a95f013e453d0c705d3f | [
"n = len(nums)\nif n < 2:\n return n\ndp = [1 for _ in range(n)]\nfor i in range(1, n):\n for j in range(i):\n if j < i and nums[j] < nums[i]:\n dp[i] = max(dp[j] + 1, dp[i])\nres = max(dp)\nreturn res",
"n = len(nums)\nif n < 2:\n return n\ncell = []\nfor num in nums:\n if not cell ... | <|body_start_0|>
n = len(nums)
if n < 2:
return n
dp = [1 for _ in range(n)]
for i in range(1, n):
for j in range(i):
if j < i and nums[j] < nums[i]:
dp[i] = max(dp[j] + 1, dp[i])
res = max(dp)
return res
<|end_b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums):
"""固定i 看[0,i]区间 如果nums[i]>nums[j],dp[i] = max(dp[i], dp[i] + 1) 取最大 :param nums: list :return: int"""
<|body_0|>
def lengthOfLIS_v2(self, nums):
"""利用贪心算法+二分查找 整体思路, 创建一个cell的列表,用于保存最长上升子序列 遍历数组 如果当前元素大于最后一个位置的元素,则插入cell 否则,利用二分... | stack_v2_sparse_classes_10k_train_005094 | 2,782 | no_license | [
{
"docstring": "固定i 看[0,i]区间 如果nums[i]>nums[j],dp[i] = max(dp[i], dp[i] + 1) 取最大 :param nums: list :return: int",
"name": "lengthOfLIS",
"signature": "def lengthOfLIS(self, nums)"
},
{
"docstring": "利用贪心算法+二分查找 整体思路, 创建一个cell的列表,用于保存最长上升子序列 遍历数组 如果当前元素大于最后一个位置的元素,则插入cell 否则,利用二分查找,将当前元素插入cell中,大... | 2 | stack_v2_sparse_classes_30k_train_004101 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums): 固定i 看[0,i]区间 如果nums[i]>nums[j],dp[i] = max(dp[i], dp[i] + 1) 取最大 :param nums: list :return: int
- def lengthOfLIS_v2(self, nums): 利用贪心算法+二分查找 整体思路, 创... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums): 固定i 看[0,i]区间 如果nums[i]>nums[j],dp[i] = max(dp[i], dp[i] + 1) 取最大 :param nums: list :return: int
- def lengthOfLIS_v2(self, nums): 利用贪心算法+二分查找 整体思路, 创... | f1bbd6b3197cd9ac4f0d35a37539c11b02272065 | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums):
"""固定i 看[0,i]区间 如果nums[i]>nums[j],dp[i] = max(dp[i], dp[i] + 1) 取最大 :param nums: list :return: int"""
<|body_0|>
def lengthOfLIS_v2(self, nums):
"""利用贪心算法+二分查找 整体思路, 创建一个cell的列表,用于保存最长上升子序列 遍历数组 如果当前元素大于最后一个位置的元素,则插入cell 否则,利用二分... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLIS(self, nums):
"""固定i 看[0,i]区间 如果nums[i]>nums[j],dp[i] = max(dp[i], dp[i] + 1) 取最大 :param nums: list :return: int"""
n = len(nums)
if n < 2:
return n
dp = [1 for _ in range(n)]
for i in range(1, n):
for j in range(i):
... | the_stack_v2_python_sparse | leetcode/动态规划/300. 最长上升子序列/lengthOfLIS.py | guohaoyuan/algorithms-for-work | train | 2 | |
f7c0bbb599f37d27466eb0c58d11d34cd7dd0d74 | [
"super(RemoteMonitor, self).__init__()\nif requests is None:\n raise ImportError(\"RemoteMonitor requires the 'requests' library.Run pip install requests.\")\nself.root = root\nself.path = path\nself.field = field\nself.headers = headers\nself.monitors = monitors\nself.send_as_json = send_as_json",
"monitors =... | <|body_start_0|>
super(RemoteMonitor, self).__init__()
if requests is None:
raise ImportError("RemoteMonitor requires the 'requests' library.Run pip install requests.")
self.root = root
self.path = path
self.field = field
self.headers = headers
self.mo... | Callback to stream training events to a server with the same interface as Keras RemoteMonitor. | RemoteMonitor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RemoteMonitor:
"""Callback to stream training events to a server with the same interface as Keras RemoteMonitor."""
def __init__(self, root='http://localhost:9000', path='/publish/epoch/end/', field='data', headers=None, send_as_json=False, monitors=None):
"""Constructor Arguments: r... | stack_v2_sparse_classes_10k_train_005095 | 2,291 | permissive | [
{
"docstring": "Constructor Arguments: root (str): Root server url path (str): Relative path to root to post events field (str): Json field of post data headers (str): Http headers send_as_json (bool): If false sends data as plain json. Otherwise sends as json. monitors (list): List of monitors names to include... | 2 | stack_v2_sparse_classes_30k_train_005755 | Implement the Python class `RemoteMonitor` described below.
Class description:
Callback to stream training events to a server with the same interface as Keras RemoteMonitor.
Method signatures and docstrings:
- def __init__(self, root='http://localhost:9000', path='/publish/epoch/end/', field='data', headers=None, sen... | Implement the Python class `RemoteMonitor` described below.
Class description:
Callback to stream training events to a server with the same interface as Keras RemoteMonitor.
Method signatures and docstrings:
- def __init__(self, root='http://localhost:9000', path='/publish/epoch/end/', field='data', headers=None, sen... | d1440b7a9c3ab2c1d3abbb282abb9ee1ea240797 | <|skeleton|>
class RemoteMonitor:
"""Callback to stream training events to a server with the same interface as Keras RemoteMonitor."""
def __init__(self, root='http://localhost:9000', path='/publish/epoch/end/', field='data', headers=None, send_as_json=False, monitors=None):
"""Constructor Arguments: r... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RemoteMonitor:
"""Callback to stream training events to a server with the same interface as Keras RemoteMonitor."""
def __init__(self, root='http://localhost:9000', path='/publish/epoch/end/', field='data', headers=None, send_as_json=False, monitors=None):
"""Constructor Arguments: root (str): Ro... | the_stack_v2_python_sparse | torchero/callbacks/remote.py | juancruzsosa/torchero | train | 10 |
86ef44fdca4a098f36ad5cba29a2886a9cee8e54 | [
"copied = matrix.copy()\nrows = set()\ncolumns = set()\nfor i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if matrix[i][j] == 0:\n rows.add(i)\n columns.add(j)\nfor i in range(len(copied)):\n for j in range(len(copied[0])):\n if i in rows or j in columns:\n ... | <|body_start_0|>
copied = matrix.copy()
rows = set()
columns = set()
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == 0:
rows.add(i)
columns.add(j)
for i in range(len(copied)):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""Purpose: Given an m x n integer matrix, sets its entire row and column to 0's if element is 0. Returns the matrix."""
<|body_0|>
def setZeroes1(self, matrix):
"""Does not return anything, modifies mat... | stack_v2_sparse_classes_10k_train_005096 | 1,424 | no_license | [
{
"docstring": "Purpose: Given an m x n integer matrix, sets its entire row and column to 0's if element is 0. Returns the matrix.",
"name": "setZeroes",
"signature": "def setZeroes(self, matrix: List[List[int]]) -> None"
},
{
"docstring": "Does not return anything, modifies matrix in-place inst... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes(self, matrix: List[List[int]]) -> None: Purpose: Given an m x n integer matrix, sets its entire row and column to 0's if element is 0. Returns the matrix.
- def set... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes(self, matrix: List[List[int]]) -> None: Purpose: Given an m x n integer matrix, sets its entire row and column to 0's if element is 0. Returns the matrix.
- def set... | 95a86cbbca28d0c0f6d72d28a2f1cb5a86327934 | <|skeleton|>
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""Purpose: Given an m x n integer matrix, sets its entire row and column to 0's if element is 0. Returns the matrix."""
<|body_0|>
def setZeroes1(self, matrix):
"""Does not return anything, modifies mat... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""Purpose: Given an m x n integer matrix, sets its entire row and column to 0's if element is 0. Returns the matrix."""
copied = matrix.copy()
rows = set()
columns = set()
for i in range(len(matrix)):
... | the_stack_v2_python_sparse | setMatrixZeroes.py | tashakim/puzzles_python | train | 8 | |
cbda420147a92a0a5a22e19377485dba57afb32b | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Proto file describing the GoogleAdsService. Service to fetch data and metrics across resources. | GoogleAdsServiceServicer | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoogleAdsServiceServicer:
"""Proto file describing the GoogleAdsService. Service to fetch data and metrics across resources."""
def Search(self, request, context):
"""Returns all rows that match the search query."""
<|body_0|>
def Mutate(self, request, context):
... | stack_v2_sparse_classes_10k_train_005097 | 5,425 | permissive | [
{
"docstring": "Returns all rows that match the search query.",
"name": "Search",
"signature": "def Search(self, request, context)"
},
{
"docstring": "Creates, updates, or removes resources. This method supports atomic transactions with multiple types of resources. For example, you can atomicall... | 2 | stack_v2_sparse_classes_30k_train_006946 | Implement the Python class `GoogleAdsServiceServicer` described below.
Class description:
Proto file describing the GoogleAdsService. Service to fetch data and metrics across resources.
Method signatures and docstrings:
- def Search(self, request, context): Returns all rows that match the search query.
- def Mutate(s... | Implement the Python class `GoogleAdsServiceServicer` described below.
Class description:
Proto file describing the GoogleAdsService. Service to fetch data and metrics across resources.
Method signatures and docstrings:
- def Search(self, request, context): Returns all rows that match the search query.
- def Mutate(s... | 0fc8a7dbf31d9e8e2a4364df93bec5f6b7edd50a | <|skeleton|>
class GoogleAdsServiceServicer:
"""Proto file describing the GoogleAdsService. Service to fetch data and metrics across resources."""
def Search(self, request, context):
"""Returns all rows that match the search query."""
<|body_0|>
def Mutate(self, request, context):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GoogleAdsServiceServicer:
"""Proto file describing the GoogleAdsService. Service to fetch data and metrics across resources."""
def Search(self, request, context):
"""Returns all rows that match the search query."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_detai... | the_stack_v2_python_sparse | google/ads/google_ads/v1/proto/services/google_ads_service_pb2_grpc.py | juanmacugat/google-ads-python | train | 1 |
6de0436abd47ba94fac9bb05fdbe77550bf7c91f | [
"self.column_names: List[str] = kargs.pop('column_names')\nsuper().__init__(*args, **kargs)\nself.set_fields_from_dict(['item_column', 'confirm_items', 'send_confirmation', 'track_read'])\nitem_column_name = self.fields['item_column'].initial\nif item_column_name is None:\n item_column_name = next((cname for cna... | <|body_start_0|>
self.column_names: List[str] = kargs.pop('column_names')
super().__init__(*args, **kargs)
self.set_fields_from_dict(['item_column', 'confirm_items', 'send_confirmation', 'track_read'])
item_column_name = self.fields['item_column'].initial
if item_column_name is N... | Form to edit the Send Email action. | EmailActionForm | [
"MIT",
"LGPL-2.0-or-later",
"Python-2.0",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailActionForm:
"""Form to edit the Send Email action."""
def __init__(self, *args, **kargs):
"""Store column names and adjust initial values."""
<|body_0|>
def clean(self):
"""Verify email values."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_005098 | 20,237 | permissive | [
{
"docstring": "Store column names and adjust initial values.",
"name": "__init__",
"signature": "def __init__(self, *args, **kargs)"
},
{
"docstring": "Verify email values.",
"name": "clean",
"signature": "def clean(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004354 | Implement the Python class `EmailActionForm` described below.
Class description:
Form to edit the Send Email action.
Method signatures and docstrings:
- def __init__(self, *args, **kargs): Store column names and adjust initial values.
- def clean(self): Verify email values. | Implement the Python class `EmailActionForm` described below.
Class description:
Form to edit the Send Email action.
Method signatures and docstrings:
- def __init__(self, *args, **kargs): Store column names and adjust initial values.
- def clean(self): Verify email values.
<|skeleton|>
class EmailActionForm:
""... | 5473e9faa24c71a2a1102d47ebc2cbf27608e42a | <|skeleton|>
class EmailActionForm:
"""Form to edit the Send Email action."""
def __init__(self, *args, **kargs):
"""Store column names and adjust initial values."""
<|body_0|>
def clean(self):
"""Verify email values."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EmailActionForm:
"""Form to edit the Send Email action."""
def __init__(self, *args, **kargs):
"""Store column names and adjust initial values."""
self.column_names: List[str] = kargs.pop('column_names')
super().__init__(*args, **kargs)
self.set_fields_from_dict(['item_col... | the_stack_v2_python_sparse | ontask/action/forms/run.py | LucasFranciscoCorreia/ontask_b | train | 0 |
03edf1a97d3ec2e95b7a9500a951150bf5cbaf95 | [
"input_json = request.data\noutput_json = dict(zip(['AvailabilityDetails', 'AuthenticationDetails', 'SessionDetails', 'Payload'], [input_json['AvailabilityDetails'], input_json['AuthenticationDetails'], input_json['SessionDetails'], None]))\ntry:\n json_params = input_json['APIParams']\n json_params['profile_... | <|body_start_0|>
input_json = request.data
output_json = dict(zip(['AvailabilityDetails', 'AuthenticationDetails', 'SessionDetails', 'Payload'], [input_json['AvailabilityDetails'], input_json['AuthenticationDetails'], input_json['SessionDetails'], None]))
try:
json_params = input_jso... | This API will create a notification | PopulateMyNotificationsAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PopulateMyNotificationsAPI:
"""This API will create a notification"""
def post(self, request):
"""Post function to crete a notification"""
<|body_0|>
def populate_my_notifications_json(self, request):
"""This API will create a notification :param request: { 'prof... | stack_v2_sparse_classes_10k_train_005099 | 3,021 | no_license | [
{
"docstring": "Post function to crete a notification",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "This API will create a notification :param request: { 'profile_id':277 } :return",
"name": "populate_my_notifications_json",
"signature": "def populate_my_not... | 2 | stack_v2_sparse_classes_30k_test_000317 | Implement the Python class `PopulateMyNotificationsAPI` described below.
Class description:
This API will create a notification
Method signatures and docstrings:
- def post(self, request): Post function to crete a notification
- def populate_my_notifications_json(self, request): This API will create a notification :p... | Implement the Python class `PopulateMyNotificationsAPI` described below.
Class description:
This API will create a notification
Method signatures and docstrings:
- def post(self, request): Post function to crete a notification
- def populate_my_notifications_json(self, request): This API will create a notification :p... | 36eb9931f330e64902354c6fc471be2adf4b7049 | <|skeleton|>
class PopulateMyNotificationsAPI:
"""This API will create a notification"""
def post(self, request):
"""Post function to crete a notification"""
<|body_0|>
def populate_my_notifications_json(self, request):
"""This API will create a notification :param request: { 'prof... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PopulateMyNotificationsAPI:
"""This API will create a notification"""
def post(self, request):
"""Post function to crete a notification"""
input_json = request.data
output_json = dict(zip(['AvailabilityDetails', 'AuthenticationDetails', 'SessionDetails', 'Payload'], [input_json['A... | the_stack_v2_python_sparse | Generic/common/notifications_new/api/populate_my_notifications/views_populate_my_notifications.py | archiemb303/common_backend_django | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.