blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1fe50aeaa3d6d7f9e13f2c75e450379338a40096 | [
"super(LibraryPackage, self).__init__(name, system, repository)\nself._libraries = []\nself._headers = []\nself._flags = []\nif libraries is not None:\n self._libraries = ['-l' + library for library in libraries]\nif headers is not None:\n self._headers = headers\nif flags is not None:\n self._flags = flag... | <|body_start_0|>
super(LibraryPackage, self).__init__(name, system, repository)
self._libraries = []
self._headers = []
self._flags = []
if libraries is not None:
self._libraries = ['-l' + library for library in libraries]
if headers is not None:
s... | Packages that are global system commands :param _libraries: list of libraries :param _headers: list of headers with extension :param _flags: list of flags :param _config: config command | LibraryPackage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LibraryPackage:
"""Packages that are global system commands :param _libraries: list of libraries :param _headers: list of headers with extension :param _flags: list of flags :param _config: config command"""
def __init__(self, name, system, repository, libraries=None, headers=None, flags=Non... | stack_v2_sparse_classes_36k_train_002500 | 2,725 | permissive | [
{
"docstring": "Construct the package with a *name* and the *system* installation information. This package is a *library* with *headers* and *flags* OR a *config* command with *headers* to find the library and flags. :param string name: name of this package. :param system: class that manages system commands :t... | 2 | stack_v2_sparse_classes_30k_train_009617 | Implement the Python class `LibraryPackage` described below.
Class description:
Packages that are global system commands :param _libraries: list of libraries :param _headers: list of headers with extension :param _flags: list of flags :param _config: config command
Method signatures and docstrings:
- def __init__(sel... | Implement the Python class `LibraryPackage` described below.
Class description:
Packages that are global system commands :param _libraries: list of libraries :param _headers: list of headers with extension :param _flags: list of flags :param _config: config command
Method signatures and docstrings:
- def __init__(sel... | 442c7bca2f921892ecf9eb3ff6821e2a9da7b156 | <|skeleton|>
class LibraryPackage:
"""Packages that are global system commands :param _libraries: list of libraries :param _headers: list of headers with extension :param _flags: list of flags :param _config: config command"""
def __init__(self, name, system, repository, libraries=None, headers=None, flags=Non... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LibraryPackage:
"""Packages that are global system commands :param _libraries: list of libraries :param _headers: list of headers with extension :param _flags: list of flags :param _config: config command"""
def __init__(self, name, system, repository, libraries=None, headers=None, flags=None, config=Non... | the_stack_v2_python_sparse | nusoft/package/library.py | pgjones/nusoft | train | 1 |
932be9f87edbce57a91b7f657f77d1882b42789a | [
"home = []\nhome.append(Bed('Bedroom'))\nself.assertEqual(home[0].room, 'Bedroom')\nself.assertEqual(home[0].name, 'Bed')",
"home = []\nhome.append(Bed('Bedroom'))\nhome.append(Sofa('Living Room'))\nhome.append(Table('Living Room'))\nself.assertEqual(len(home), 3)\nself.assertEqual(len(map_the_home(home)), 2)"
] | <|body_start_0|>
home = []
home.append(Bed('Bedroom'))
self.assertEqual(home[0].room, 'Bedroom')
self.assertEqual(home[0].name, 'Bed')
<|end_body_0|>
<|body_start_1|>
home = []
home.append(Bed('Bedroom'))
home.append(Sofa('Living Room'))
home.append(Table... | Test | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test:
def test_append(self):
"""Test the addition of a furnishing to home and check the attributes"""
<|body_0|>
def test_map_the_home(self):
"""Test the number of objects added to home, then test to see if the number of room groups is correct after calling map_the_h... | stack_v2_sparse_classes_36k_train_002501 | 981 | no_license | [
{
"docstring": "Test the addition of a furnishing to home and check the attributes",
"name": "test_append",
"signature": "def test_append(self)"
},
{
"docstring": "Test the number of objects added to home, then test to see if the number of room groups is correct after calling map_the_home",
... | 2 | null | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def test_append(self): Test the addition of a furnishing to home and check the attributes
- def test_map_the_home(self): Test the number of objects added to home, then test to see if the... | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def test_append(self): Test the addition of a furnishing to home and check the attributes
- def test_map_the_home(self): Test the number of objects added to home, then test to see if the... | eff582478058db318e1b9352ce26c5afa8f21231 | <|skeleton|>
class Test:
def test_append(self):
"""Test the addition of a furnishing to home and check the attributes"""
<|body_0|>
def test_map_the_home(self):
"""Test the number of objects added to home, then test to see if the number of room groups is correct after calling map_the_h... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test:
def test_append(self):
"""Test the addition of a furnishing to home and check the attributes"""
home = []
home.append(Bed('Bedroom'))
self.assertEqual(home[0].room, 'Bedroom')
self.assertEqual(home[0].name, 'Bed')
def test_map_the_home(self):
"""Test ... | the_stack_v2_python_sparse | python/Python3_Homework07/src/test_furnishings.py | joelgarzatx/portfolio | train | 0 | |
205748b941dfe8bdaa322345a11ceb5aa0b242b0 | [
"super().__init__(parent=parent)\nself.setTitle('Pulse intensities (SA3)')\nself.setLabel('left', 'Intensity (arb.)')\nself.setLabel('bottom', 'Pulse index')\nself._plot = self.plotCurve(pen=FColor.mkPen('g'))",
"y = data['xgm_intensity']\nx = np.arange(len(y))\nself._plot.setData(x, y)"
] | <|body_start_0|>
super().__init__(parent=parent)
self.setTitle('Pulse intensities (SA3)')
self.setLabel('left', 'Intensity (arb.)')
self.setLabel('bottom', 'Pulse index')
self._plot = self.plotCurve(pen=FColor.mkPen('g'))
<|end_body_0|>
<|body_start_1|>
y = data['xgm_int... | XasTimXgmPulsePlot class. Visualize XGM intensity in the current train. | XasTimXgmPulsePlot | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XasTimXgmPulsePlot:
"""XasTimXgmPulsePlot class. Visualize XGM intensity in the current train."""
def __init__(self, *, parent=None):
"""Initialization."""
<|body_0|>
def updateF(self, data):
"""Override."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_002502 | 13,999 | permissive | [
{
"docstring": "Initialization.",
"name": "__init__",
"signature": "def __init__(self, *, parent=None)"
},
{
"docstring": "Override.",
"name": "updateF",
"signature": "def updateF(self, data)"
}
] | 2 | null | Implement the Python class `XasTimXgmPulsePlot` described below.
Class description:
XasTimXgmPulsePlot class. Visualize XGM intensity in the current train.
Method signatures and docstrings:
- def __init__(self, *, parent=None): Initialization.
- def updateF(self, data): Override. | Implement the Python class `XasTimXgmPulsePlot` described below.
Class description:
XasTimXgmPulsePlot class. Visualize XGM intensity in the current train.
Method signatures and docstrings:
- def __init__(self, *, parent=None): Initialization.
- def updateF(self, data): Override.
<|skeleton|>
class XasTimXgmPulsePlo... | a6ee28040b15ae8d110570bd9f3c37e5a3e70fc0 | <|skeleton|>
class XasTimXgmPulsePlot:
"""XasTimXgmPulsePlot class. Visualize XGM intensity in the current train."""
def __init__(self, *, parent=None):
"""Initialization."""
<|body_0|>
def updateF(self, data):
"""Override."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XasTimXgmPulsePlot:
"""XasTimXgmPulsePlot class. Visualize XGM intensity in the current train."""
def __init__(self, *, parent=None):
"""Initialization."""
super().__init__(parent=parent)
self.setTitle('Pulse intensities (SA3)')
self.setLabel('left', 'Intensity (arb.)')
... | the_stack_v2_python_sparse | extra_foam/special_suite/xas_tim_w.py | European-XFEL/EXtra-foam | train | 8 |
0c9c8e583008ed45d2b7d3c579c680049fb9ccee | [
"from models import User, Rol, roles\nuser = User.query.filter(User.name == usuarioName).first_or_404()\nrol = Rol.query.filter(Rol.nombre == rolNombre).first_or_404()\nuser.roles.append(rol)\ndb.session.commit()",
"from models import User, Rol, roles\nuser = User.query.filter(User.name == usuarioName).first_or_4... | <|body_start_0|>
from models import User, Rol, roles
user = User.query.filter(User.name == usuarioName).first_or_404()
rol = Rol.query.filter(Rol.nombre == rolNombre).first_or_404()
user.roles.append(rol)
db.session.commit()
<|end_body_0|>
<|body_start_1|>
from models im... | MgrUserXRol | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MgrUserXRol:
def guardar(self, usuarioName, rolNombre):
"""asigna un rol a un usuario"""
<|body_0|>
def borrar(self, usuarioName, rolNombre):
"""desasigna un rol a un usuario"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from models import User, R... | stack_v2_sparse_classes_36k_train_002503 | 749 | no_license | [
{
"docstring": "asigna un rol a un usuario",
"name": "guardar",
"signature": "def guardar(self, usuarioName, rolNombre)"
},
{
"docstring": "desasigna un rol a un usuario",
"name": "borrar",
"signature": "def borrar(self, usuarioName, rolNombre)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013522 | Implement the Python class `MgrUserXRol` described below.
Class description:
Implement the MgrUserXRol class.
Method signatures and docstrings:
- def guardar(self, usuarioName, rolNombre): asigna un rol a un usuario
- def borrar(self, usuarioName, rolNombre): desasigna un rol a un usuario | Implement the Python class `MgrUserXRol` described below.
Class description:
Implement the MgrUserXRol class.
Method signatures and docstrings:
- def guardar(self, usuarioName, rolNombre): asigna un rol a un usuario
- def borrar(self, usuarioName, rolNombre): desasigna un rol a un usuario
<|skeleton|>
class MgrUserX... | da5330f318698f86af12c3c91cb3f1524540f4ca | <|skeleton|>
class MgrUserXRol:
def guardar(self, usuarioName, rolNombre):
"""asigna un rol a un usuario"""
<|body_0|>
def borrar(self, usuarioName, rolNombre):
"""desasigna un rol a un usuario"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MgrUserXRol:
def guardar(self, usuarioName, rolNombre):
"""asigna un rol a un usuario"""
from models import User, Rol, roles
user = User.query.filter(User.name == usuarioName).first_or_404()
rol = Rol.query.filter(Rol.nombre == rolNombre).first_or_404()
user.roles.appen... | the_stack_v2_python_sparse | src/mgrUserXRol.py | frvc123/proyecto-sicp | train | 0 | |
9141a8064c5c84334e89c4e793aa60b310a9613c | [
"self.services = services_definition['services']\nself.builders = {}\nfor service in self.services:\n service_builder = service.get('service-builder')\n if not service_builder:\n continue\n if isinstance(service_builder, dict):\n for name, builder in service_builder.items():\n full... | <|body_start_0|>
self.services = services_definition['services']
self.builders = {}
for service in self.services:
service_builder = service.get('service-builder')
if not service_builder:
continue
if isinstance(service_builder, dict):
... | ServiceBuilder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServiceBuilder:
def __init__(self, services_definition=services_config):
"""@brief @brief Create a ServiceBuilder. @param services_definition Complete services definition, services.xml."""
<|body_0|>
def buildServiceURL(self, name, context):
"""@brief given the envir... | stack_v2_sparse_classes_36k_train_002504 | 4,026 | no_license | [
{
"docstring": "@brief @brief Create a ServiceBuilder. @param services_definition Complete services definition, services.xml.",
"name": "__init__",
"signature": "def __init__(self, services_definition=services_config)"
},
{
"docstring": "@brief given the environment on construction, return a ser... | 2 | stack_v2_sparse_classes_30k_train_002342 | Implement the Python class `ServiceBuilder` described below.
Class description:
Implement the ServiceBuilder class.
Method signatures and docstrings:
- def __init__(self, services_definition=services_config): @brief @brief Create a ServiceBuilder. @param services_definition Complete services definition, services.xml.... | Implement the Python class `ServiceBuilder` described below.
Class description:
Implement the ServiceBuilder class.
Method signatures and docstrings:
- def __init__(self, services_definition=services_config): @brief @brief Create a ServiceBuilder. @param services_definition Complete services definition, services.xml.... | 00645a93b672dd3ce5e02bd620a90b8e275aba01 | <|skeleton|>
class ServiceBuilder:
def __init__(self, services_definition=services_config):
"""@brief @brief Create a ServiceBuilder. @param services_definition Complete services definition, services.xml."""
<|body_0|>
def buildServiceURL(self, name, context):
"""@brief given the envir... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ServiceBuilder:
def __init__(self, services_definition=services_config):
"""@brief @brief Create a ServiceBuilder. @param services_definition Complete services definition, services.xml."""
self.services = services_definition['services']
self.builders = {}
for service in self.se... | the_stack_v2_python_sparse | indra/lib/python/indra/ipc/servicebuilder.py | OS-Development/VW.Meerkat | train | 1 | |
883e896d6c2c5cdb20126336a0449040b358334e | [
"self.name = name or self.__class__.__name__\nself.last_layer_only = last_layer_only\nself.sample_size = 1\nself.reduce_fn = reduce_fn\ntry:\n reduce_fn(torch.Tensor([[0], [1]]), dim=0)\nexcept BaseException:\n raise ValueError('reduce_fn should have a signature like tf.reduce_mean!')",
"model.train()\noutp... | <|body_start_0|>
self.name = name or self.__class__.__name__
self.last_layer_only = last_layer_only
self.sample_size = 1
self.reduce_fn = reduce_fn
try:
reduce_fn(torch.Tensor([[0], [1]]), dim=0)
except BaseException:
raise ValueError('reduce_fn sh... | GradCAM: intermediate activations and gradients as input importance. GradCAM is the gradient version of CAM using ideas from Gradient times Input, removing the necessity of a GAP layer. For each convolution layer, in the case of graphs a GNN block, the activations can be retrieved and interpreted as a transformed versi... | GradCAM | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GradCAM:
"""GradCAM: intermediate activations and gradients as input importance. GradCAM is the gradient version of CAM using ideas from Gradient times Input, removing the necessity of a GAP layer. For each convolution layer, in the case of graphs a GNN block, the activations can be retrieved and... | stack_v2_sparse_classes_36k_train_002505 | 3,643 | permissive | [
{
"docstring": "GradCAM constructor. Args: last_layer_only: If to use only the last layer activations, if not will use all last activations. reduce_fn: Reduction operation for layers, should have the same call signature as torch.mean (e.g. tf.reduce_sum). name: identifying label for method.",
"name": "__ini... | 2 | stack_v2_sparse_classes_30k_train_002181 | Implement the Python class `GradCAM` described below.
Class description:
GradCAM: intermediate activations and gradients as input importance. GradCAM is the gradient version of CAM using ideas from Gradient times Input, removing the necessity of a GAP layer. For each convolution layer, in the case of graphs a GNN bloc... | Implement the Python class `GradCAM` described below.
Class description:
GradCAM: intermediate activations and gradients as input importance. GradCAM is the gradient version of CAM using ideas from Gradient times Input, removing the necessity of a GAP layer. For each convolution layer, in the case of graphs a GNN bloc... | 11a36843a83ddc93748c5437f5a21f2507b66c77 | <|skeleton|>
class GradCAM:
"""GradCAM: intermediate activations and gradients as input importance. GradCAM is the gradient version of CAM using ideas from Gradient times Input, removing the necessity of a GAP layer. For each convolution layer, in the case of graphs a GNN block, the activations can be retrieved and... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GradCAM:
"""GradCAM: intermediate activations and gradients as input importance. GradCAM is the gradient version of CAM using ideas from Gradient times Input, removing the necessity of a GAP layer. For each convolution layer, in the case of graphs a GNN block, the activations can be retrieved and interpreted ... | the_stack_v2_python_sparse | MolRep/Explainer/Attribution/GradCAM.py | biomed-AI/MolRep | train | 104 |
aded2b1537ab5890a567093c5927a3bb7b016343 | [
"super().__init__(graph)\nsolver = solver.upper()\nif solver not in cp.installed_solvers():\n raise KeyError(\"Solver '%s' is not installed.\" % solver)\nself.solver = getattr(cp, solver)",
"matrix = self._solve_sdp()\nmatrix = nearest_psd(matrix)\nvectors = np.linalg.cholesky(matrix)\ncut = get_partition(vect... | <|body_start_0|>
super().__init__(graph)
solver = solver.upper()
if solver not in cp.installed_solvers():
raise KeyError("Solver '%s' is not installed." % solver)
self.solver = getattr(cp, solver)
<|end_body_0|>
<|body_start_1|>
matrix = self._solve_sdp()
mat... | Semi-Definite Programming based solver for the Max-Cut problem. Given a graph with non-negative weights, the method implemented here aims at maximizing $$\\sum_{{i < j}} w_{{ij}}(1 - x_{{ij}})$$ where $X = (x_{{ij}}))$ is a positive semi-definite matrix with values equal to 1 on its diagonal. The implementation relies ... | MaxCutSDP | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaxCutSDP:
"""Semi-Definite Programming based solver for the Max-Cut problem. Given a graph with non-negative weights, the method implemented here aims at maximizing $$\\sum_{{i < j}} w_{{ij}}(1 - x_{{ij}})$$ where $X = (x_{{ij}}))$ is a positive semi-definite matrix with values equal to 1 on its... | stack_v2_sparse_classes_36k_train_002506 | 4,255 | permissive | [
{
"docstring": "Instantiate the SDP-relaxed Max-Cut solver. graph : networkx.Graph instance of the graph to cut solver : name of the solver to use (default 'scs') Note: 'cvxopt' appears, in general, better than 'scs', but tends to disfunction on large (or even middle-sized) graphs, for an unknown reason interna... | 3 | null | Implement the Python class `MaxCutSDP` described below.
Class description:
Semi-Definite Programming based solver for the Max-Cut problem. Given a graph with non-negative weights, the method implemented here aims at maximizing $$\\sum_{{i < j}} w_{{ij}}(1 - x_{{ij}})$$ where $X = (x_{{ij}}))$ is a positive semi-defini... | Implement the Python class `MaxCutSDP` described below.
Class description:
Semi-Definite Programming based solver for the Max-Cut problem. Given a graph with non-negative weights, the method implemented here aims at maximizing $$\\sum_{{i < j}} w_{{ij}}(1 - x_{{ij}})$$ where $X = (x_{{ij}}))$ is a positive semi-defini... | 002c5ecbad671b75059290065db73a7152c98db9 | <|skeleton|>
class MaxCutSDP:
"""Semi-Definite Programming based solver for the Max-Cut problem. Given a graph with non-negative weights, the method implemented here aims at maximizing $$\\sum_{{i < j}} w_{{ij}}(1 - x_{{ij}})$$ where $X = (x_{{ij}}))$ is a positive semi-definite matrix with values equal to 1 on its... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MaxCutSDP:
"""Semi-Definite Programming based solver for the Max-Cut problem. Given a graph with non-negative weights, the method implemented here aims at maximizing $$\\sum_{{i < j}} w_{{ij}}(1 - x_{{ij}})$$ where $X = (x_{{ij}}))$ is a positive semi-definite matrix with values equal to 1 on its diagonal. Th... | the_stack_v2_python_sparse | 启发式搜索与演化算法/hw4/_sdp.py | jocelyn2002/NJUAI_CodingHW | train | 5 |
da94067534fe0d909b4cddfb4a5d47467b9dd595 | [
"global COMPANY_CONN\ncursor = None\ntry:\n n = str(lieGoodsPrice['goods_id'])[-1:]\n cursor = COMPANY_CONN.cursor(buffered=True, dictionary=True)\n sql = 'INSERT INTO lie_goods(goods_id, price) VALUES(%(goods_id)s, %(price)s)'\n cursor.execute(sql, lieGoodsPrice)\n COMPANY_CONN.commit()\nexcept Exce... | <|body_start_0|>
global COMPANY_CONN
cursor = None
try:
n = str(lieGoodsPrice['goods_id'])[-1:]
cursor = COMPANY_CONN.cursor(buffered=True, dictionary=True)
sql = 'INSERT INTO lie_goods(goods_id, price) VALUES(%(goods_id)s, %(price)s)'
cursor.execu... | LieGoodsPrice | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LieGoodsPrice:
def addLieGoodsPrice(cls, lieGoodsPrice):
"""method: addLieGoodsPrice params: lieGoodsPrice-type: LieGoodsPrice"""
<|body_0|>
def get_price_by_goods_id(cls, goods_id):
"""method: get_price_by_goods_id params: goods_id-type: int return: price return-typ... | stack_v2_sparse_classes_36k_train_002507 | 13,174 | no_license | [
{
"docstring": "method: addLieGoodsPrice params: lieGoodsPrice-type: LieGoodsPrice",
"name": "addLieGoodsPrice",
"signature": "def addLieGoodsPrice(cls, lieGoodsPrice)"
},
{
"docstring": "method: get_price_by_goods_id params: goods_id-type: int return: price return-type: str json",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_014018 | Implement the Python class `LieGoodsPrice` described below.
Class description:
Implement the LieGoodsPrice class.
Method signatures and docstrings:
- def addLieGoodsPrice(cls, lieGoodsPrice): method: addLieGoodsPrice params: lieGoodsPrice-type: LieGoodsPrice
- def get_price_by_goods_id(cls, goods_id): method: get_pri... | Implement the Python class `LieGoodsPrice` described below.
Class description:
Implement the LieGoodsPrice class.
Method signatures and docstrings:
- def addLieGoodsPrice(cls, lieGoodsPrice): method: addLieGoodsPrice params: lieGoodsPrice-type: LieGoodsPrice
- def get_price_by_goods_id(cls, goods_id): method: get_pri... | 1e49a6e13ea4b11427f47999c13a609be9ae3ecf | <|skeleton|>
class LieGoodsPrice:
def addLieGoodsPrice(cls, lieGoodsPrice):
"""method: addLieGoodsPrice params: lieGoodsPrice-type: LieGoodsPrice"""
<|body_0|>
def get_price_by_goods_id(cls, goods_id):
"""method: get_price_by_goods_id params: goods_id-type: int return: price return-typ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LieGoodsPrice:
def addLieGoodsPrice(cls, lieGoodsPrice):
"""method: addLieGoodsPrice params: lieGoodsPrice-type: LieGoodsPrice"""
global COMPANY_CONN
cursor = None
try:
n = str(lieGoodsPrice['goods_id'])[-1:]
cursor = COMPANY_CONN.cursor(buffered=True, d... | the_stack_v2_python_sparse | rsonline/server/db/company/mysql_client.py | yunhao-qing/PythonScrapy | train | 0 | |
5187607b6a38859f0aaa1dc6c9e2881eeb49181e | [
"if not s or len(s) == 0:\n return 0\nstack = []\nnum = 0\nsign = '+'\nfor index in range(len(s)):\n ch = s[index]\n if ch.isdigit():\n num = num * 10 + int(ch)\n if not ch.isdigit() and ch != ' ' or index == len(s) - 1:\n if sign == '+':\n stack.append(num)\n elif sign =... | <|body_start_0|>
if not s or len(s) == 0:
return 0
stack = []
num = 0
sign = '+'
for index in range(len(s)):
ch = s[index]
if ch.isdigit():
num = num * 10 + int(ch)
if not ch.isdigit() and ch != ' ' or index == len(s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def calculate(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def calculate(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not s or len(s) == 0:
return 0
stack = []
... | stack_v2_sparse_classes_36k_train_002508 | 2,253 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "calculate",
"signature": "def calculate(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "calculate",
"signature": "def calculate(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calculate(self, s): :type s: str :rtype: int
- def calculate(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 calculate(self, s): :type s: str :rtype: int
- def calculate(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def calculate(self, s):
""":type s:... | d953abe2c9680f636563e76287d2f907e90ced63 | <|skeleton|>
class Solution:
def calculate(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def calculate(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def calculate(self, s):
""":type s: str :rtype: int"""
if not s or len(s) == 0:
return 0
stack = []
num = 0
sign = '+'
for index in range(len(s)):
ch = s[index]
if ch.isdigit():
num = num * 10 + int(c... | the_stack_v2_python_sparse | Python_leetcode/227_basic_calculate_ii.py | xiangcao/Leetcode | train | 0 | |
0144888d1b9b077b84656a8bf9b9cf9f9c1d4970 | [
"def helper(root):\n if root:\n ans.append(str(root.val))\n helper(root.left)\n helper(root.right)\n else:\n ans.append('#')\nans = []\nhelper(root)\nreturn ' '.join(ans)",
"def helper2():\n val = next(vals)\n if val == '#':\n return None\n node = TreeNode(int(val... | <|body_start_0|>
def helper(root):
if root:
ans.append(str(root.val))
helper(root.left)
helper(root.right)
else:
ans.append('#')
ans = []
helper(root)
return ' '.join(ans)
<|end_body_0|>
<|body_start... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_002509 | 5,715 | 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_018206 | 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:... | c95e789d24ae9044e73acdba01a57c30b19ef9c1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def helper(root):
if root:
ans.append(str(root.val))
helper(root.left)
helper(root.right)
else:
an... | the_stack_v2_python_sparse | Serialize_and_Deserialize_Binary_Tree.py | xiang525/my_leetcode | train | 0 | |
be8188999f2a51cbec2b3554b4f112cd782a94d9 | [
"self.reqpaser = reqparse.RequestParser()\nself.reqpaser.add_argument('attribute_id', type=str, store_missing=False, required=False)\nself.reqpaser.add_argument('subtheme_id', type=int, store_missing=False, required=False)",
"args = self.reqpaser.parse_args()\nif 'attribute_id' in args and 'subtheme_id' not in ar... | <|body_start_0|>
self.reqpaser = reqparse.RequestParser()
self.reqpaser.add_argument('attribute_id', type=str, store_missing=False, required=False)
self.reqpaser.add_argument('subtheme_id', type=int, store_missing=False, required=False)
<|end_body_0|>
<|body_start_1|>
args = self.reqpas... | Get Attributes from database | GetAttributes | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetAttributes:
"""Get Attributes from database"""
def __init__(self) -> None:
"""Set reqpase arguments"""
<|body_0|>
def get(self) -> [db.Model]:
"""Fetch Attributes from the database :param attribute_id: Attribute id :param subtheme_id: SubTheme id :return: A li... | stack_v2_sparse_classes_36k_train_002510 | 2,129 | permissive | [
{
"docstring": "Set reqpase arguments",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Fetch Attributes from the database :param attribute_id: Attribute id :param subtheme_id: SubTheme id :return: A list of Attributes with an HTTPstatus code OK (200) or an error... | 2 | stack_v2_sparse_classes_30k_train_011485 | Implement the Python class `GetAttributes` described below.
Class description:
Get Attributes from database
Method signatures and docstrings:
- def __init__(self) -> None: Set reqpase arguments
- def get(self) -> [db.Model]: Fetch Attributes from the database :param attribute_id: Attribute id :param subtheme_id: SubT... | Implement the Python class `GetAttributes` described below.
Class description:
Get Attributes from database
Method signatures and docstrings:
- def __init__(self) -> None: Set reqpase arguments
- def get(self) -> [db.Model]: Fetch Attributes from the database :param attribute_id: Attribute id :param subtheme_id: SubT... | 5d123691d1f25d0b85e20e4e8293266bf23c9f8a | <|skeleton|>
class GetAttributes:
"""Get Attributes from database"""
def __init__(self) -> None:
"""Set reqpase arguments"""
<|body_0|>
def get(self) -> [db.Model]:
"""Fetch Attributes from the database :param attribute_id: Attribute id :param subtheme_id: SubTheme id :return: A li... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetAttributes:
"""Get Attributes from database"""
def __init__(self) -> None:
"""Set reqpase arguments"""
self.reqpaser = reqparse.RequestParser()
self.reqpaser.add_argument('attribute_id', type=str, store_missing=False, required=False)
self.reqpaser.add_argument('subtheme... | the_stack_v2_python_sparse | Analytics/resources/attributes/get_attributes.py | thanosbnt/SharingCitiesDashboard | train | 0 |
3f5bd9cc4321e2c3a0dc4fc90cd05ca770aead2b | [
"first_text = (('i', 'have', 'a', 'cat'), ('his', 'name', 'is', 'bruno'))\nsecond_text = (('i', 'have', 'a', 'cat'), ('his', 'name', 'is', 'paw'))\nexpected = {'text_plagiarism': 0.875, 'sentence_plagiarism': [1.0, 0.75], 'sentence_lcs_length': [4, 3], 'difference_indexes': [((), ()), ((3, 4), (3, 4))]}\nactual = a... | <|body_start_0|>
first_text = (('i', 'have', 'a', 'cat'), ('his', 'name', 'is', 'bruno'))
second_text = (('i', 'have', 'a', 'cat'), ('his', 'name', 'is', 'paw'))
expected = {'text_plagiarism': 0.875, 'sentence_plagiarism': [1.0, 0.75], 'sentence_lcs_length': [4, 3], 'difference_indexes': [((), (... | Checks for accumulate_diff_stats function | AccumulateDiffStatsTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccumulateDiffStatsTest:
"""Checks for accumulate_diff_stats function"""
def test_accumulate_diff_stats_ideal(self):
"""Tests that accumulate_diff_stats function can handle simple ideal input"""
<|body_0|>
def test_accumulate_diff_stats_check_output(self):
"""Tes... | stack_v2_sparse_classes_36k_train_002511 | 3,701 | permissive | [
{
"docstring": "Tests that accumulate_diff_stats function can handle simple ideal input",
"name": "test_accumulate_diff_stats_ideal",
"signature": "def test_accumulate_diff_stats_ideal(self)"
},
{
"docstring": "Tests that accumulate_diff_stats function can generate correct correct output accordi... | 5 | stack_v2_sparse_classes_30k_train_004604 | Implement the Python class `AccumulateDiffStatsTest` described below.
Class description:
Checks for accumulate_diff_stats function
Method signatures and docstrings:
- def test_accumulate_diff_stats_ideal(self): Tests that accumulate_diff_stats function can handle simple ideal input
- def test_accumulate_diff_stats_ch... | Implement the Python class `AccumulateDiffStatsTest` described below.
Class description:
Checks for accumulate_diff_stats function
Method signatures and docstrings:
- def test_accumulate_diff_stats_ideal(self): Tests that accumulate_diff_stats function can handle simple ideal input
- def test_accumulate_diff_stats_ch... | ada4bec878dd1cbc19058cb4e87893946ae21498 | <|skeleton|>
class AccumulateDiffStatsTest:
"""Checks for accumulate_diff_stats function"""
def test_accumulate_diff_stats_ideal(self):
"""Tests that accumulate_diff_stats function can handle simple ideal input"""
<|body_0|>
def test_accumulate_diff_stats_check_output(self):
"""Tes... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccumulateDiffStatsTest:
"""Checks for accumulate_diff_stats function"""
def test_accumulate_diff_stats_ideal(self):
"""Tests that accumulate_diff_stats function can handle simple ideal input"""
first_text = (('i', 'have', 'a', 'cat'), ('his', 'name', 'is', 'bruno'))
second_text =... | the_stack_v2_python_sparse | lab_2/accumulate_diff_stats_test.py | WhiteJaeger/2020-2-level-labs | train | 0 |
8bb053396bfc84bed1b2e1f9f358852fc1435138 | [
"super(SimulatedInteractionModule, self).__init__()\nself.pool_data, self.occ_data, self.start_end = (pool_data, occ_data, seq_start_end)\nself.traj_len, self.num_seqs = (obs.shape[0] - 1 + pred.shape[0], seq_start_end.shape[0])\nself.t, self.s = (0, 0)\nself.embedding, self.embedding_occ = (interaction_module.embe... | <|body_start_0|>
super(SimulatedInteractionModule, self).__init__()
self.pool_data, self.occ_data, self.start_end = (pool_data, occ_data, seq_start_end)
self.traj_len, self.num_seqs = (obs.shape[0] - 1 + pred.shape[0], seq_start_end.shape[0])
self.t, self.s = (0, 0)
self.embeddin... | Simulates the ShapeBasedPooling class (../interacion_modules/shape_based.py) to return pooling of of neighbour motion. The pooling data has been pre-computed, which is why this module simulates it. The module knows how many sequences there are, and sequentially returns the correct portion of the pooling data assuming t... | SimulatedInteractionModule | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimulatedInteractionModule:
"""Simulates the ShapeBasedPooling class (../interacion_modules/shape_based.py) to return pooling of of neighbour motion. The pooling data has been pre-computed, which is why this module simulates it. The module knows how many sequences there are, and sequentially retu... | stack_v2_sparse_classes_36k_train_002512 | 17,400 | permissive | [
{
"docstring": "Initialize the SimulatedInteractionModule with a batch of data :param obs: Tensor of shape (obs_len, num_peds, 2). Observed (past) trajectories :param pred: Tensor of shape (pred_len, num_peds, 2). Predicted (or future) trajectories :param seq_start_end: Tensor of shape (batch_size). Delimitting... | 2 | stack_v2_sparse_classes_30k_train_004204 | Implement the Python class `SimulatedInteractionModule` described below.
Class description:
Simulates the ShapeBasedPooling class (../interacion_modules/shape_based.py) to return pooling of of neighbour motion. The pooling data has been pre-computed, which is why this module simulates it. The module knows how many seq... | Implement the Python class `SimulatedInteractionModule` described below.
Class description:
Simulates the ShapeBasedPooling class (../interacion_modules/shape_based.py) to return pooling of of neighbour motion. The pooling data has been pre-computed, which is why this module simulates it. The module knows how many seq... | 1b9fbe6c89c74dc706fd8d3b11ea08977ba2c1d3 | <|skeleton|>
class SimulatedInteractionModule:
"""Simulates the ShapeBasedPooling class (../interacion_modules/shape_based.py) to return pooling of of neighbour motion. The pooling data has been pre-computed, which is why this module simulates it. The module knows how many sequences there are, and sequentially retu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimulatedInteractionModule:
"""Simulates the ShapeBasedPooling class (../interacion_modules/shape_based.py) to return pooling of of neighbour motion. The pooling data has been pre-computed, which is why this module simulates it. The module knows how many sequences there are, and sequentially returns the corre... | the_stack_v2_python_sparse | models/interaction_modules/train_aux.py | pedro-mgb/pedestrian-arc-lstm-smf | train | 4 |
fdec7fcf22ef1bb9b807996c83f9dd61bcdbe8a2 | [
"if AudioOutputHandler.__instance is not None:\n raise Exception('This class is a singleton!')\nelse:\n AudioOutputHandler.__instance = self",
"if AudioOutputHandler.__instance is None:\n AudioOutputHandler()\nreturn AudioOutputHandler.__instance",
"text_to_mp3 = TextToMP3.get_instance()\ntext_to_mp3.c... | <|body_start_0|>
if AudioOutputHandler.__instance is not None:
raise Exception('This class is a singleton!')
else:
AudioOutputHandler.__instance = self
<|end_body_0|>
<|body_start_1|>
if AudioOutputHandler.__instance is None:
AudioOutputHandler()
retu... | AudioOutputHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AudioOutputHandler:
def __init__(self):
"""Virtually private constructor. This class is a singleton."""
<|body_0|>
def get_instance():
"""Static access method."""
<|body_1|>
def speak(self, text, filename):
"""" Get the TextToMP3 instance and con... | stack_v2_sparse_classes_36k_train_002513 | 1,117 | no_license | [
{
"docstring": "Virtually private constructor. This class is a singleton.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Static access method.",
"name": "get_instance",
"signature": "def get_instance()"
},
{
"docstring": "\" Get the TextToMP3 instance ... | 3 | null | Implement the Python class `AudioOutputHandler` described below.
Class description:
Implement the AudioOutputHandler class.
Method signatures and docstrings:
- def __init__(self): Virtually private constructor. This class is a singleton.
- def get_instance(): Static access method.
- def speak(self, text, filename): "... | Implement the Python class `AudioOutputHandler` described below.
Class description:
Implement the AudioOutputHandler class.
Method signatures and docstrings:
- def __init__(self): Virtually private constructor. This class is a singleton.
- def get_instance(): Static access method.
- def speak(self, text, filename): "... | 53fa4e6910ef9f226ea93510ec5cbeca131ee66c | <|skeleton|>
class AudioOutputHandler:
def __init__(self):
"""Virtually private constructor. This class is a singleton."""
<|body_0|>
def get_instance():
"""Static access method."""
<|body_1|>
def speak(self, text, filename):
"""" Get the TextToMP3 instance and con... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AudioOutputHandler:
def __init__(self):
"""Virtually private constructor. This class is a singleton."""
if AudioOutputHandler.__instance is not None:
raise Exception('This class is a singleton!')
else:
AudioOutputHandler.__instance = self
def get_instance()... | the_stack_v2_python_sparse | parts/audio/output/AudioOutputHandler.py | Guerzoniansus/BingoBotController | train | 0 | |
406e66a7dbdee8a5ac1b6aafa6a3a0fcc4ad9750 | [
"feature_id = kwargs['feature_id']\ngate_id = kwargs.get('gate_id', None)\nvotes = Vote.get_votes(feature_id=feature_id, gate_id=gate_id)\ndicts = [converters.vote_value_to_json_dict(v) for v in votes]\nreturn {'votes': dicts}",
"feature_id = kwargs['feature_id']\ngate_id = kwargs['gate_id']\nfeature = self.get_s... | <|body_start_0|>
feature_id = kwargs['feature_id']
gate_id = kwargs.get('gate_id', None)
votes = Vote.get_votes(feature_id=feature_id, gate_id=gate_id)
dicts = [converters.vote_value_to_json_dict(v) for v in votes]
return {'votes': dicts}
<|end_body_0|>
<|body_start_1|>
... | Users may see the set of votes on a feature, and add their own, if allowed. | VotesAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VotesAPI:
"""Users may see the set of votes on a feature, and add their own, if allowed."""
def do_get(self, **kwargs) -> dict[str, list[dict[str, Any]]]:
"""Return a list of all vote values for a given feature."""
<|body_0|>
def do_post(self, **kwargs) -> dict[str, str]... | stack_v2_sparse_classes_36k_train_002514 | 4,047 | permissive | [
{
"docstring": "Return a list of all vote values for a given feature.",
"name": "do_get",
"signature": "def do_get(self, **kwargs) -> dict[str, list[dict[str, Any]]]"
},
{
"docstring": "Set a user's vote value for the specified feature and gate.",
"name": "do_post",
"signature": "def do_... | 3 | stack_v2_sparse_classes_30k_train_001413 | Implement the Python class `VotesAPI` described below.
Class description:
Users may see the set of votes on a feature, and add their own, if allowed.
Method signatures and docstrings:
- def do_get(self, **kwargs) -> dict[str, list[dict[str, Any]]]: Return a list of all vote values for a given feature.
- def do_post(s... | Implement the Python class `VotesAPI` described below.
Class description:
Users may see the set of votes on a feature, and add their own, if allowed.
Method signatures and docstrings:
- def do_get(self, **kwargs) -> dict[str, list[dict[str, Any]]]: Return a list of all vote values for a given feature.
- def do_post(s... | 17f9886d064da5bda84006d5866077727646fff2 | <|skeleton|>
class VotesAPI:
"""Users may see the set of votes on a feature, and add their own, if allowed."""
def do_get(self, **kwargs) -> dict[str, list[dict[str, Any]]]:
"""Return a list of all vote values for a given feature."""
<|body_0|>
def do_post(self, **kwargs) -> dict[str, str]... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VotesAPI:
"""Users may see the set of votes on a feature, and add their own, if allowed."""
def do_get(self, **kwargs) -> dict[str, list[dict[str, Any]]]:
"""Return a list of all vote values for a given feature."""
feature_id = kwargs['feature_id']
gate_id = kwargs.get('gate_id', ... | the_stack_v2_python_sparse | api/reviews_api.py | GoogleChrome/chromium-dashboard | train | 574 |
77beaa7bd4c490cf4948c4ca25bb5d3c25483a9d | [
"super(EditVendorDialog, self).__init__(parent=parent)\nself.setupUi(self)\nself.dbsession = Session()\nself.selected_vendor = None\nvendor_names = [result.name for result in self.dbsession.query(Vendor.name).filter(Vendor.name != 'Amazon')]\nself.vendorBox.addItems(vendor_names)\nself.accepted.connect(self.update_... | <|body_start_0|>
super(EditVendorDialog, self).__init__(parent=parent)
self.setupUi(self)
self.dbsession = Session()
self.selected_vendor = None
vendor_names = [result.name for result in self.dbsession.query(Vendor.name).filter(Vendor.name != 'Amazon')]
self.vendorBox.add... | A dialog that provides viewing and editing for Vendor features. | EditVendorDialog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditVendorDialog:
"""A dialog that provides viewing and editing for Vendor features."""
def __init__(self, default=None, parent=None):
"""Initialize the widgets with info from the vendor specified by default. Default is a name."""
<|body_0|>
def on_vendor_changed(self):
... | stack_v2_sparse_classes_36k_train_002515 | 25,458 | no_license | [
{
"docstring": "Initialize the widgets with info from the vendor specified by default. Default is a name.",
"name": "__init__",
"signature": "def __init__(self, default=None, parent=None)"
},
{
"docstring": "Update the widgets with the info from the newly selected vendor.",
"name": "on_vendo... | 3 | stack_v2_sparse_classes_30k_test_000094 | Implement the Python class `EditVendorDialog` described below.
Class description:
A dialog that provides viewing and editing for Vendor features.
Method signatures and docstrings:
- def __init__(self, default=None, parent=None): Initialize the widgets with info from the vendor specified by default. Default is a name.... | Implement the Python class `EditVendorDialog` described below.
Class description:
A dialog that provides viewing and editing for Vendor features.
Method signatures and docstrings:
- def __init__(self, default=None, parent=None): Initialize the widgets with info from the vendor specified by default. Default is a name.... | 7d22707a1782125d86140c52d20eaadd2df6e4fc | <|skeleton|>
class EditVendorDialog:
"""A dialog that provides viewing and editing for Vendor features."""
def __init__(self, default=None, parent=None):
"""Initialize the widgets with info from the vendor specified by default. Default is a name."""
<|body_0|>
def on_vendor_changed(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EditVendorDialog:
"""A dialog that provides viewing and editing for Vendor features."""
def __init__(self, default=None, parent=None):
"""Initialize the widgets with info from the vendor specified by default. Default is a name."""
super(EditVendorDialog, self).__init__(parent=parent)
... | the_stack_v2_python_sparse | dialogs.py | garrettmk/Prowler | train | 1 |
9375ff595168b269b61c056e250e06e0895a8b7b | [
"self.argv = argv\nself.script_base = _getCallerPath()\nself.argsManifest = {}\ndefault_args = ['configfile', 'logfile', 'loglevel', 'logto', 'debug']\nfor arg in default_args:\n self.argsManifest[arg] = dict(type=str, default=None, help='', required=False)\n if arg == 'configfile':\n self.argsManifest... | <|body_start_0|>
self.argv = argv
self.script_base = _getCallerPath()
self.argsManifest = {}
default_args = ['configfile', 'logfile', 'loglevel', 'logto', 'debug']
for arg in default_args:
self.argsManifest[arg] = dict(type=str, default=None, help='', required=False)
... | General purpose command line arguments and config arguments handler returns a set args objects with result. Methods: __init__ - standard constructor addArgs - manifest arguments _missingArgsAlert - raise error if required args are missing handleCommandArgs - command line args handler handleArgs - config args handler Ar... | ArgumentHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArgumentHandler:
"""General purpose command line arguments and config arguments handler returns a set args objects with result. Methods: __init__ - standard constructor addArgs - manifest arguments _missingArgsAlert - raise error if required args are missing handleCommandArgs - command line args ... | stack_v2_sparse_classes_36k_train_002516 | 8,418 | no_license | [
{
"docstring": "Class constructor. Args: argv - command line arguments",
"name": "__init__",
"signature": "def __init__(self, argv=None)"
},
{
"docstring": "Manifest arguments in dictionary.",
"name": "addArgs",
"signature": "def addArgs(self, **kwargs)"
},
{
"docstring": "Enforc... | 5 | stack_v2_sparse_classes_30k_val_000286 | Implement the Python class `ArgumentHandler` described below.
Class description:
General purpose command line arguments and config arguments handler returns a set args objects with result. Methods: __init__ - standard constructor addArgs - manifest arguments _missingArgsAlert - raise error if required args are missing... | Implement the Python class `ArgumentHandler` described below.
Class description:
General purpose command line arguments and config arguments handler returns a set args objects with result. Methods: __init__ - standard constructor addArgs - manifest arguments _missingArgsAlert - raise error if required args are missing... | e84ba5e1ac4bd0adaf3217a4b9a0fade40601810 | <|skeleton|>
class ArgumentHandler:
"""General purpose command line arguments and config arguments handler returns a set args objects with result. Methods: __init__ - standard constructor addArgs - manifest arguments _missingArgsAlert - raise error if required args are missing handleCommandArgs - command line args ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArgumentHandler:
"""General purpose command line arguments and config arguments handler returns a set args objects with result. Methods: __init__ - standard constructor addArgs - manifest arguments _missingArgsAlert - raise error if required args are missing handleCommandArgs - command line args handler handl... | the_stack_v2_python_sparse | utils/argsHandler.py | krishnatpatil/python-practice | train | 0 |
e63f6accc744295ac34222e1e8b5c59f05dc8d3d | [
"if not email:\n raise ValueError('Users must have an email address')\nuser = self.model(email=self.normalize_email(email))\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(email, password=password)\nuser.is_admin = True\nuser.save(using=self._db)\nreturn user"
] | <|body_start_0|>
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email))
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<|body_start_1|>
user = self.create_user(... | MyUserManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyUserManager:
def create_user(self, email, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, password=None):
"""Creates and saves a superuser with the given email, date of bi... | stack_v2_sparse_classes_36k_train_002517 | 4,400 | permissive | [
{
"docstring": "Creates and saves a User with the given email, date of birth and password.",
"name": "create_user",
"signature": "def create_user(self, email, password=None)"
},
{
"docstring": "Creates and saves a superuser with the given email, date of birth and password.",
"name": "create_... | 2 | stack_v2_sparse_classes_30k_train_000453 | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, email, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, email, password=Non... | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, email, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, email, password=Non... | 0b61f67ce3158cf727d3570daf60bff1b0417360 | <|skeleton|>
class MyUserManager:
def create_user(self, email, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, password=None):
"""Creates and saves a superuser with the given email, date of bi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyUserManager:
def create_user(self, email, 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=self.normalize_email(email))
user.... | the_stack_v2_python_sparse | Business_Coaching_Platform/user/models.py | SDOS2020/Team_1_Business_Coaching_Platform | train | 0 | |
d59f52e8b4a45e98cb06fdfd00dfee331091988e | [
"pic_np = pic_tensor.asnumpy()[0]\nif pic_np.shape[0] == 1:\n pic_np = (pic_np[0] + 1) / 2.0 * 255.0\nelif pic_np.shape[0] == 3:\n pic_np = (np.transpose(pic_np, (1, 2, 0)) + 1) / 2.0 * 255.0\npic = Image.fromarray(pic_np)\npic = pic.convert('RGB')\npic.save(pic_path)\nprint(pic_path + ' is saved.')",
"real... | <|body_start_0|>
pic_np = pic_tensor.asnumpy()[0]
if pic_np.shape[0] == 1:
pic_np = (pic_np[0] + 1) / 2.0 * 255.0
elif pic_np.shape[0] == 3:
pic_np = (np.transpose(pic_np, (1, 2, 0)) + 1) / 2.0 * 255.0
pic = Image.fromarray(pic_np)
pic = pic.convert('RGB')... | Eval | Eval | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Eval:
"""Eval"""
def save_image(pic_tensor, pic_path='test.png'):
"""save image"""
<|body_0|>
def infer_one_image(net, all_data):
"""infer one image"""
<|body_1|>
def expand_tensor_data(data_tensor):
"""expand_tensor_data"""
<|body_2|... | stack_v2_sparse_classes_36k_train_002518 | 4,422 | permissive | [
{
"docstring": "save image",
"name": "save_image",
"signature": "def save_image(pic_tensor, pic_path='test.png')"
},
{
"docstring": "infer one image",
"name": "infer_one_image",
"signature": "def infer_one_image(net, all_data)"
},
{
"docstring": "expand_tensor_data",
"name": ... | 4 | stack_v2_sparse_classes_30k_train_008813 | Implement the Python class `Eval` described below.
Class description:
Eval
Method signatures and docstrings:
- def save_image(pic_tensor, pic_path='test.png'): save image
- def infer_one_image(net, all_data): infer one image
- def expand_tensor_data(data_tensor): expand_tensor_data
- def process_input(all_data, resul... | Implement the Python class `Eval` described below.
Class description:
Eval
Method signatures and docstrings:
- def save_image(pic_tensor, pic_path='test.png'): save image
- def infer_one_image(net, all_data): infer one image
- def expand_tensor_data(data_tensor): expand_tensor_data
- def process_input(all_data, resul... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class Eval:
"""Eval"""
def save_image(pic_tensor, pic_path='test.png'):
"""save image"""
<|body_0|>
def infer_one_image(net, all_data):
"""infer one image"""
<|body_1|>
def expand_tensor_data(data_tensor):
"""expand_tensor_data"""
<|body_2|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Eval:
"""Eval"""
def save_image(pic_tensor, pic_path='test.png'):
"""save image"""
pic_np = pic_tensor.asnumpy()[0]
if pic_np.shape[0] == 1:
pic_np = (pic_np[0] + 1) / 2.0 * 255.0
elif pic_np.shape[0] == 3:
pic_np = (np.transpose(pic_np, (1, 2, 0)) ... | the_stack_v2_python_sparse | research/cv/APDrawingGAN/eval.py | mindspore-ai/models | train | 301 |
1cb1c0347aea92db98ab3ce7b66103e61fa22819 | [
"self.capacity = capacity\nself.length = 0\nself.order = []\nself.map = {}",
"if key not in self.map:\n return -1\nself.order.remove(key)\nself.order.append(key)\nreturn self.map[key]",
"if key in self.map:\n num = self.get(key)\n if num != value:\n self.map[key] = value\nelse:\n if self.leng... | <|body_start_0|>
self.capacity = capacity
self.length = 0
self.order = []
self.map = {}
<|end_body_0|>
<|body_start_1|>
if key not in self.map:
return -1
self.order.remove(key)
self.order.append(key)
return self.map[key]
<|end_body_1|>
<|body... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_002519 | 1,850 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: nothing",
"name": "set",
"sig... | 3 | null | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing
<|skeleton|>
cla... | dda63f5b196bfcdc4062bdad8d47076f36a9d89a | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.length = 0
self.order = []
self.map = {}
def get(self, key):
""":rtype: int"""
if key not in self.map:
return -1
self.order.remove(ke... | the_stack_v2_python_sparse | Bloomberg/146_LRU_Cache.py | bwang8482/LeetCode | train | 1 | |
1ce548568fcf013dd156a760ff701c816c97491d | [
"if identity_arg_names is None:\n identity_arg_names = ('%s_guid' % object_arg_name,)\nelif not isinstance(identity_arg_names, (list, tuple)):\n identity_arg_names = (identity_arg_names,)\n\ndef _resolver(kwargs):\n query_func = model.query.get if return_not_found else model.query.get_or_404\n identity_... | <|body_start_0|>
if identity_arg_names is None:
identity_arg_names = ('%s_guid' % object_arg_name,)
elif not isinstance(identity_arg_names, (list, tuple)):
identity_arg_names = (identity_arg_names,)
def _resolver(kwargs):
query_func = model.query.get if retur... | Having app-specific handlers here. | Namespace | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Namespace:
"""Having app-specific handlers here."""
def resolve_object_by_model(self, model, object_arg_name, identity_arg_names=None, return_not_found=False):
"""A helper decorator to resolve DB record instance by id. Arguments: model (type) - a Flask-SQLAlchemy model class with ``q... | stack_v2_sparse_classes_36k_train_002520 | 5,806 | permissive | [
{
"docstring": "A helper decorator to resolve DB record instance by id. Arguments: model (type) - a Flask-SQLAlchemy model class with ``query.get_or_404`` method object_arg_name (str) - argument name for a resolved object identity_arg_names (tuple) - a list of argument names holding an object identity, by defau... | 4 | stack_v2_sparse_classes_30k_train_001352 | Implement the Python class `Namespace` described below.
Class description:
Having app-specific handlers here.
Method signatures and docstrings:
- def resolve_object_by_model(self, model, object_arg_name, identity_arg_names=None, return_not_found=False): A helper decorator to resolve DB record instance by id. Argument... | Implement the Python class `Namespace` described below.
Class description:
Having app-specific handlers here.
Method signatures and docstrings:
- def resolve_object_by_model(self, model, object_arg_name, identity_arg_names=None, return_not_found=False): A helper decorator to resolve DB record instance by id. Argument... | 821c9cae985751a129b3be1ad08b8ad295d0a3d8 | <|skeleton|>
class Namespace:
"""Having app-specific handlers here."""
def resolve_object_by_model(self, model, object_arg_name, identity_arg_names=None, return_not_found=False):
"""A helper decorator to resolve DB record instance by id. Arguments: model (type) - a Flask-SQLAlchemy model class with ``q... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Namespace:
"""Having app-specific handlers here."""
def resolve_object_by_model(self, model, object_arg_name, identity_arg_names=None, return_not_found=False):
"""A helper decorator to resolve DB record instance by id. Arguments: model (type) - a Flask-SQLAlchemy model class with ``query.get_or_4... | the_stack_v2_python_sparse | app/extensions/api/namespace.py | Emily-Ke/houston | train | 0 |
f412e83c808bc6daa97fb002aec7fe4ed5628b13 | [
"if airflow_vars is None:\n airflow_vars = [AirflowVars.DATA_PATH, AirflowVars.PROJECT_ID, AirflowVars.DATA_LOCATION, AirflowVars.DOWNLOAD_BUCKET, AirflowVars.TRANSFORM_BUCKET]\nif airflow_conns is None:\n airflow_conns = [AirflowConns.OAEBU_SERVICE_ACCOUNT]\nif dag_id is None:\n dag_id = make_dag_id(self.... | <|body_start_0|>
if airflow_vars is None:
airflow_vars = [AirflowVars.DATA_PATH, AirflowVars.PROJECT_ID, AirflowVars.DATA_LOCATION, AirflowVars.DOWNLOAD_BUCKET, AirflowVars.TRANSFORM_BUCKET]
if airflow_conns is None:
airflow_conns = [AirflowConns.OAEBU_SERVICE_ACCOUNT]
if... | Google Analytics Telescope. | GoogleAnalyticsTelescope | [
"Apache-2.0",
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoogleAnalyticsTelescope:
"""Google Analytics Telescope."""
def __init__(self, organisation: Organisation, view_id: str, pagepath_regex: str, dag_id: Optional[str]=None, start_date: pendulum.DateTime=pendulum.datetime(2018, 1, 1), schedule_interval: str='@monthly', dataset_id: str='google', ... | stack_v2_sparse_classes_36k_train_002521 | 20,663 | permissive | [
{
"docstring": "Construct a GoogleAnalyticsTelescope instance. :param organisation: the Organisation of which data is processed. :param view_id: the view ID, obtained from the 'extra' info from the API regarding the telescope. :param pagepath_regex: the pagepath regex expression, obtained from the 'extra' info ... | 4 | stack_v2_sparse_classes_30k_train_020974 | Implement the Python class `GoogleAnalyticsTelescope` described below.
Class description:
Google Analytics Telescope.
Method signatures and docstrings:
- def __init__(self, organisation: Organisation, view_id: str, pagepath_regex: str, dag_id: Optional[str]=None, start_date: pendulum.DateTime=pendulum.datetime(2018, ... | Implement the Python class `GoogleAnalyticsTelescope` described below.
Class description:
Google Analytics Telescope.
Method signatures and docstrings:
- def __init__(self, organisation: Organisation, view_id: str, pagepath_regex: str, dag_id: Optional[str]=None, start_date: pendulum.DateTime=pendulum.datetime(2018, ... | 5ba454bf5e1cb64b80719ac971ebf6214568faa1 | <|skeleton|>
class GoogleAnalyticsTelescope:
"""Google Analytics Telescope."""
def __init__(self, organisation: Organisation, view_id: str, pagepath_regex: str, dag_id: Optional[str]=None, start_date: pendulum.DateTime=pendulum.datetime(2018, 1, 1), schedule_interval: str='@monthly', dataset_id: str='google', ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GoogleAnalyticsTelescope:
"""Google Analytics Telescope."""
def __init__(self, organisation: Organisation, view_id: str, pagepath_regex: str, dag_id: Optional[str]=None, start_date: pendulum.DateTime=pendulum.datetime(2018, 1, 1), schedule_interval: str='@monthly', dataset_id: str='google', schema_folder... | the_stack_v2_python_sparse | oaebu_workflows/workflows/google_analytics_telescope.py | The-Academic-Observatory/oaebu-workflows | train | 7 |
b193964771e915d36308ed16fb9105f49ee8ca8b | [
"Parametre.__init__(self, 'descendre', 'lower')\nself.schema = '<texte_libre>'\nself.aide_courte = 'descend un canot'\nself.aide_longue = \"Cette commande permet de descendre un canot qui se trouve sur le pont du navire où vous vous trouvez. Vous devez vous tenir près d'un bossoir, permettant de faire descendre le ... | <|body_start_0|>
Parametre.__init__(self, 'descendre', 'lower')
self.schema = '<texte_libre>'
self.aide_courte = 'descend un canot'
self.aide_longue = "Cette commande permet de descendre un canot qui se trouve sur le pont du navire où vous vous trouvez. Vous devez vous tenir près d'un bo... | Commande 'canot descendre'. | PrmDescendre | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmDescendre:
"""Commande 'canot descendre'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Parame... | stack_v2_sparse_classes_36k_train_002522 | 3,513 | permissive | [
{
"docstring": "Constructeur du paramètre",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Interprétation du paramètre.",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | null | Implement the Python class `PrmDescendre` described below.
Class description:
Commande 'canot descendre'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre. | Implement the Python class `PrmDescendre` described below.
Class description:
Commande 'canot descendre'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre.
<|skeleton|>
class PrmDescendre:
"""Commande '... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmDescendre:
"""Commande 'canot descendre'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrmDescendre:
"""Commande 'canot descendre'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'descendre', 'lower')
self.schema = '<texte_libre>'
self.aide_courte = 'descend un canot'
self.aide_longue = "Cette commande permet de desce... | the_stack_v2_python_sparse | src/secondaires/navigation/commandes/canot/descendre.py | vincent-lg/tsunami | train | 5 |
86d69c3485cf4306cdf942f421fa0c90b9c464a9 | [
"data = super().get_context_data(*args, **kwargs)\ndata['project'] = get_object_or_404(Project, pk=self.kwargs['pk'])\nreturn data",
"pk = self.kwargs['pk']\nfilesource = form.save(commit=False)\nfilesource.project = get_object_or_404(Project, pk=pk)\nfilesource.save()\nreturn HttpResponseRedirect(reverse('projec... | <|body_start_0|>
data = super().get_context_data(*args, **kwargs)
data['project'] = get_object_or_404(Project, pk=self.kwargs['pk'])
return data
<|end_body_0|>
<|body_start_1|>
pk = self.kwargs['pk']
filesource = form.save(commit=False)
filesource.project = get_object_or... | A base class for view for creating new project sources | SourceCreateView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SourceCreateView:
"""A base class for view for creating new project sources"""
def get_context_data(self, *args, **kwargs):
"""Override to add project to the template context"""
<|body_0|>
def form_valid(self, form):
"""Override to set the project for the `Source... | stack_v2_sparse_classes_36k_train_002523 | 3,269 | permissive | [
{
"docstring": "Override to add project to the template context",
"name": "get_context_data",
"signature": "def get_context_data(self, *args, **kwargs)"
},
{
"docstring": "Override to set the project for the `Source` and redirect back to that project",
"name": "form_valid",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_012239 | Implement the Python class `SourceCreateView` described below.
Class description:
A base class for view for creating new project sources
Method signatures and docstrings:
- def get_context_data(self, *args, **kwargs): Override to add project to the template context
- def form_valid(self, form): Override to set the pr... | Implement the Python class `SourceCreateView` described below.
Class description:
A base class for view for creating new project sources
Method signatures and docstrings:
- def get_context_data(self, *args, **kwargs): Override to add project to the template context
- def form_valid(self, form): Override to set the pr... | ce5d86343e340ff0bd734e49a48d0745ae88144d | <|skeleton|>
class SourceCreateView:
"""A base class for view for creating new project sources"""
def get_context_data(self, *args, **kwargs):
"""Override to add project to the template context"""
<|body_0|>
def form_valid(self, form):
"""Override to set the project for the `Source... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SourceCreateView:
"""A base class for view for creating new project sources"""
def get_context_data(self, *args, **kwargs):
"""Override to add project to the template context"""
data = super().get_context_data(*args, **kwargs)
data['project'] = get_object_or_404(Project, pk=self.k... | the_stack_v2_python_sparse | director/projects/source_views.py | paulolimac/hub | train | 0 |
5f23d37bf30819ea0fb18dc4e26c56e798597c25 | [
"if nums is None or len(nums) == 0:\n return 0\nmax_sum = nums[0]\ndp = [0] * len(nums)\ndp[0] = nums[0]\nfor i, v in enumerate(nums):\n if i == 0:\n continue\n if v >= 0:\n dp[i] = dp[i - 1] + v if dp[i - 1] > 0 else v\n else:\n dp[i] = dp[i - 1] + v if dp[i - 1] + v > 0 else v\n ... | <|body_start_0|>
if nums is None or len(nums) == 0:
return 0
max_sum = nums[0]
dp = [0] * len(nums)
dp[0] = nums[0]
for i, v in enumerate(nums):
if i == 0:
continue
if v >= 0:
dp[i] = dp[i - 1] + v if dp[i - 1] >... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maxSubArray2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if nums is None or len(nums) == 0:
... | stack_v2_sparse_classes_36k_train_002524 | 1,895 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maxSubArray",
"signature": "def maxSubArray(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maxSubArray2",
"signature": "def maxSubArray2(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray(self, nums): :type nums: List[int] :rtype: int
- def maxSubArray2(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray(self, nums): :type nums: List[int] :rtype: int
- def maxSubArray2(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxSubArra... | 4aa3a3a0da8b911e140446352debb9b567b6d78b | <|skeleton|>
class Solution:
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maxSubArray2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
if nums is None or len(nums) == 0:
return 0
max_sum = nums[0]
dp = [0] * len(nums)
dp[0] = nums[0]
for i, v in enumerate(nums):
if i == 0:
cont... | the_stack_v2_python_sparse | maximum_subarray_53.py | adiggo/leetcode_py | train | 0 | |
d13f8f8bc0237b3c58757a1716f49f4d7bd34c21 | [
"form = ExchangeForm(request.POST)\nif not form.is_valid():\n messages.add_message(request, messages.ERROR, 'Failed to create new exchange account')\n return redirect('{}#accounts'.format(reverse('index')))\nelse:\n exchange_account = form.save(commit=False)\n exchange_account.owner = request.user\n ... | <|body_start_0|>
form = ExchangeForm(request.POST)
if not form.is_valid():
messages.add_message(request, messages.ERROR, 'Failed to create new exchange account')
return redirect('{}#accounts'.format(reverse('index')))
else:
exchange_account = form.save(commit=... | ExchangeAccount | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExchangeAccount:
def post(request):
"""Create Exchange Account"""
<|body_0|>
def get(request, pk):
"""Delete Exchange account"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
form = ExchangeForm(request.POST)
if not form.is_valid():
... | stack_v2_sparse_classes_36k_train_002525 | 2,209 | permissive | [
{
"docstring": "Create Exchange Account",
"name": "post",
"signature": "def post(request)"
},
{
"docstring": "Delete Exchange account",
"name": "get",
"signature": "def get(request, pk)"
}
] | 2 | null | Implement the Python class `ExchangeAccount` described below.
Class description:
Implement the ExchangeAccount class.
Method signatures and docstrings:
- def post(request): Create Exchange Account
- def get(request, pk): Delete Exchange account | Implement the Python class `ExchangeAccount` described below.
Class description:
Implement the ExchangeAccount class.
Method signatures and docstrings:
- def post(request): Create Exchange Account
- def get(request, pk): Delete Exchange account
<|skeleton|>
class ExchangeAccount:
def post(request):
"""C... | 2f0c9f73c9f6aa4d415429c79b58e15baa312f26 | <|skeleton|>
class ExchangeAccount:
def post(request):
"""Create Exchange Account"""
<|body_0|>
def get(request, pk):
"""Delete Exchange account"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExchangeAccount:
def post(request):
"""Create Exchange Account"""
form = ExchangeForm(request.POST)
if not form.is_valid():
messages.add_message(request, messages.ERROR, 'Failed to create new exchange account')
return redirect('{}#accounts'.format(reverse('index... | the_stack_v2_python_sparse | overwatch/views/accounts.py | inuitwallet/overwatch | train | 2 | |
df53ef60e254b0cbfd7a318d6b5276cbacfa0e50 | [
"_query_builder = Configuration.get_base_uri()\n_query_builder += '/information/business/info/matchit'\n_query_parameters = {'companyname': companyname, 'orgnumber': orgnumber}\n_query_builder = APIHelper.append_url_with_query_parameters(_query_builder, _query_parameters, Configuration.array_serialization)\n_query_... | <|body_start_0|>
_query_builder = Configuration.get_base_uri()
_query_builder += '/information/business/info/matchit'
_query_parameters = {'companyname': companyname, 'orgnumber': orgnumber}
_query_builder = APIHelper.append_url_with_query_parameters(_query_builder, _query_parameters, Co... | A Controller to access Endpoints in the idfy_rest_client API. | BusinessController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BusinessController:
"""A Controller to access Endpoints in the idfy_rest_client API."""
def retrieve_information_from_matchit(self, companyname=None, orgnumber=None):
"""Does a GET request to /information/business/info/matchit. Query company information from Matchit, Matchit uses exi... | stack_v2_sparse_classes_36k_train_002526 | 8,448 | permissive | [
{
"docstring": "Does a GET request to /information/business/info/matchit. Query company information from Matchit, Matchit uses existing information to build up their database. Supports query by name and/or orgnumber Args: companyname (string, optional): query param orgnumber (string, optional): query param Retu... | 3 | stack_v2_sparse_classes_30k_train_019459 | Implement the Python class `BusinessController` described below.
Class description:
A Controller to access Endpoints in the idfy_rest_client API.
Method signatures and docstrings:
- def retrieve_information_from_matchit(self, companyname=None, orgnumber=None): Does a GET request to /information/business/info/matchit.... | Implement the Python class `BusinessController` described below.
Class description:
A Controller to access Endpoints in the idfy_rest_client API.
Method signatures and docstrings:
- def retrieve_information_from_matchit(self, companyname=None, orgnumber=None): Does a GET request to /information/business/info/matchit.... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class BusinessController:
"""A Controller to access Endpoints in the idfy_rest_client API."""
def retrieve_information_from_matchit(self, companyname=None, orgnumber=None):
"""Does a GET request to /information/business/info/matchit. Query company information from Matchit, Matchit uses exi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BusinessController:
"""A Controller to access Endpoints in the idfy_rest_client API."""
def retrieve_information_from_matchit(self, companyname=None, orgnumber=None):
"""Does a GET request to /information/business/info/matchit. Query company information from Matchit, Matchit uses existing informa... | the_stack_v2_python_sparse | idfy_rest_client/controllers/business_controller.py | dealflowteam/Idfy | train | 0 |
42c5717ec3796500e126ec84009e856dbee092ee | [
"params = ParamsParser(request.GET)\nlimit = params.int('limit', desc='每页最大渲染数', require=False, default=10)\npage = params.int('page', desc='当前页数', require=False, default=1)\naccounts = FaceUAccount.objects.values('id', 'update_time', 'nickname')\nif params.has('nickname'):\n accounts = accounts.filter(nickname_... | <|body_start_0|>
params = ParamsParser(request.GET)
limit = params.int('limit', desc='每页最大渲染数', require=False, default=10)
page = params.int('page', desc='当前页数', require=False, default=1)
accounts = FaceUAccount.objects.values('id', 'update_time', 'nickname')
if params.has('nickn... | FaceUAccountListMget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FaceUAccountListMget:
def get(self, request):
"""获取用户列表 :param request: :return:"""
<|body_0|>
def post(self, request):
"""批量获取用户信息 :param request: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
params = ParamsParser(request.GET)
l... | stack_v2_sparse_classes_36k_train_002527 | 1,743 | no_license | [
{
"docstring": "获取用户列表 :param request: :return:",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "批量获取用户信息 :param request: :return:",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | null | Implement the Python class `FaceUAccountListMget` described below.
Class description:
Implement the FaceUAccountListMget class.
Method signatures and docstrings:
- def get(self, request): 获取用户列表 :param request: :return:
- def post(self, request): 批量获取用户信息 :param request: :return: | Implement the Python class `FaceUAccountListMget` described below.
Class description:
Implement the FaceUAccountListMget class.
Method signatures and docstrings:
- def get(self, request): 获取用户列表 :param request: :return:
- def post(self, request): 批量获取用户信息 :param request: :return:
<|skeleton|>
class FaceUAccountListM... | 7467cd66e1fc91f0b3a264f8fc9b93f22f09fe7b | <|skeleton|>
class FaceUAccountListMget:
def get(self, request):
"""获取用户列表 :param request: :return:"""
<|body_0|>
def post(self, request):
"""批量获取用户信息 :param request: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FaceUAccountListMget:
def get(self, request):
"""获取用户列表 :param request: :return:"""
params = ParamsParser(request.GET)
limit = params.int('limit', desc='每页最大渲染数', require=False, default=10)
page = params.int('page', desc='当前页数', require=False, default=1)
accounts = Face... | the_stack_v2_python_sparse | FireHydrant/server/faceU/views/accounts/list_mget.py | shoogoome/FireHydrant | train | 4 | |
02a5677fecdc1ec62441462a5da234b12d4b0e81 | [
"attr = handler_input.attributes_manager.session_attributes\nmode = attr['mode']\nmode_stats = attr.get('mode_stats', dict())\nif mode not in mode_stats.keys():\n mode_stats[mode] = [0, 0]\nmode_correct, mode_incorrect = mode_stats[mode]\nif correct:\n mode_correct = int(mode_correct) + 1\nelse:\n mode_inc... | <|body_start_0|>
attr = handler_input.attributes_manager.session_attributes
mode = attr['mode']
mode_stats = attr.get('mode_stats', dict())
if mode not in mode_stats.keys():
mode_stats[mode] = [0, 0]
mode_correct, mode_incorrect = mode_stats[mode]
if correct:
... | ModeStats | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModeStats:
def update_mode_stats(handler_input, correct: bool) -> None:
"""Updates mode_stats depending on correct."""
<|body_0|>
def get_mode_stats(handler_input, mode: str) -> tuple:
"""Returns a tuple (int, int) of the mode statistics."""
<|body_1|>
d... | stack_v2_sparse_classes_36k_train_002528 | 2,644 | permissive | [
{
"docstring": "Updates mode_stats depending on correct.",
"name": "update_mode_stats",
"signature": "def update_mode_stats(handler_input, correct: bool) -> None"
},
{
"docstring": "Returns a tuple (int, int) of the mode statistics.",
"name": "get_mode_stats",
"signature": "def get_mode_... | 3 | null | Implement the Python class `ModeStats` described below.
Class description:
Implement the ModeStats class.
Method signatures and docstrings:
- def update_mode_stats(handler_input, correct: bool) -> None: Updates mode_stats depending on correct.
- def get_mode_stats(handler_input, mode: str) -> tuple: Returns a tuple (... | Implement the Python class `ModeStats` described below.
Class description:
Implement the ModeStats class.
Method signatures and docstrings:
- def update_mode_stats(handler_input, correct: bool) -> None: Updates mode_stats depending on correct.
- def get_mode_stats(handler_input, mode: str) -> tuple: Returns a tuple (... | 1072dea1a5be0b339211ff39db6a89a90aca64c1 | <|skeleton|>
class ModeStats:
def update_mode_stats(handler_input, correct: bool) -> None:
"""Updates mode_stats depending on correct."""
<|body_0|>
def get_mode_stats(handler_input, mode: str) -> tuple:
"""Returns a tuple (int, int) of the mode statistics."""
<|body_1|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModeStats:
def update_mode_stats(handler_input, correct: bool) -> None:
"""Updates mode_stats depending on correct."""
attr = handler_input.attributes_manager.session_attributes
mode = attr['mode']
mode_stats = attr.get('mode_stats', dict())
if mode not in mode_stats.ke... | the_stack_v2_python_sparse | 1_code/stats/mode_stats.py | jaimiles23/Multiplication-Medley | train | 0 | |
b27a31f55ab05efcd34f94cdf942883baba8b4ec | [
"self.reqpaser = reqparse.RequestParser()\nself.reqpaser.add_argument('id', type=int, required=False, store_missing=False)\nself.reqpaser.add_argument('attribute_id', type=str, required=False, store_missing=False)\nself.reqpaser.add_argument('user_id', type=int, required=False, store_missing=False)",
"args = self... | <|body_start_0|>
self.reqpaser = reqparse.RequestParser()
self.reqpaser.add_argument('id', type=int, required=False, store_missing=False)
self.reqpaser.add_argument('attribute_id', type=str, required=False, store_missing=False)
self.reqpaser.add_argument('user_id', type=int, required=Fal... | Delete Attribute Alias | DeleteAttributeAlias | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteAttributeAlias:
"""Delete Attribute Alias"""
def __init__(self) -> None:
"""Set reqpase arguments"""
<|body_0|>
def post(self) -> ({str: str}, HTTPStatus):
"""Delete Attribute Alias :param id: Attribute Alias id :param attribute_id: Parent Attribute id :par... | stack_v2_sparse_classes_36k_train_002529 | 1,906 | permissive | [
{
"docstring": "Set reqpase arguments",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Delete Attribute Alias :param id: Attribute Alias id :param attribute_id: Parent Attribute id :param user_id: Current User id :return: No content with an HTTPstatus code NoCon... | 2 | null | Implement the Python class `DeleteAttributeAlias` described below.
Class description:
Delete Attribute Alias
Method signatures and docstrings:
- def __init__(self) -> None: Set reqpase arguments
- def post(self) -> ({str: str}, HTTPStatus): Delete Attribute Alias :param id: Attribute Alias id :param attribute_id: Par... | Implement the Python class `DeleteAttributeAlias` described below.
Class description:
Delete Attribute Alias
Method signatures and docstrings:
- def __init__(self) -> None: Set reqpase arguments
- def post(self) -> ({str: str}, HTTPStatus): Delete Attribute Alias :param id: Attribute Alias id :param attribute_id: Par... | 5d123691d1f25d0b85e20e4e8293266bf23c9f8a | <|skeleton|>
class DeleteAttributeAlias:
"""Delete Attribute Alias"""
def __init__(self) -> None:
"""Set reqpase arguments"""
<|body_0|>
def post(self) -> ({str: str}, HTTPStatus):
"""Delete Attribute Alias :param id: Attribute Alias id :param attribute_id: Parent Attribute id :par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeleteAttributeAlias:
"""Delete Attribute Alias"""
def __init__(self) -> None:
"""Set reqpase arguments"""
self.reqpaser = reqparse.RequestParser()
self.reqpaser.add_argument('id', type=int, required=False, store_missing=False)
self.reqpaser.add_argument('attribute_id', ty... | the_stack_v2_python_sparse | Analytics/resources/attributes/delete_attribute_alias.py | thanosbnt/SharingCitiesDashboard | train | 0 |
3e9c41be92ca294f5dee64505134d7be8a947390 | [
"super().__init__()\nself.conv_pool = list()\nself.conv_pool.append(nn.Conv2d(ch_in, ch_in, kernel_size=3, stride=2, padding=1, bias=True))\nif act_fun == 'relu':\n self.conv_pool.append(nn.ReLU(inplace=True))\nelif act_fun == 'leakyrelu':\n self.conv_pool.append(nn.LeakyReLU(inplace=True))\nelif act_fun == '... | <|body_start_0|>
super().__init__()
self.conv_pool = list()
self.conv_pool.append(nn.Conv2d(ch_in, ch_in, kernel_size=3, stride=2, padding=1, bias=True))
if act_fun == 'relu':
self.conv_pool.append(nn.ReLU(inplace=True))
elif act_fun == 'leakyrelu':
self.c... | ConvPool | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvPool:
def __init__(self, ch_in, act_fun, normalization):
""":param ch_in: :param act_fun: :param normalization:"""
<|body_0|>
def forward(self, x):
""":param x: Block input (image or feature maps). :type x: :return: Block output (feature maps)."""
<|body_... | stack_v2_sparse_classes_36k_train_002530 | 1,607 | permissive | [
{
"docstring": ":param ch_in: :param act_fun: :param normalization:",
"name": "__init__",
"signature": "def __init__(self, ch_in, act_fun, normalization)"
},
{
"docstring": ":param x: Block input (image or feature maps). :type x: :return: Block output (feature maps).",
"name": "forward",
... | 2 | stack_v2_sparse_classes_30k_train_015570 | Implement the Python class `ConvPool` described below.
Class description:
Implement the ConvPool class.
Method signatures and docstrings:
- def __init__(self, ch_in, act_fun, normalization): :param ch_in: :param act_fun: :param normalization:
- def forward(self, x): :param x: Block input (image or feature maps). :typ... | Implement the Python class `ConvPool` described below.
Class description:
Implement the ConvPool class.
Method signatures and docstrings:
- def __init__(self, ch_in, act_fun, normalization): :param ch_in: :param act_fun: :param normalization:
- def forward(self, x): :param x: Block input (image or feature maps). :typ... | f979c3bbc7497e9b3425df425bc5cffddf229cac | <|skeleton|>
class ConvPool:
def __init__(self, ch_in, act_fun, normalization):
""":param ch_in: :param act_fun: :param normalization:"""
<|body_0|>
def forward(self, x):
""":param x: Block input (image or feature maps). :type x: :return: Block output (feature maps)."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvPool:
def __init__(self, ch_in, act_fun, normalization):
""":param ch_in: :param act_fun: :param normalization:"""
super().__init__()
self.conv_pool = list()
self.conv_pool.append(nn.Conv2d(ch_in, ch_in, kernel_size=3, stride=2, padding=1, bias=True))
if act_fun == ... | the_stack_v2_python_sparse | segmentation/customs/pooling_layers.py | khanhhoaa19/thyroidclassification | train | 0 | |
0b0271b3c93d07971a8f79373fa531494dd632f2 | [
"if cls.get_by_id(score_category):\n raise Exception('There already exists an instance with the given id: %s' % score_category)\ncls(id=score_category, current_position_in_rotation=user_id).put()",
"instance = cls.get_by_id(score_category)\nif instance is None:\n cls.create(score_category, user_id)\nelse:\n... | <|body_start_0|>
if cls.get_by_id(score_category):
raise Exception('There already exists an instance with the given id: %s' % score_category)
cls(id=score_category, current_position_in_rotation=user_id).put()
<|end_body_0|>
<|body_start_1|>
instance = cls.get_by_id(score_category)
... | Model to keep track of the position in the reviewer rotation. This model is keyed by the score category. | ReviewerRotationTrackingModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReviewerRotationTrackingModel:
"""Model to keep track of the position in the reviewer rotation. This model is keyed by the score category."""
def create(cls, score_category, user_id):
"""Creates a new ReviewerRotationTrackingModel instance. Args: score_category: str. The score catego... | stack_v2_sparse_classes_36k_train_002531 | 11,112 | permissive | [
{
"docstring": "Creates a new ReviewerRotationTrackingModel instance. Args: score_category: str. The score category. user_id: str. The ID of the user who completed their turn in the rotation for the given category. Raises: Exception: There is already an instance with the given id.",
"name": "create",
"s... | 2 | null | Implement the Python class `ReviewerRotationTrackingModel` described below.
Class description:
Model to keep track of the position in the reviewer rotation. This model is keyed by the score category.
Method signatures and docstrings:
- def create(cls, score_category, user_id): Creates a new ReviewerRotationTrackingMo... | Implement the Python class `ReviewerRotationTrackingModel` described below.
Class description:
Model to keep track of the position in the reviewer rotation. This model is keyed by the score category.
Method signatures and docstrings:
- def create(cls, score_category, user_id): Creates a new ReviewerRotationTrackingMo... | 899b9755a6b795a8991e596055ac24065a8435e0 | <|skeleton|>
class ReviewerRotationTrackingModel:
"""Model to keep track of the position in the reviewer rotation. This model is keyed by the score category."""
def create(cls, score_category, user_id):
"""Creates a new ReviewerRotationTrackingModel instance. Args: score_category: str. The score catego... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReviewerRotationTrackingModel:
"""Model to keep track of the position in the reviewer rotation. This model is keyed by the score category."""
def create(cls, score_category, user_id):
"""Creates a new ReviewerRotationTrackingModel instance. Args: score_category: str. The score category. user_id: ... | the_stack_v2_python_sparse | core/storage/suggestion/gae_models.py | import-keshav/oppia | train | 4 |
0e691ac7febb18c3510ed79ef05ee2592ef4e926 | [
"super(EncoderPrenet, self).__init__()\nself.embedding_size = embedding_size\nself.conv1 = Conv(in_channels=embedding_size, out_channels=num_hidden, kernel_size=5, padding=int(np.floor(5 / 2)), w_init='relu')\nself.conv2 = Conv(in_channels=num_hidden, out_channels=num_hidden, kernel_size=5, padding=int(np.floor(5 /... | <|body_start_0|>
super(EncoderPrenet, self).__init__()
self.embedding_size = embedding_size
self.conv1 = Conv(in_channels=embedding_size, out_channels=num_hidden, kernel_size=5, padding=int(np.floor(5 / 2)), w_init='relu')
self.conv2 = Conv(in_channels=num_hidden, out_channels=num_hidden... | Pre-network for Encoder consists of convolution networks. | EncoderPrenet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderPrenet:
"""Pre-network for Encoder consists of convolution networks."""
def __init__(self, embedding_size, num_hidden):
"""init."""
<|body_0|>
def forward(self, input_):
"""forward."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(En... | stack_v2_sparse_classes_36k_train_002532 | 17,934 | permissive | [
{
"docstring": "init.",
"name": "__init__",
"signature": "def __init__(self, embedding_size, num_hidden)"
},
{
"docstring": "forward.",
"name": "forward",
"signature": "def forward(self, input_)"
}
] | 2 | null | Implement the Python class `EncoderPrenet` described below.
Class description:
Pre-network for Encoder consists of convolution networks.
Method signatures and docstrings:
- def __init__(self, embedding_size, num_hidden): init.
- def forward(self, input_): forward. | Implement the Python class `EncoderPrenet` described below.
Class description:
Pre-network for Encoder consists of convolution networks.
Method signatures and docstrings:
- def __init__(self, embedding_size, num_hidden): init.
- def forward(self, input_): forward.
<|skeleton|>
class EncoderPrenet:
"""Pre-network... | 31d50b1ea1dea92f4182c5b2b6fe9fe4c981ae39 | <|skeleton|>
class EncoderPrenet:
"""Pre-network for Encoder consists of convolution networks."""
def __init__(self, embedding_size, num_hidden):
"""init."""
<|body_0|>
def forward(self, input_):
"""forward."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EncoderPrenet:
"""Pre-network for Encoder consists of convolution networks."""
def __init__(self, embedding_size, num_hidden):
"""init."""
super(EncoderPrenet, self).__init__()
self.embedding_size = embedding_size
self.conv1 = Conv(in_channels=embedding_size, out_channels=... | the_stack_v2_python_sparse | SVS/model/layers/pretrain_module.py | SJTMusicTeam/SVS_system | train | 85 |
e8f52c2928a3956df0c89ab142c49eaa63b78e9b | [
"if not isinstance(blur_type, str):\n raise TypeError('Bad type for arg blur_type - expected string. Received type \"%s\".' % type(blur_type).__name__)\nself.blur_type = blur_type\nself.kernel_size = kernel_size",
"if self.blur_type == 'gaussian':\n return self.gaussianBlur(image, self.kernel_size)\nelif se... | <|body_start_0|>
if not isinstance(blur_type, str):
raise TypeError('Bad type for arg blur_type - expected string. Received type "%s".' % type(blur_type).__name__)
self.blur_type = blur_type
self.kernel_size = kernel_size
<|end_body_0|>
<|body_start_1|>
if self.blur_type == ... | The blur is responsible for applying different blur techniques to the images passed. | BlurManager | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlurManager:
"""The blur is responsible for applying different blur techniques to the images passed."""
def __init__(self, blur_type, kernel_size):
"""Initialise Blur Manager. :param blur_type (str): Indicates the type of blur operation that should be applied to the image. :param ker... | stack_v2_sparse_classes_36k_train_002533 | 4,986 | permissive | [
{
"docstring": "Initialise Blur Manager. :param blur_type (str): Indicates the type of blur operation that should be applied to the image. :param kernel_size (int tuple): Indicates the kernel size for blurring operations. Raises: - TypeError: If a none string value is passed for blur_type.",
"name": "__init... | 5 | stack_v2_sparse_classes_30k_train_006448 | Implement the Python class `BlurManager` described below.
Class description:
The blur is responsible for applying different blur techniques to the images passed.
Method signatures and docstrings:
- def __init__(self, blur_type, kernel_size): Initialise Blur Manager. :param blur_type (str): Indicates the type of blur ... | Implement the Python class `BlurManager` described below.
Class description:
The blur is responsible for applying different blur techniques to the images passed.
Method signatures and docstrings:
- def __init__(self, blur_type, kernel_size): Initialise Blur Manager. :param blur_type (str): Indicates the type of blur ... | d62917262080f09d7c9e7262f507e2c1482d7c56 | <|skeleton|>
class BlurManager:
"""The blur is responsible for applying different blur techniques to the images passed."""
def __init__(self, blur_type, kernel_size):
"""Initialise Blur Manager. :param blur_type (str): Indicates the type of blur operation that should be applied to the image. :param ker... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BlurManager:
"""The blur is responsible for applying different blur techniques to the images passed."""
def __init__(self, blur_type, kernel_size):
"""Initialise Blur Manager. :param blur_type (str): Indicates the type of blur operation that should be applied to the image. :param kernel_size (int... | the_stack_v2_python_sparse | src/main/python/hutts_verification/image_preprocessing/blur_manager.py | javaTheHutts/Java-the-Hutts | train | 2 |
c06026d12de91c870b697d903c8fca850c17a0dd | [
"def dfs(node, string):\n if not node:\n string += 'None,'\n else:\n string += f'{node.val},'\n string = dfs(node.left, string)\n string = dfs(node.right, string)\n return string\nreturn dfs(root, '')",
"def dfs(nodes):\n if nodes[0] == 'None':\n nodes.pop(0)\n ... | <|body_start_0|>
def dfs(node, string):
if not node:
string += 'None,'
else:
string += f'{node.val},'
string = dfs(node.left, string)
string = dfs(node.right, string)
return string
return dfs(root, '')
<|... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_002534 | 4,308 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 647fea5d2c8122468a1c018c6829b1c08717d86a | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def dfs(node, string):
if not node:
string += 'None,'
else:
string += f'{node.val},'
string = dfs(node.left, strin... | the_stack_v2_python_sparse | LeetCode/facebook/top_facebook_questions/serialize_and_deserialize_binary_tree.py | jinurajan/Datastructures | train | 0 | |
38428b8e3bfb318256e1e263a325a904a7401313 | [
"self.tts = tts\nself.stt = stt\nself.prompt = None",
"general_actions = GenericDevice().action_names()\nif input_.prefix_from(general_actions, pop_if_true=False):\n return GenericDevice(context=context)\nif context is not None and context.get('device'):\n device_name = context['device']\nelse:\n device_... | <|body_start_0|>
self.tts = tts
self.stt = stt
self.prompt = None
<|end_body_0|>
<|body_start_1|>
general_actions = GenericDevice().action_names()
if input_.prefix_from(general_actions, pop_if_true=False):
return GenericDevice(context=context)
if context is n... | Main driver for the voice activated commands | VUI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VUI:
"""Main driver for the voice activated commands"""
def __init__(self, tts: TextToSpeech, stt: SpeechToText):
""":param tts: Text to speech object :param stt: Speech to text object"""
<|body_0|>
def device_from(self, input_: CommandParser, context) -> Device:
... | stack_v2_sparse_classes_36k_train_002535 | 6,403 | permissive | [
{
"docstring": ":param tts: Text to speech object :param stt: Speech to text object",
"name": "__init__",
"signature": "def __init__(self, tts: TextToSpeech, stt: SpeechToText)"
},
{
"docstring": "Returns the Device to use based on the input string and current context :param input_: CommandParse... | 5 | stack_v2_sparse_classes_30k_train_009819 | Implement the Python class `VUI` described below.
Class description:
Main driver for the voice activated commands
Method signatures and docstrings:
- def __init__(self, tts: TextToSpeech, stt: SpeechToText): :param tts: Text to speech object :param stt: Speech to text object
- def device_from(self, input_: CommandPar... | Implement the Python class `VUI` described below.
Class description:
Main driver for the voice activated commands
Method signatures and docstrings:
- def __init__(self, tts: TextToSpeech, stt: SpeechToText): :param tts: Text to speech object :param stt: Speech to text object
- def device_from(self, input_: CommandPar... | 36c8d07feecfb0166f0125585e109b1b357c4519 | <|skeleton|>
class VUI:
"""Main driver for the voice activated commands"""
def __init__(self, tts: TextToSpeech, stt: SpeechToText):
""":param tts: Text to speech object :param stt: Speech to text object"""
<|body_0|>
def device_from(self, input_: CommandParser, context) -> Device:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VUI:
"""Main driver for the voice activated commands"""
def __init__(self, tts: TextToSpeech, stt: SpeechToText):
""":param tts: Text to speech object :param stt: Speech to text object"""
self.tts = tts
self.stt = stt
self.prompt = None
def device_from(self, input_: C... | the_stack_v2_python_sparse | smart_home_hub/vui/vui_thread.py | rsmith49/smart_home_hub | train | 0 |
b289e1fb8cb63905a33774a47eabdd4b8ad2a4f5 | [
"try:\n start, end = user_utils.local_day_range(user)\n obj = self.filter(user=user, created_on__range=(start, end)).get()\n return obj.id\nexcept self.model.DoesNotExist:\n return None",
"start, end = user_utils.local_day_range(user)\ntry:\n obj = self.get(user=user, created_on__range=(start, end)... | <|body_start_0|>
try:
start, end = user_utils.local_day_range(user)
obj = self.filter(user=user, created_on__range=(start, end)).get()
return obj.id
except self.model.DoesNotExist:
return None
<|end_body_0|>
<|body_start_1|>
start, end = user_util... | DailyProgressManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DailyProgressManager:
def exists_today(self, user):
"""Check to see if there's already a progress object for today. If so, return it's ID (or None)"""
<|body_0|>
def for_today(self, user):
"""Get/Create the current day's DailyProgress instance for the user"""
... | stack_v2_sparse_classes_36k_train_002536 | 21,796 | permissive | [
{
"docstring": "Check to see if there's already a progress object for today. If so, return it's ID (or None)",
"name": "exists_today",
"signature": "def exists_today(self, user)"
},
{
"docstring": "Get/Create the current day's DailyProgress instance for the user",
"name": "for_today",
"s... | 3 | null | Implement the Python class `DailyProgressManager` described below.
Class description:
Implement the DailyProgressManager class.
Method signatures and docstrings:
- def exists_today(self, user): Check to see if there's already a progress object for today. If so, return it's ID (or None)
- def for_today(self, user): Ge... | Implement the Python class `DailyProgressManager` described below.
Class description:
Implement the DailyProgressManager class.
Method signatures and docstrings:
- def exists_today(self, user): Check to see if there's already a progress object for today. If so, return it's ID (or None)
- def for_today(self, user): Ge... | 3d22179c581ab3da18900483930d5ecc0a5fca73 | <|skeleton|>
class DailyProgressManager:
def exists_today(self, user):
"""Check to see if there's already a progress object for today. If so, return it's ID (or None)"""
<|body_0|>
def for_today(self, user):
"""Get/Create the current day's DailyProgress instance for the user"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DailyProgressManager:
def exists_today(self, user):
"""Check to see if there's already a progress object for today. If so, return it's ID (or None)"""
try:
start, end = user_utils.local_day_range(user)
obj = self.filter(user=user, created_on__range=(start, end)).get()
... | the_stack_v2_python_sparse | tndata_backend/goals/managers.py | tndatacommons/tndata_backend | train | 1 | |
10d2c8981f29db5dc510de2042c75ba212bcdda2 | [
"self.comment = backwards.unicode2bytes(comment)\nkwargs.setdefault('read_meth', 'readline')\nsuper(AsciiFileComm, self)._init_before_open(**kwargs)",
"kwargs = super(AsciiFileComm, self).opp_comm_kwargs()\nkwargs['comment'] = self.comment\nreturn kwargs",
"flag, msg = super(AsciiFileComm, self)._recv()\nif sel... | <|body_start_0|>
self.comment = backwards.unicode2bytes(comment)
kwargs.setdefault('read_meth', 'readline')
super(AsciiFileComm, self)._init_before_open(**kwargs)
<|end_body_0|>
<|body_start_1|>
kwargs = super(AsciiFileComm, self).opp_comm_kwargs()
kwargs['comment'] = self.comme... | Class for handling I/O from/to a file on disk. Args: name (str): The environment variable where communication address is stored. comment (str, optional): String indicating a comment. If 'read_meth' is 'readline' and this is provided, lines starting with a comment will be skipped. **kwargs: Additional keywords arguments... | AsciiFileComm | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsciiFileComm:
"""Class for handling I/O from/to a file on disk. Args: name (str): The environment variable where communication address is stored. comment (str, optional): String indicating a comment. If 'read_meth' is 'readline' and this is provided, lines starting with a comment will be skipped... | stack_v2_sparse_classes_36k_train_002537 | 2,162 | permissive | [
{
"docstring": "Get absolute path and set attributes.",
"name": "_init_before_open",
"signature": "def _init_before_open(self, comment=serialize._default_comment, **kwargs)"
},
{
"docstring": "Get keyword arguments to initialize communication with opposite comm object. Returns: dict: Keyword arg... | 3 | stack_v2_sparse_classes_30k_test_000065 | Implement the Python class `AsciiFileComm` described below.
Class description:
Class for handling I/O from/to a file on disk. Args: name (str): The environment variable where communication address is stored. comment (str, optional): String indicating a comment. If 'read_meth' is 'readline' and this is provided, lines ... | Implement the Python class `AsciiFileComm` described below.
Class description:
Class for handling I/O from/to a file on disk. Args: name (str): The environment variable where communication address is stored. comment (str, optional): String indicating a comment. If 'read_meth' is 'readline' and this is provided, lines ... | 73422c1adcc56386db80d9b9b8f0ccdce9f02036 | <|skeleton|>
class AsciiFileComm:
"""Class for handling I/O from/to a file on disk. Args: name (str): The environment variable where communication address is stored. comment (str, optional): String indicating a comment. If 'read_meth' is 'readline' and this is provided, lines starting with a comment will be skipped... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AsciiFileComm:
"""Class for handling I/O from/to a file on disk. Args: name (str): The environment variable where communication address is stored. comment (str, optional): String indicating a comment. If 'read_meth' is 'readline' and this is provided, lines starting with a comment will be skipped. **kwargs: A... | the_stack_v2_python_sparse | cis_interface/communication/AsciiFileComm.py | justinmcgrath/cis_interface | train | 0 |
89e34bdb92d7bf94d16257a84928320dde6832a3 | [
"import numpy as np\nimport healpy as hp\nsuper(GSMObserver, self).__init__()\nself.gsm = GlobalSkyModel()\nself.observed_sky = None\nself.gsm.generate(100)\nself._n_pix = hp.get_map_size(self.gsm.generated_map_data)\nself._n_side = hp.npix2nside(self._n_pix)\nself._theta, self._phi = hp.pix2ang(self._n_side, np.ar... | <|body_start_0|>
import numpy as np
import healpy as hp
super(GSMObserver, self).__init__()
self.gsm = GlobalSkyModel()
self.observed_sky = None
self.gsm.generate(100)
self._n_pix = hp.get_map_size(self.gsm.generated_map_data)
self._n_side = hp.npix2nside(... | Observer of the Global Sky Model. Generates the Observed sky, for a given point on Earth. Applies the necessary rotations and coordinate transformations so that the observed 'sky' can be returned, instead of the full galaxy-centered GSM. This class is based on pyephem's Observer(). The GSM bit can be thought of as an '... | pyGSM2008Obs | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class pyGSM2008Obs:
"""Observer of the Global Sky Model. Generates the Observed sky, for a given point on Earth. Applies the necessary rotations and coordinate transformations so that the observed 'sky' can be returned, instead of the full galaxy-centered GSM. This class is based on pyephem's Observer(... | stack_v2_sparse_classes_36k_train_002538 | 21,210 | no_license | [
{
"docstring": "Initialize the Observer object. Calls ephem.Observer.__init__ function and adds on gsm",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Generate the observed sky for the observer, based on the GSM. Parameters ---------- freq: float Frequency of map to ge... | 4 | null | Implement the Python class `pyGSM2008Obs` described below.
Class description:
Observer of the Global Sky Model. Generates the Observed sky, for a given point on Earth. Applies the necessary rotations and coordinate transformations so that the observed 'sky' can be returned, instead of the full galaxy-centered GSM. Thi... | Implement the Python class `pyGSM2008Obs` described below.
Class description:
Observer of the Global Sky Model. Generates the Observed sky, for a given point on Earth. Applies the necessary rotations and coordinate transformations so that the observed 'sky' can be returned, instead of the full galaxy-centered GSM. Thi... | b49777105a76b5ae03555a9f93f116454c8245a9 | <|skeleton|>
class pyGSM2008Obs:
"""Observer of the Global Sky Model. Generates the Observed sky, for a given point on Earth. Applies the necessary rotations and coordinate transformations so that the observed 'sky' can be returned, instead of the full galaxy-centered GSM. This class is based on pyephem's Observer(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class pyGSM2008Obs:
"""Observer of the Global Sky Model. Generates the Observed sky, for a given point on Earth. Applies the necessary rotations and coordinate transformations so that the observed 'sky' can be returned, instead of the full galaxy-centered GSM. This class is based on pyephem's Observer(). The GSM bi... | the_stack_v2_python_sparse | Astro/pyGSM.py | jizhi/jizhipy | train | 1 |
33cf267801528fac85d2670db79a786811ddbc89 | [
"self.group_id = group_id\nself.group_mbx_params = group_mbx_params\nself.restore_site_params = restore_site_params",
"if dictionary is None:\n return None\ngroup_id = dictionary.get('groupId')\ngroup_mbx_params = cohesity_management_sdk.models.restore_outlook_params.RestoreOutlookParams.from_dictionary(dictio... | <|body_start_0|>
self.group_id = group_id
self.group_mbx_params = group_mbx_params
self.restore_site_params = restore_site_params
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
group_id = dictionary.get('groupId')
group_mbx_params = cohesi... | Implementation of the 'RestoreO365GroupsParams_GroupGranularParams' model. TODO: type description here. Attributes: group_id (string): The Unique ID of the group. group_mbx_params (RestoreOutlookParams): The restore details of the group mailbox. restore_site_params (RestoreSiteParams): The restore details of the group ... | RestoreO365GroupsParams_GroupGranularParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoreO365GroupsParams_GroupGranularParams:
"""Implementation of the 'RestoreO365GroupsParams_GroupGranularParams' model. TODO: type description here. Attributes: group_id (string): The Unique ID of the group. group_mbx_params (RestoreOutlookParams): The restore details of the group mailbox. res... | stack_v2_sparse_classes_36k_train_002539 | 2,446 | permissive | [
{
"docstring": "Constructor for the RestoreO365GroupsParams_GroupGranularParams class",
"name": "__init__",
"signature": "def __init__(self, group_id=None, group_mbx_params=None, restore_site_params=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (d... | 2 | null | Implement the Python class `RestoreO365GroupsParams_GroupGranularParams` described below.
Class description:
Implementation of the 'RestoreO365GroupsParams_GroupGranularParams' model. TODO: type description here. Attributes: group_id (string): The Unique ID of the group. group_mbx_params (RestoreOutlookParams): The re... | Implement the Python class `RestoreO365GroupsParams_GroupGranularParams` described below.
Class description:
Implementation of the 'RestoreO365GroupsParams_GroupGranularParams' model. TODO: type description here. Attributes: group_id (string): The Unique ID of the group. group_mbx_params (RestoreOutlookParams): The re... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RestoreO365GroupsParams_GroupGranularParams:
"""Implementation of the 'RestoreO365GroupsParams_GroupGranularParams' model. TODO: type description here. Attributes: group_id (string): The Unique ID of the group. group_mbx_params (RestoreOutlookParams): The restore details of the group mailbox. res... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RestoreO365GroupsParams_GroupGranularParams:
"""Implementation of the 'RestoreO365GroupsParams_GroupGranularParams' model. TODO: type description here. Attributes: group_id (string): The Unique ID of the group. group_mbx_params (RestoreOutlookParams): The restore details of the group mailbox. restore_site_par... | the_stack_v2_python_sparse | cohesity_management_sdk/models/restore_o_365_groups_params_group_granular_params.py | cohesity/management-sdk-python | train | 24 |
5f2442d1f0ec2e8af04d9c219c9bcdb3e639c5da | [
"count = Counter()\nself.times = []\nself.persons = []\nmost_recent = None\nfor person, time in zip(persons, times):\n count[person] += 1\n p, c = count.most_common(1)[0]\n self.times.append(time)\n if count[person] == c:\n self.persons.append(person)\n most_recent = person\n else:\n ... | <|body_start_0|>
count = Counter()
self.times = []
self.persons = []
most_recent = None
for person, time in zip(persons, times):
count[person] += 1
p, c = count.most_common(1)[0]
self.times.append(time)
if count[person] == c:
... | TopVotedCandidate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopVotedCandidate:
def __init__(self, persons, times):
""":type persons: List[int] :type times: List[int]"""
<|body_0|>
def q(self, t):
""":type t: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
count = Counter()
self.times ... | stack_v2_sparse_classes_36k_train_002540 | 1,304 | no_license | [
{
"docstring": ":type persons: List[int] :type times: List[int]",
"name": "__init__",
"signature": "def __init__(self, persons, times)"
},
{
"docstring": ":type t: int :rtype: int",
"name": "q",
"signature": "def q(self, t)"
}
] | 2 | null | Implement the Python class `TopVotedCandidate` described below.
Class description:
Implement the TopVotedCandidate class.
Method signatures and docstrings:
- def __init__(self, persons, times): :type persons: List[int] :type times: List[int]
- def q(self, t): :type t: int :rtype: int | Implement the Python class `TopVotedCandidate` described below.
Class description:
Implement the TopVotedCandidate class.
Method signatures and docstrings:
- def __init__(self, persons, times): :type persons: List[int] :type times: List[int]
- def q(self, t): :type t: int :rtype: int
<|skeleton|>
class TopVotedCandi... | 3232620c73175dcf4cfef31a07319e7cc032d224 | <|skeleton|>
class TopVotedCandidate:
def __init__(self, persons, times):
""":type persons: List[int] :type times: List[int]"""
<|body_0|>
def q(self, t):
""":type t: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TopVotedCandidate:
def __init__(self, persons, times):
""":type persons: List[int] :type times: List[int]"""
count = Counter()
self.times = []
self.persons = []
most_recent = None
for person, time in zip(persons, times):
count[person] += 1
... | the_stack_v2_python_sparse | C103/0911_online_election/solution_1.py | asymmetry/leetcode | train | 0 | |
ee20202869447bb407ad42396139f3f783b816d7 | [
"l2 = len(nums2)\nnums2_next = [-1] * l2\nfor i in range(l2 - 1):\n for j in range(i + 1, l2):\n if nums2[j] > nums2[i]:\n nums2_next[i] = nums2[j]\n break\nres = []\nfor k in nums1:\n res.append(nums2_next[nums2.index(k)])\nreturn res",
"if not nums1 or not nums2:\n return [... | <|body_start_0|>
l2 = len(nums2)
nums2_next = [-1] * l2
for i in range(l2 - 1):
for j in range(i + 1, l2):
if nums2[j] > nums2[i]:
nums2_next[i] = nums2[j]
break
res = []
for k in nums1:
res.append(nu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nextGreaterElement(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_0|>
def nextGreaterElement2(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_1|... | stack_v2_sparse_classes_36k_train_002541 | 1,411 | no_license | [
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: List[int]",
"name": "nextGreaterElement",
"signature": "def nextGreaterElement(self, nums1, nums2)"
},
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: List[int]",
"name": "nextGreaterElement2",
"s... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextGreaterElement(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int]
- def nextGreaterElement2(self, nums1, nums2): :type nums1: List[int] ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextGreaterElement(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int]
- def nextGreaterElement2(self, nums1, nums2): :type nums1: List[int] ... | c92a5ddcc56e3f69be1e6fb25e9c8ed277e57ee0 | <|skeleton|>
class Solution:
def nextGreaterElement(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_0|>
def nextGreaterElement2(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def nextGreaterElement(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
l2 = len(nums2)
nums2_next = [-1] * l2
for i in range(l2 - 1):
for j in range(i + 1, l2):
if nums2[j] > nums2[i]:
... | the_stack_v2_python_sparse | code/496#Next Greater Element I.py | EachenKuang/LeetCode | train | 28 | |
2cacf9a51a6a111aef33653dad4f00313e5a2063 | [
"def shift(velocity):\n \"\"\"\n Computes the direction of shift for each node for upwind\n discretization based on sign of veclocity\n \"\"\"\n shift_vel = np.sign(velocity)\n shift_vel[np.where(shift_vel <= 0)] = 0\n shift_vel[np.where(shift_vel > 0)] = -1\n return ... | <|body_start_0|>
def shift(velocity):
"""
Computes the direction of shift for each node for upwind
discretization based on sign of veclocity
"""
shift_vel = np.sign(velocity)
shift_vel[np.where(shift_vel <= 0)] = 0
... | Simulation | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Simulation:
def initialize(self):
"""Initialize the grid and variables for advection and set the initial conditions for the chosen problem."""
<|body_0|>
def method_compute_timestep(self):
"""The timestep() function computes the advective timestep (CFL) constraint. T... | stack_v2_sparse_classes_36k_train_002542 | 5,494 | permissive | [
{
"docstring": "Initialize the grid and variables for advection and set the initial conditions for the chosen problem.",
"name": "initialize",
"signature": "def initialize(self)"
},
{
"docstring": "The timestep() function computes the advective timestep (CFL) constraint. The CFL constraint says ... | 4 | null | Implement the Python class `Simulation` described below.
Class description:
Implement the Simulation class.
Method signatures and docstrings:
- def initialize(self): Initialize the grid and variables for advection and set the initial conditions for the chosen problem.
- def method_compute_timestep(self): The timestep... | Implement the Python class `Simulation` described below.
Class description:
Implement the Simulation class.
Method signatures and docstrings:
- def initialize(self): Initialize the grid and variables for advection and set the initial conditions for the chosen problem.
- def method_compute_timestep(self): The timestep... | f91789a319caa98dfbc3f496e9953756e6ee3ca9 | <|skeleton|>
class Simulation:
def initialize(self):
"""Initialize the grid and variables for advection and set the initial conditions for the chosen problem."""
<|body_0|>
def method_compute_timestep(self):
"""The timestep() function computes the advective timestep (CFL) constraint. T... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Simulation:
def initialize(self):
"""Initialize the grid and variables for advection and set the initial conditions for the chosen problem."""
def shift(velocity):
"""
Computes the direction of shift for each node for upwind
discretization ba... | the_stack_v2_python_sparse | pyro/advection_nonuniform/simulation.py | python-hydro/pyro2 | train | 202 | |
07efcf23083468776d36a27465be3af81364a084 | [
"super().__init__(acq, data, posterior, **kwargs)\nself.norm_fn = acq\nself.dotprod_fn = dotprod_fn\nself.sigmas = self.norm_fn(self.theta_mean, self.theta_cov, self.X_unlabeled, **self.kwargs)\nself.sigma = self.sigmas.sum()",
"N = len(self.X_unlabeled)\nself.cross_prods = np.zeros([N, N])\nfor n, x_n in enumera... | <|body_start_0|>
super().__init__(acq, data, posterior, **kwargs)
self.norm_fn = acq
self.dotprod_fn = dotprod_fn
self.sigmas = self.norm_fn(self.theta_mean, self.theta_cov, self.X_unlabeled, **self.kwargs)
self.sigma = self.sigmas.sum()
<|end_body_0|>
<|body_start_1|>
N... | FrankWolfe | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FrankWolfe:
def __init__(self, acq, data, posterior, dotprod_fn=None, **kwargs):
"""Constructs a batch of points using closed-form ACS-FW. :param acq: (function) Acquisition function, i.e. weighted inner product of each point with itself. :param data: (ActiveLearningDataset) Dataset. :pa... | stack_v2_sparse_classes_36k_train_002543 | 15,347 | no_license | [
{
"docstring": "Constructs a batch of points using closed-form ACS-FW. :param acq: (function) Acquisition function, i.e. weighted inner product of each point with itself. :param data: (ActiveLearningDataset) Dataset. :param posterior: (function) Function to compute posterior mean and covariance. :param dotprod_... | 4 | stack_v2_sparse_classes_30k_train_021660 | Implement the Python class `FrankWolfe` described below.
Class description:
Implement the FrankWolfe class.
Method signatures and docstrings:
- def __init__(self, acq, data, posterior, dotprod_fn=None, **kwargs): Constructs a batch of points using closed-form ACS-FW. :param acq: (function) Acquisition function, i.e. ... | Implement the Python class `FrankWolfe` described below.
Class description:
Implement the FrankWolfe class.
Method signatures and docstrings:
- def __init__(self, acq, data, posterior, dotprod_fn=None, **kwargs): Constructs a batch of points using closed-form ACS-FW. :param acq: (function) Acquisition function, i.e. ... | 5a3d54770ba0cb3319f6a4cd4a975e31915dd49b | <|skeleton|>
class FrankWolfe:
def __init__(self, acq, data, posterior, dotprod_fn=None, **kwargs):
"""Constructs a batch of points using closed-form ACS-FW. :param acq: (function) Acquisition function, i.e. weighted inner product of each point with itself. :param data: (ActiveLearningDataset) Dataset. :pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FrankWolfe:
def __init__(self, acq, data, posterior, dotprod_fn=None, **kwargs):
"""Constructs a batch of points using closed-form ACS-FW. :param acq: (function) Acquisition function, i.e. weighted inner product of each point with itself. :param data: (ActiveLearningDataset) Dataset. :param posterior:... | the_stack_v2_python_sparse | query_strategies/bayesian_utils/acs/coresets.py | AILARON/active-learning | train | 0 | |
03bd4ffbbe35eebeffc6257a761aa7d5fb7d13a7 | [
"self.fields[name] = typ(label='', required=False)\nif value is not None:\n self.fields[name].initial = value\nif pos:\n order = list(self.fields.keys())\n order.remove(name)\n order.insert(pos, name)\n self.fields = OrderedDict(((key, self.fields[key]) for key in order))",
"expr = re.compile('%s_\... | <|body_start_0|>
self.fields[name] = typ(label='', required=False)
if value is not None:
self.fields[name].initial = value
if pos:
order = list(self.fields.keys())
order.remove(name)
order.insert(pos, name)
self.fields = OrderedDict(((k... | A form which accepts dynamic fields. We consider a field to be dynamic when it can appear multiple times within the same request. | DynamicForm | [
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DynamicForm:
"""A form which accepts dynamic fields. We consider a field to be dynamic when it can appear multiple times within the same request."""
def _create_field(self, typ, name, value=None, pos=None):
"""Create a new form field."""
<|body_0|>
def _load_from_qdict(s... | stack_v2_sparse_classes_36k_train_002544 | 11,908 | permissive | [
{
"docstring": "Create a new form field.",
"name": "_create_field",
"signature": "def _create_field(self, typ, name, value=None, pos=None)"
},
{
"docstring": "Load all instances of a field from a ``QueryDict`` object. :param ``QueryDict`` qdict: a QueryDict object :param string pattern: pattern ... | 2 | stack_v2_sparse_classes_30k_train_011633 | Implement the Python class `DynamicForm` described below.
Class description:
A form which accepts dynamic fields. We consider a field to be dynamic when it can appear multiple times within the same request.
Method signatures and docstrings:
- def _create_field(self, typ, name, value=None, pos=None): Create a new form... | Implement the Python class `DynamicForm` described below.
Class description:
A form which accepts dynamic fields. We consider a field to be dynamic when it can appear multiple times within the same request.
Method signatures and docstrings:
- def _create_field(self, typ, name, value=None, pos=None): Create a new form... | df699aab0799ec1725b6b89be38e56285821c889 | <|skeleton|>
class DynamicForm:
"""A form which accepts dynamic fields. We consider a field to be dynamic when it can appear multiple times within the same request."""
def _create_field(self, typ, name, value=None, pos=None):
"""Create a new form field."""
<|body_0|>
def _load_from_qdict(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DynamicForm:
"""A form which accepts dynamic fields. We consider a field to be dynamic when it can appear multiple times within the same request."""
def _create_field(self, typ, name, value=None, pos=None):
"""Create a new form field."""
self.fields[name] = typ(label='', required=False)
... | the_stack_v2_python_sparse | modoboa/lib/form_utils.py | modoboa/modoboa | train | 2,201 |
f1b833ff5e8e245c58949a2092886147e22ec2be | [
"all_dep_paths = rule_details[su.SRCS_KEY][:]\nall_dep_paths.extend(link_libs)\nall_dep_paths.extend(dep_sources)\nall_dep_paths.append(rule_details[su.OUT_KEY])\nrule_details[su.ALL_DEP_PATHS_KEY].extend(sorted(list(set(all_dep_paths))))",
"su.init_rule_common(rule_details, rule_details[su.NAME_KEY], [su.SRCS_KE... | <|body_start_0|>
all_dep_paths = rule_details[su.SRCS_KEY][:]
all_dep_paths.extend(link_libs)
all_dep_paths.extend(dep_sources)
all_dep_paths.append(rule_details[su.OUT_KEY])
rule_details[su.ALL_DEP_PATHS_KEY].extend(sorted(list(set(all_dep_paths))))
<|end_body_0|>
<|body_start_... | Common Python handler functions. | PyCommon | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PyCommon:
"""Common Python handler functions."""
def _set_all_dep_paths(cls, rule_details, link_libs, dep_sources):
"""Set all dependency paths list for the rule."""
<|body_0|>
def _internal_setup(cls, rule_details, details_map, is_test):
"""Initializing build ru... | stack_v2_sparse_classes_36k_train_002545 | 11,513 | permissive | [
{
"docstring": "Set all dependency paths list for the rule.",
"name": "_set_all_dep_paths",
"signature": "def _set_all_dep_paths(cls, rule_details, link_libs, dep_sources)"
},
{
"docstring": "Initializing build rule dictionary.",
"name": "_internal_setup",
"signature": "def _internal_set... | 4 | stack_v2_sparse_classes_30k_train_016116 | Implement the Python class `PyCommon` described below.
Class description:
Common Python handler functions.
Method signatures and docstrings:
- def _set_all_dep_paths(cls, rule_details, link_libs, dep_sources): Set all dependency paths list for the rule.
- def _internal_setup(cls, rule_details, details_map, is_test): ... | Implement the Python class `PyCommon` described below.
Class description:
Common Python handler functions.
Method signatures and docstrings:
- def _set_all_dep_paths(cls, rule_details, link_libs, dep_sources): Set all dependency paths list for the rule.
- def _internal_setup(cls, rule_details, details_map, is_test): ... | af028dd413dd2595cb8338a5a2c2d61a95adf7c6 | <|skeleton|>
class PyCommon:
"""Common Python handler functions."""
def _set_all_dep_paths(cls, rule_details, link_libs, dep_sources):
"""Set all dependency paths list for the rule."""
<|body_0|>
def _internal_setup(cls, rule_details, details_map, is_test):
"""Initializing build ru... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PyCommon:
"""Common Python handler functions."""
def _set_all_dep_paths(cls, rule_details, link_libs, dep_sources):
"""Set all dependency paths list for the rule."""
all_dep_paths = rule_details[su.SRCS_KEY][:]
all_dep_paths.extend(link_libs)
all_dep_paths.extend(dep_sourc... | the_stack_v2_python_sparse | build_tool/bu.scripts/mool/python_common.py | rocketfuel/mool | train | 3 |
62527f50c3ab8200bc3dae7ff881e40339aade0d | [
"if HubClient.__instance is not None:\n raise Exception('A singleton class cannot be initialized twice')\nself.__connection = http.client.HTTPConnection(HubClient.HUB_SERVER_HOST, HubClient.HUB_SERVER_PORT)",
"if HubClient.__instance is None:\n HubClient.__instance = HubClient()\nreturn HubClient.__instance... | <|body_start_0|>
if HubClient.__instance is not None:
raise Exception('A singleton class cannot be initialized twice')
self.__connection = http.client.HTTPConnection(HubClient.HUB_SERVER_HOST, HubClient.HUB_SERVER_PORT)
<|end_body_0|>
<|body_start_1|>
if HubClient.__instance is None... | Singleton REST client to interact with the authentication server. --- This class is responsible of interfacing the authentication server as another data source, via a REST API presentation layer in the authentication server. Note: Uses the AUTH_SERVER_HOST and AUTH_SERVER_PORT environment variables to open the connecti... | HubClient | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HubClient:
"""Singleton REST client to interact with the authentication server. --- This class is responsible of interfacing the authentication server as another data source, via a REST API presentation layer in the authentication server. Note: Uses the AUTH_SERVER_HOST and AUTH_SERVER_PORT envir... | stack_v2_sparse_classes_36k_train_002546 | 1,956 | permissive | [
{
"docstring": "Constructor method. --- Do NOT use this method. Use instance() instead.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Singleton instance access method. --- Do NOT use the constructor. Use this method instead. Returns: The singleton instance of this cl... | 3 | stack_v2_sparse_classes_30k_train_009883 | Implement the Python class `HubClient` described below.
Class description:
Singleton REST client to interact with the authentication server. --- This class is responsible of interfacing the authentication server as another data source, via a REST API presentation layer in the authentication server. Note: Uses the AUTH... | Implement the Python class `HubClient` described below.
Class description:
Singleton REST client to interact with the authentication server. --- This class is responsible of interfacing the authentication server as another data source, via a REST API presentation layer in the authentication server. Note: Uses the AUTH... | 9ae0c71140d537bb43c0f8ec8a81b8fff38dec21 | <|skeleton|>
class HubClient:
"""Singleton REST client to interact with the authentication server. --- This class is responsible of interfacing the authentication server as another data source, via a REST API presentation layer in the authentication server. Note: Uses the AUTH_SERVER_HOST and AUTH_SERVER_PORT envir... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HubClient:
"""Singleton REST client to interact with the authentication server. --- This class is responsible of interfacing the authentication server as another data source, via a REST API presentation layer in the authentication server. Note: Uses the AUTH_SERVER_HOST and AUTH_SERVER_PORT environment variab... | the_stack_v2_python_sparse | src/components/client/conexiones/hub_client.py | adp1002/practica-dms-2019-2020 | train | 0 |
9811355c716de8bf3f8ca16bfbdb859b0f842eb9 | [
"self.capacity = capacity\nself.queue = PriorityQueue()\nself.hashmaps = {}\nself.is_debug = is_debug",
"node_to_reshuffle = self.hashmaps.get(key, None)\nif node_to_reshuffle == None:\n if self.is_debug:\n print(f'missing Cache[{key}] = -1')\n return -1\nself.arrange_mru(key, node_to_reshuffle.value... | <|body_start_0|>
self.capacity = capacity
self.queue = PriorityQueue()
self.hashmaps = {}
self.is_debug = is_debug
<|end_body_0|>
<|body_start_1|>
node_to_reshuffle = self.hashmaps.get(key, None)
if node_to_reshuffle == None:
if self.is_debug:
... | LRU_Cache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRU_Cache:
def __init__(self, capacity, is_debug):
"""Initialize LRU_Cache with specified attributes. self.capacity(int): the maximum size of LRU_Cache self.queue(class): to track cache key (least -> .. -> most recently used) self.hashmaps(dictionary): hashmaps[key] = Node(key,value) sel... | stack_v2_sparse_classes_36k_train_002547 | 5,909 | no_license | [
{
"docstring": "Initialize LRU_Cache with specified attributes. self.capacity(int): the maximum size of LRU_Cache self.queue(class): to track cache key (least -> .. -> most recently used) self.hashmaps(dictionary): hashmaps[key] = Node(key,value) self.is_debug(boolean) = enable printing debug output",
"name... | 5 | stack_v2_sparse_classes_30k_train_009826 | Implement the Python class `LRU_Cache` described below.
Class description:
Implement the LRU_Cache class.
Method signatures and docstrings:
- def __init__(self, capacity, is_debug): Initialize LRU_Cache with specified attributes. self.capacity(int): the maximum size of LRU_Cache self.queue(class): to track cache key ... | Implement the Python class `LRU_Cache` described below.
Class description:
Implement the LRU_Cache class.
Method signatures and docstrings:
- def __init__(self, capacity, is_debug): Initialize LRU_Cache with specified attributes. self.capacity(int): the maximum size of LRU_Cache self.queue(class): to track cache key ... | 72e466ff8d593cffdea8062f04caf92a5a5d2704 | <|skeleton|>
class LRU_Cache:
def __init__(self, capacity, is_debug):
"""Initialize LRU_Cache with specified attributes. self.capacity(int): the maximum size of LRU_Cache self.queue(class): to track cache key (least -> .. -> most recently used) self.hashmaps(dictionary): hashmaps[key] = Node(key,value) sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRU_Cache:
def __init__(self, capacity, is_debug):
"""Initialize LRU_Cache with specified attributes. self.capacity(int): the maximum size of LRU_Cache self.queue(class): to track cache key (least -> .. -> most recently used) self.hashmaps(dictionary): hashmaps[key] = Node(key,value) self.is_debug(boo... | the_stack_v2_python_sparse | problem1_Hashed_Queue_Linked_List/lru_cache.py | jadugnap/python-data-structure | train | 0 | |
50b73f49584343b3e5656fb9795b586af75cc7db | [
"self.k = k\nself.min_heap = nums\nheapq.heapify(self.min_heap)\nwhile len(self.min_heap) > self.k:\n heapq.heappop(self.min_heap)",
"if len(self.min_heap) < self.k:\n heapq.heappush(self.min_heap, val)\nelse:\n heapq.heappushpop(self.min_heap, val)\nreturn self.min_heap[0]"
] | <|body_start_0|>
self.k = k
self.min_heap = nums
heapq.heapify(self.min_heap)
while len(self.min_heap) > self.k:
heapq.heappop(self.min_heap)
<|end_body_0|>
<|body_start_1|>
if len(self.min_heap) < self.k:
heapq.heappush(self.min_heap, val)
else:
... | KthLargest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k: int, nums: List[int]):
"""Time complexity: O(n log n) Space complexity: O(1)"""
<|body_0|>
def add(self, val: int) -> int:
"""Time complexity: O(log n) Space complexity: O(1)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_002548 | 864 | permissive | [
{
"docstring": "Time complexity: O(n log n) Space complexity: O(1)",
"name": "__init__",
"signature": "def __init__(self, k: int, nums: List[int])"
},
{
"docstring": "Time complexity: O(log n) Space complexity: O(1)",
"name": "add",
"signature": "def add(self, val: int) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_test_001150 | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k: int, nums: List[int]): Time complexity: O(n log n) Space complexity: O(1)
- def add(self, val: int) -> int: Time complexity: O(log n) Space complexity: ... | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k: int, nums: List[int]): Time complexity: O(n log n) Space complexity: O(1)
- def add(self, val: int) -> int: Time complexity: O(log n) Space complexity: ... | 32b0878f63e5edd19a1fbe13bfa4c518a4261e23 | <|skeleton|>
class KthLargest:
def __init__(self, k: int, nums: List[int]):
"""Time complexity: O(n log n) Space complexity: O(1)"""
<|body_0|>
def add(self, val: int) -> int:
"""Time complexity: O(log n) Space complexity: O(1)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KthLargest:
def __init__(self, k: int, nums: List[int]):
"""Time complexity: O(n log n) Space complexity: O(1)"""
self.k = k
self.min_heap = nums
heapq.heapify(self.min_heap)
while len(self.min_heap) > self.k:
heapq.heappop(self.min_heap)
def add(self, ... | the_stack_v2_python_sparse | leetcode/Heaps/703. Kth Largest Element in a Stream.py | danielfsousa/algorithms-solutions | train | 2 | |
414c7e9dbe1a590259815fb994394a87e1fb9a7b | [
"cls.NETWORK_ATTACHMENT_ARG = flags.NetworkAttachmentArgument()\ncls.NETWORK_ATTACHMENT_ARG.AddArgument(parser, operation_type='create')\ncls.SUBNETWORK_ARG = subnetwork_flags.SubnetworkArgumentForNetworkAttachment()\ncls.SUBNETWORK_ARG.AddArgument(parser)\nparser.display_info.AddFormat(flags.DEFAULT_LIST_FORMAT)\n... | <|body_start_0|>
cls.NETWORK_ATTACHMENT_ARG = flags.NetworkAttachmentArgument()
cls.NETWORK_ATTACHMENT_ARG.AddArgument(parser, operation_type='create')
cls.SUBNETWORK_ARG = subnetwork_flags.SubnetworkArgumentForNetworkAttachment()
cls.SUBNETWORK_ARG.AddArgument(parser)
parser.dis... | Create a Google Compute Engine network attachment. | Create | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Create:
"""Create a Google Compute Engine network attachment."""
def Args(cls, parser):
"""Create a Google Compute Engine network attachment. Args: parser: the parser that parses the input from the user."""
<|body_0|>
def Run(self, args):
"""Issue a network attac... | stack_v2_sparse_classes_36k_train_002549 | 5,014 | permissive | [
{
"docstring": "Create a Google Compute Engine network attachment. Args: parser: the parser that parses the input from the user.",
"name": "Args",
"signature": "def Args(cls, parser)"
},
{
"docstring": "Issue a network attachment INSERT request.",
"name": "Run",
"signature": "def Run(sel... | 2 | stack_v2_sparse_classes_30k_train_013233 | Implement the Python class `Create` described below.
Class description:
Create a Google Compute Engine network attachment.
Method signatures and docstrings:
- def Args(cls, parser): Create a Google Compute Engine network attachment. Args: parser: the parser that parses the input from the user.
- def Run(self, args): ... | Implement the Python class `Create` described below.
Class description:
Create a Google Compute Engine network attachment.
Method signatures and docstrings:
- def Args(cls, parser): Create a Google Compute Engine network attachment. Args: parser: the parser that parses the input from the user.
- def Run(self, args): ... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class Create:
"""Create a Google Compute Engine network attachment."""
def Args(cls, parser):
"""Create a Google Compute Engine network attachment. Args: parser: the parser that parses the input from the user."""
<|body_0|>
def Run(self, args):
"""Issue a network attac... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Create:
"""Create a Google Compute Engine network attachment."""
def Args(cls, parser):
"""Create a Google Compute Engine network attachment. Args: parser: the parser that parses the input from the user."""
cls.NETWORK_ATTACHMENT_ARG = flags.NetworkAttachmentArgument()
cls.NETWORK... | the_stack_v2_python_sparse | lib/surface/compute/network_attachments/create.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
a8e6acf38526e16b0a98e994e5692d53285264c5 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('yufeng72', 'yufeng72')\nurl = 'http://bostonopendata-boston.opendata.arcgis.com/datasets/cbf14bb032ef4bd38e20429f71acb61a_2.csv'\nresponse = urllib.request.urlopen(url)\nr = csv.reader(io.StringIO(respon... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('yufeng72', 'yufeng72')
url = 'http://bostonopendata-boston.opendata.arcgis.com/datasets/cbf14bb032ef4bd38e20429f71acb61a_2.csv'
response = urllib.... | RetrieveCollegesUniversities | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RetrieveCollegesUniversities:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document descri... | stack_v2_sparse_classes_36k_train_002550 | 5,033 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_019813 | Implement the Python class `RetrieveCollegesUniversities` described below.
Class description:
Implement the RetrieveCollegesUniversities class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.Pro... | Implement the Python class `RetrieveCollegesUniversities` described below.
Class description:
Implement the RetrieveCollegesUniversities class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.Pro... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class RetrieveCollegesUniversities:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document descri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RetrieveCollegesUniversities:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('yufeng72', 'yufeng72')... | the_stack_v2_python_sparse | yufeng72/RetrieveCollegesUniversities.py | maximega/course-2019-spr-proj | train | 2 | |
83c7aea969af0891ea544e1c1084193ed0f79507 | [
"self.hass: HomeAssistant = hass\nself.server: snapcast.control.Snapserver = server\nself.hpid: str = hpid\nself._entry_id = entry_id\nself.clients: list[SnapcastClientDevice] = []\nself.groups: list[SnapcastGroupDevice] = []\nself.hass_async_add_entities: AddEntitiesCallback\nself.server.set_on_update_callback(sel... | <|body_start_0|>
self.hass: HomeAssistant = hass
self.server: snapcast.control.Snapserver = server
self.hpid: str = hpid
self._entry_id = entry_id
self.clients: list[SnapcastClientDevice] = []
self.groups: list[SnapcastGroupDevice] = []
self.hass_async_add_entitie... | Snapcast server and data stored in the Home Assistant data object. | HomeAssistantSnapcast | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HomeAssistantSnapcast:
"""Snapcast server and data stored in the Home Assistant data object."""
def __init__(self, hass: HomeAssistant, server: snapcast.control.Snapserver, hpid: str, entry_id: str) -> None:
"""Initialize the HomeAssistantSnapcast object. Parameters ---------- hass: ... | stack_v2_sparse_classes_36k_train_002551 | 5,006 | permissive | [
{
"docstring": "Initialize the HomeAssistantSnapcast object. Parameters ---------- hass: HomeAssistant hass object server : snapcast.control.Snapserver Snapcast server hpid : str host and port entry_id: str ConfigEntry entry_id Returns ------- None",
"name": "__init__",
"signature": "def __init__(self, ... | 6 | null | Implement the Python class `HomeAssistantSnapcast` described below.
Class description:
Snapcast server and data stored in the Home Assistant data object.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, server: snapcast.control.Snapserver, hpid: str, entry_id: str) -> None: Initialize the H... | Implement the Python class `HomeAssistantSnapcast` described below.
Class description:
Snapcast server and data stored in the Home Assistant data object.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, server: snapcast.control.Snapserver, hpid: str, entry_id: str) -> None: Initialize the H... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class HomeAssistantSnapcast:
"""Snapcast server and data stored in the Home Assistant data object."""
def __init__(self, hass: HomeAssistant, server: snapcast.control.Snapserver, hpid: str, entry_id: str) -> None:
"""Initialize the HomeAssistantSnapcast object. Parameters ---------- hass: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HomeAssistantSnapcast:
"""Snapcast server and data stored in the Home Assistant data object."""
def __init__(self, hass: HomeAssistant, server: snapcast.control.Snapserver, hpid: str, entry_id: str) -> None:
"""Initialize the HomeAssistantSnapcast object. Parameters ---------- hass: HomeAssistant... | the_stack_v2_python_sparse | homeassistant/components/snapcast/server.py | home-assistant/core | train | 35,501 |
b9cf7aced1761cf6944eb88333cd328136ade255 | [
"res = True\npoint = [p.x, p.y, p.z]\nsize = data.size * data.nodemat * data.scale\nsize -= data.nodemat.off\nsize = [size.x, size.y, size.z]\noffset = [data.offset.x, data.offset.y, data.offset.z]\npos = c4d.Vector() * data.nodemat\npos = [pos.x, pos.y, pos.z]\nfor i in range(3):\n res = pos[i] + offset[i] + si... | <|body_start_0|>
res = True
point = [p.x, p.y, p.z]
size = data.size * data.nodemat * data.scale
size -= data.nodemat.off
size = [size.x, size.y, size.z]
offset = [data.offset.x, data.offset.y, data.offset.z]
pos = c4d.Vector() * data.nodemat
pos = [pos.x,... | Utility class for the noise falloff | NoiseFalloffHelper | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoiseFalloffHelper:
"""Utility class for the noise falloff"""
def PointInBox(p, data):
"""Returns if a point is in box. Args: p (c4d.Vector): The point position. data (c4d.BaseContainer): Falloff data information. Returns: True if the point is in box, otherwise False"""
<|bod... | stack_v2_sparse_classes_36k_train_002552 | 13,785 | permissive | [
{
"docstring": "Returns if a point is in box. Args: p (c4d.Vector): The point position. data (c4d.BaseContainer): Falloff data information. Returns: True if the point is in box, otherwise False",
"name": "PointInBox",
"signature": "def PointInBox(p, data)"
},
{
"docstring": "Helper method to dra... | 2 | stack_v2_sparse_classes_30k_train_019363 | Implement the Python class `NoiseFalloffHelper` described below.
Class description:
Utility class for the noise falloff
Method signatures and docstrings:
- def PointInBox(p, data): Returns if a point is in box. Args: p (c4d.Vector): The point position. data (c4d.BaseContainer): Falloff data information. Returns: True... | Implement the Python class `NoiseFalloffHelper` described below.
Class description:
Utility class for the noise falloff
Method signatures and docstrings:
- def PointInBox(p, data): Returns if a point is in box. Args: p (c4d.Vector): The point position. data (c4d.BaseContainer): Falloff data information. Returns: True... | b1ea3fce533df34094bc3d0bd6460dfb84306e53 | <|skeleton|>
class NoiseFalloffHelper:
"""Utility class for the noise falloff"""
def PointInBox(p, data):
"""Returns if a point is in box. Args: p (c4d.Vector): The point position. data (c4d.BaseContainer): Falloff data information. Returns: True if the point is in box, otherwise False"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NoiseFalloffHelper:
"""Utility class for the noise falloff"""
def PointInBox(p, data):
"""Returns if a point is in box. Args: p (c4d.Vector): The point position. data (c4d.BaseContainer): Falloff data information. Returns: True if the point is in box, otherwise False"""
res = True
... | the_stack_v2_python_sparse | plugins/py-noise_falloff_r14/py-noise_falloff_r14.pyp | PluginCafe/cinema4d_py_sdk_extended | train | 112 |
1af32c233fa1289e2541dbf6607a6f358cef0859 | [
"try:\n search = request.GET.get('search', '')\n if search:\n brands = self.get_filter_objects(Brand, name__icontains=search)\n else:\n brands = self.get_all_objects(Brand)\n serializer = serializers.BrandSerializer(brands, many=True)\n return Utils.dispatch_success(request, serializer.... | <|body_start_0|>
try:
search = request.GET.get('search', '')
if search:
brands = self.get_filter_objects(Brand, name__icontains=search)
else:
brands = self.get_all_objects(Brand)
serializer = serializers.BrandSerializer(brands, many... | Brand List and create Endpoint | BrandList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BrandList:
"""Brand List and create Endpoint"""
def get(self, request):
"""returns the list of brand :param request: :return:"""
<|body_0|>
def post(self, request):
"""Creates a new brand :param request: { "name" : "Honda" } :return:"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_002553 | 23,745 | permissive | [
{
"docstring": "returns the list of brand :param request: :return:",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Creates a new brand :param request: { \"name\" : \"Honda\" } :return:",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012856 | Implement the Python class `BrandList` described below.
Class description:
Brand List and create Endpoint
Method signatures and docstrings:
- def get(self, request): returns the list of brand :param request: :return:
- def post(self, request): Creates a new brand :param request: { "name" : "Honda" } :return: | Implement the Python class `BrandList` described below.
Class description:
Brand List and create Endpoint
Method signatures and docstrings:
- def get(self, request): returns the list of brand :param request: :return:
- def post(self, request): Creates a new brand :param request: { "name" : "Honda" } :return:
<|skele... | 1e31affddf60d2de72445a85dd2055bdeba6f670 | <|skeleton|>
class BrandList:
"""Brand List and create Endpoint"""
def get(self, request):
"""returns the list of brand :param request: :return:"""
<|body_0|>
def post(self, request):
"""Creates a new brand :param request: { "name" : "Honda" } :return:"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BrandList:
"""Brand List and create Endpoint"""
def get(self, request):
"""returns the list of brand :param request: :return:"""
try:
search = request.GET.get('search', '')
if search:
brands = self.get_filter_objects(Brand, name__icontains=search)
... | the_stack_v2_python_sparse | the_mechanic_backend/v0/stock/views.py | muthukumar4999/the-mechanic-backend | train | 0 |
c56de23f6ab3dd4114473ff26108ecac6a0c8328 | [
"self.phenotypes = phenotypes\nself.chrom = chrom\nself.contigs = {}\nif phenotypes != None:\n for phenotype in phenotypes.values():\n for contig in phenotype.contigs:\n self.contigs[contig.ID] = contig",
"try:\n contigId = GffReader.idRegex.search(info[8]).group(1)\nexcept (AttributeError... | <|body_start_0|>
self.phenotypes = phenotypes
self.chrom = chrom
self.contigs = {}
if phenotypes != None:
for phenotype in phenotypes.values():
for contig in phenotype.contigs:
self.contigs[contig.ID] = contig
<|end_body_0|>
<|body_start_1... | The GffReader reads a GFF3 file. | GffReader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GffReader:
"""The GffReader reads a GFF3 file."""
def __init__(self, phenotypes=None, chrom=None):
"""The constructor reads of all phenotypes all contigs, and converts this to one dictionary with contig objects with the contig ID as key. if the phenotypes == None, an empty dictionary... | stack_v2_sparse_classes_36k_train_002554 | 9,107 | no_license | [
{
"docstring": "The constructor reads of all phenotypes all contigs, and converts this to one dictionary with contig objects with the contig ID as key. if the phenotypes == None, an empty dictionary is created and all contigs will be added to this dictionary.",
"name": "__init__",
"signature": "def __in... | 2 | stack_v2_sparse_classes_30k_train_004104 | Implement the Python class `GffReader` described below.
Class description:
The GffReader reads a GFF3 file.
Method signatures and docstrings:
- def __init__(self, phenotypes=None, chrom=None): The constructor reads of all phenotypes all contigs, and converts this to one dictionary with contig objects with the contig ... | Implement the Python class `GffReader` described below.
Class description:
The GffReader reads a GFF3 file.
Method signatures and docstrings:
- def __init__(self, phenotypes=None, chrom=None): The constructor reads of all phenotypes all contigs, and converts this to one dictionary with contig objects with the contig ... | 53315eca821785aa02218e903b60921ecf18246b | <|skeleton|>
class GffReader:
"""The GffReader reads a GFF3 file."""
def __init__(self, phenotypes=None, chrom=None):
"""The constructor reads of all phenotypes all contigs, and converts this to one dictionary with contig objects with the contig ID as key. if the phenotypes == None, an empty dictionary... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GffReader:
"""The GffReader reads a GFF3 file."""
def __init__(self, phenotypes=None, chrom=None):
"""The constructor reads of all phenotypes all contigs, and converts this to one dictionary with contig objects with the contig ID as key. if the phenotypes == None, an empty dictionary is created a... | the_stack_v2_python_sparse | pythonCodebase/src/programs/phenotyper/Readers.py | JJacobi13/VLPB | train | 0 |
4a9d8dc4307c0dfd9bc88d181f5442d6ccf8ef4f | [
"if isinstance(building_type, str):\n return self.get(name=building_type.lower())\nraise TypeError(f'Building type must be a string but got {type(building_type)}')",
"if isinstance(path_to_csv_file, str):\n loader = BuildingTypeLoader(path_to_csv_file)\n loader.load()"
] | <|body_start_0|>
if isinstance(building_type, str):
return self.get(name=building_type.lower())
raise TypeError(f'Building type must be a string but got {type(building_type)}')
<|end_body_0|>
<|body_start_1|>
if isinstance(path_to_csv_file, str):
loader = BuildingTypeLoa... | BuildingTypeManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BuildingTypeManager:
def get_building_by_type(self, building_type: str) -> BuildingType:
"""Return BuildingType instance, raise error if not found"""
<|body_0|>
def load_building_type(self, path_to_csv_file='./csv_data/buildingType.csv', force_2d=False):
"""Load csv ... | stack_v2_sparse_classes_36k_train_002555 | 9,041 | permissive | [
{
"docstring": "Return BuildingType instance, raise error if not found",
"name": "get_building_by_type",
"signature": "def get_building_by_type(self, building_type: str) -> BuildingType"
},
{
"docstring": "Load csv data from given path. It must contains header",
"name": "load_building_type",... | 2 | null | Implement the Python class `BuildingTypeManager` described below.
Class description:
Implement the BuildingTypeManager class.
Method signatures and docstrings:
- def get_building_by_type(self, building_type: str) -> BuildingType: Return BuildingType instance, raise error if not found
- def load_building_type(self, pa... | Implement the Python class `BuildingTypeManager` described below.
Class description:
Implement the BuildingTypeManager class.
Method signatures and docstrings:
- def get_building_by_type(self, building_type: str) -> BuildingType: Return BuildingType instance, raise error if not found
- def load_building_type(self, pa... | 142c623da4722f7443d76fc8bef0e56c0aa3d48e | <|skeleton|>
class BuildingTypeManager:
def get_building_by_type(self, building_type: str) -> BuildingType:
"""Return BuildingType instance, raise error if not found"""
<|body_0|>
def load_building_type(self, path_to_csv_file='./csv_data/buildingType.csv', force_2d=False):
"""Load csv ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BuildingTypeManager:
def get_building_by_type(self, building_type: str) -> BuildingType:
"""Return BuildingType instance, raise error if not found"""
if isinstance(building_type, str):
return self.get(name=building_type.lower())
raise TypeError(f'Building type must be a str... | the_stack_v2_python_sparse | app/models/constants/building_type.py | polowis/virtComp | train | 0 | |
cfd64dfb7b29ad67fbe6888ad41d0f17652a7b7d | [
"super(VarifocalLoss, self).__init__()\nassert alpha >= 0.0\nself.use_sigmoid = use_sigmoid\nself.alpha = alpha\nself.gamma = gamma\nself.iou_weighted = iou_weighted\nself.reduction = reduction\nself.loss_weight = loss_weight",
"loss = self.loss_weight * varifocal_loss(pred, target, alpha=self.alpha, gamma=self.g... | <|body_start_0|>
super(VarifocalLoss, self).__init__()
assert alpha >= 0.0
self.use_sigmoid = use_sigmoid
self.alpha = alpha
self.gamma = gamma
self.iou_weighted = iou_weighted
self.reduction = reduction
self.loss_weight = loss_weight
<|end_body_0|>
<|bod... | VarifocalLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VarifocalLoss:
def __init__(self, use_sigmoid=True, alpha=0.75, gamma=2.0, iou_weighted=True, reduction='mean', loss_weight=1.0):
"""`Varifocal Loss <https://arxiv.org/abs/2008.13367>`_ Args: use_sigmoid (bool, optional): Whether the prediction is used for sigmoid or softmax. Defaults to... | stack_v2_sparse_classes_36k_train_002556 | 5,886 | permissive | [
{
"docstring": "`Varifocal Loss <https://arxiv.org/abs/2008.13367>`_ Args: use_sigmoid (bool, optional): Whether the prediction is used for sigmoid or softmax. Defaults to True. alpha (float, optional): A balance factor for the negative part of Varifocal Loss, which is different from the alpha of Focal Loss. De... | 2 | null | Implement the Python class `VarifocalLoss` described below.
Class description:
Implement the VarifocalLoss class.
Method signatures and docstrings:
- def __init__(self, use_sigmoid=True, alpha=0.75, gamma=2.0, iou_weighted=True, reduction='mean', loss_weight=1.0): `Varifocal Loss <https://arxiv.org/abs/2008.13367>`_ ... | Implement the Python class `VarifocalLoss` described below.
Class description:
Implement the VarifocalLoss class.
Method signatures and docstrings:
- def __init__(self, use_sigmoid=True, alpha=0.75, gamma=2.0, iou_weighted=True, reduction='mean', loss_weight=1.0): `Varifocal Loss <https://arxiv.org/abs/2008.13367>`_ ... | bd83b98342b0a6bc8d8dcd5936233aeda1e32167 | <|skeleton|>
class VarifocalLoss:
def __init__(self, use_sigmoid=True, alpha=0.75, gamma=2.0, iou_weighted=True, reduction='mean', loss_weight=1.0):
"""`Varifocal Loss <https://arxiv.org/abs/2008.13367>`_ Args: use_sigmoid (bool, optional): Whether the prediction is used for sigmoid or softmax. Defaults to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VarifocalLoss:
def __init__(self, use_sigmoid=True, alpha=0.75, gamma=2.0, iou_weighted=True, reduction='mean', loss_weight=1.0):
"""`Varifocal Loss <https://arxiv.org/abs/2008.13367>`_ Args: use_sigmoid (bool, optional): Whether the prediction is used for sigmoid or softmax. Defaults to True. alpha (... | the_stack_v2_python_sparse | ppdet/modeling/losses/varifocal_loss.py | PaddlePaddle/PaddleDetection | train | 12,523 | |
e811a2109ec02a65eaa1c873d5bcb58ab8721ffd | [
"self.capacity = capacity\nself.usage_frequency = []\nself.lru = {}",
"if key in self.lru:\n self.usage_frequency.remove(key)\n self.usage_frequency.append(key)\n return self.lru[key]\nreturn -1",
"if key in self.lru:\n self.lru[key] = value\n self.usage_frequency.remove(key)\n self.usage_freq... | <|body_start_0|>
self.capacity = capacity
self.usage_frequency = []
self.lru = {}
<|end_body_0|>
<|body_start_1|>
if key in self.lru:
self.usage_frequency.remove(key)
self.usage_frequency.append(key)
return self.lru[key]
return -1
<|end_body_1... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_002557 | 1,163 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: None",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_002592 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None
<|sk... | 4169b02f43538545d0bcddecbf68ca446f18890f | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.usage_frequency = []
self.lru = {}
def get(self, key):
""":type key: int :rtype: int"""
if key in self.lru:
self.usage_frequency.remove(key)
... | the_stack_v2_python_sparse | Leetcode/hashmap-hashset/lru-cache.py | Poppy22/coding-practice | train | 0 | |
c0786cd138ea47293d63911108d026d7a16b37c7 | [
"test_graph = class_dependency.JavaClassDependencyGraph()\ntest_graph.add_edge_if_new(self.CLASS_1, self.CLASS_2)\ntest_graph.add_edge_if_new(self.CLASS_1, self.CLASS_3)\ntest_graph.add_edge_if_new(self.CLASS_2, self.CLASS_3)\ntest_graph.get_node_by_key(self.CLASS_1).add_nested_class(self.CLASS_1_NESTED_1)\ntest_gr... | <|body_start_0|>
test_graph = class_dependency.JavaClassDependencyGraph()
test_graph.add_edge_if_new(self.CLASS_1, self.CLASS_2)
test_graph.add_edge_if_new(self.CLASS_1, self.CLASS_3)
test_graph.add_edge_if_new(self.CLASS_2, self.CLASS_3)
test_graph.get_node_by_key(self.CLASS_1).... | Unit tests for various de/serialization functions. | TestSerialization | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSerialization:
"""Unit tests for various de/serialization functions."""
def test_class_serialization(self):
"""Tests JSON serialization of a class dependency graph."""
<|body_0|>
def test_package_serialization(self):
"""Tests JSON serialization of a package d... | stack_v2_sparse_classes_36k_train_002558 | 7,187 | permissive | [
{
"docstring": "Tests JSON serialization of a class dependency graph.",
"name": "test_class_serialization",
"signature": "def test_class_serialization(self)"
},
{
"docstring": "Tests JSON serialization of a package dependency graph.",
"name": "test_package_serialization",
"signature": "d... | 3 | stack_v2_sparse_classes_30k_train_010131 | Implement the Python class `TestSerialization` described below.
Class description:
Unit tests for various de/serialization functions.
Method signatures and docstrings:
- def test_class_serialization(self): Tests JSON serialization of a class dependency graph.
- def test_package_serialization(self): Tests JSON seriali... | Implement the Python class `TestSerialization` described below.
Class description:
Unit tests for various de/serialization functions.
Method signatures and docstrings:
- def test_class_serialization(self): Tests JSON serialization of a class dependency graph.
- def test_package_serialization(self): Tests JSON seriali... | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | <|skeleton|>
class TestSerialization:
"""Unit tests for various de/serialization functions."""
def test_class_serialization(self):
"""Tests JSON serialization of a class dependency graph."""
<|body_0|>
def test_package_serialization(self):
"""Tests JSON serialization of a package d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestSerialization:
"""Unit tests for various de/serialization functions."""
def test_class_serialization(self):
"""Tests JSON serialization of a class dependency graph."""
test_graph = class_dependency.JavaClassDependencyGraph()
test_graph.add_edge_if_new(self.CLASS_1, self.CLASS_... | the_stack_v2_python_sparse | tools/android/dependency_analysis/serialization_unittest.py | chromium/chromium | train | 17,408 |
560506bdedf73f85c26f9b8175c422fc6d162ac2 | [
"super(InteractiveBrokersPriceHandler, self).__init__()\nself.conn = ibConnection(clientId=IB.data_handler_id.value, port=IB.port.value)\nself.conn.register(self.__tick_price_handler, message.tickPrice)\nif not self.conn.connect():\n raise ValueError('Odin was unable to connect to the Trader Workstation.')\ntoda... | <|body_start_0|>
super(InteractiveBrokersPriceHandler, self).__init__()
self.conn = ibConnection(clientId=IB.data_handler_id.value, port=IB.port.value)
self.conn.register(self.__tick_price_handler, message.tickPrice)
if not self.conn.connect():
raise ValueError('Odin was unab... | Interactive Brokers Price Handler Class | InteractiveBrokersPriceHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InteractiveBrokersPriceHandler:
"""Interactive Brokers Price Handler Class"""
def __init__(self):
"""Initialize parameters of the Interactive Brokers price handler object."""
<|body_0|>
def __tick_price_handler(self, msg):
"""Handle incoming prices from the Trade... | stack_v2_sparse_classes_36k_train_002559 | 2,674 | permissive | [
{
"docstring": "Initialize parameters of the Interactive Brokers price handler object.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Handle incoming prices from the Trader Workstation.",
"name": "__tick_price_handler",
"signature": "def __tick_price_handler(s... | 3 | null | Implement the Python class `InteractiveBrokersPriceHandler` described below.
Class description:
Interactive Brokers Price Handler Class
Method signatures and docstrings:
- def __init__(self): Initialize parameters of the Interactive Brokers price handler object.
- def __tick_price_handler(self, msg): Handle incoming ... | Implement the Python class `InteractiveBrokersPriceHandler` described below.
Class description:
Interactive Brokers Price Handler Class
Method signatures and docstrings:
- def __init__(self): Initialize parameters of the Interactive Brokers price handler object.
- def __tick_price_handler(self, msg): Handle incoming ... | e2e9d638c68947d24f1260d35a3527dd84c2523f | <|skeleton|>
class InteractiveBrokersPriceHandler:
"""Interactive Brokers Price Handler Class"""
def __init__(self):
"""Initialize parameters of the Interactive Brokers price handler object."""
<|body_0|>
def __tick_price_handler(self, msg):
"""Handle incoming prices from the Trade... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InteractiveBrokersPriceHandler:
"""Interactive Brokers Price Handler Class"""
def __init__(self):
"""Initialize parameters of the Interactive Brokers price handler object."""
super(InteractiveBrokersPriceHandler, self).__init__()
self.conn = ibConnection(clientId=IB.data_handler_i... | the_stack_v2_python_sparse | odin/handlers/data_handler/price_handler/interactive_brokers_price_handler.py | stjordanis/Odin | train | 0 |
4154c4a49fa59366b8a88e965a5b903ecc2e7a9a | [
"self.c = [0] * (len(nums) + 1)\nself.nums = nums\nfor i in range(len(self.nums)):\n k = i + 1\n while k <= len(self.nums):\n self.c[k] += self.nums[i]\n k += k & -k",
"diff = val - self.nums[i]\nself.nums[i] = val\ni += 1\nwhile i <= len(self.nums):\n self.c[i] += diff\n i += i & -i",
... | <|body_start_0|>
self.c = [0] * (len(nums) + 1)
self.nums = nums
for i in range(len(self.nums)):
k = i + 1
while k <= len(self.nums):
self.c[k] += self.nums[i]
k += k & -k
<|end_body_0|>
<|body_start_1|>
diff = val - self.nums[i]
... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: void"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_36k_train_002560 | 2,692 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type val: int :rtype: void",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
... | 3 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: void
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: void
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | 36cb33af758b1d01da35982481a8bbfbee5c2810 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: void"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self.c = [0] * (len(nums) + 1)
self.nums = nums
for i in range(len(self.nums)):
k = i + 1
while k <= len(self.nums):
self.c[k] += self.nums[i]
k += k & -k
... | the_stack_v2_python_sparse | LeetCode/rangeSumQueryMutable.py | dicao425/algorithmExercise | train | 0 | |
4f4f530cda1eff18842990d24468d879711a7aa1 | [
"self.input_type = input_type\nself.face_model = keras.models.load_model(configuration.MODEL_PATH + 'CNN_face_regression.h5')\nself.EEG_model = keras.models.load_model(configuration.MODEL_PATH + 'LSTM_EEG_regression.h5')\nself.todiscrete_model = keras.models.load_model(configuration.MODEL_PATH + 'continuous_to_disc... | <|body_start_0|>
self.input_type = input_type
self.face_model = keras.models.load_model(configuration.MODEL_PATH + 'CNN_face_regression.h5')
self.EEG_model = keras.models.load_model(configuration.MODEL_PATH + 'LSTM_EEG_regression.h5')
self.todiscrete_model = keras.models.load_model(confi... | This class is used to return the emotion in real time. Attribute: input_tpye: input_type: 'file' indicates that the stream is from file. In other case, the stream will from the default camera. face_model: the model for predicting emotion by faces. EEG_model: the model for predicting emotion by EEG. todiscrete_model: th... | EmotionReader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmotionReader:
"""This class is used to return the emotion in real time. Attribute: input_tpye: input_type: 'file' indicates that the stream is from file. In other case, the stream will from the default camera. face_model: the model for predicting emotion by faces. EEG_model: the model for predic... | stack_v2_sparse_classes_36k_train_002561 | 16,328 | permissive | [
{
"docstring": "Arguments: input_type: 'file' indicates that the stream is from file. In other case, the stream will from the defalt camera.",
"name": "__init__",
"signature": "def __init__(self, input_type)"
},
{
"docstring": "Returns: valence: the valence predicted by faces arousal: the arousa... | 5 | stack_v2_sparse_classes_30k_val_000541 | Implement the Python class `EmotionReader` described below.
Class description:
This class is used to return the emotion in real time. Attribute: input_tpye: input_type: 'file' indicates that the stream is from file. In other case, the stream will from the default camera. face_model: the model for predicting emotion by... | Implement the Python class `EmotionReader` described below.
Class description:
This class is used to return the emotion in real time. Attribute: input_tpye: input_type: 'file' indicates that the stream is from file. In other case, the stream will from the default camera. face_model: the model for predicting emotion by... | 531f646dcb493dce2575af3b9d77403ebc1f4a35 | <|skeleton|>
class EmotionReader:
"""This class is used to return the emotion in real time. Attribute: input_tpye: input_type: 'file' indicates that the stream is from file. In other case, the stream will from the default camera. face_model: the model for predicting emotion by faces. EEG_model: the model for predic... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmotionReader:
"""This class is used to return the emotion in real time. Attribute: input_tpye: input_type: 'file' indicates that the stream is from file. In other case, the stream will from the default camera. face_model: the model for predicting emotion by faces. EEG_model: the model for predicting emotion ... | the_stack_v2_python_sparse | MindLink-Eumpy/real_time_detection/GUI/MLE_tool/tool.py | wozu-dichter/MindLink-Explorer | train | 0 |
e603b24693ab033cb8967a8234f78f500d892203 | [
"current = self.head\nwhile current is not None:\n if current.get_data() == item:\n return True\n else:\n if current.get_data() > item:\n return False\n current = current.get_next()\nreturn False",
"current = self.head\nprevious = None\nstop = False\nwhile current is not None... | <|body_start_0|>
current = self.head
while current is not None:
if current.get_data() == item:
return True
else:
if current.get_data() > item:
return False
current = current.get_next()
return False
<|end_... | Ordered List class, a collection of nodes indexed, but the numbers inside must be in order. Inherits __init__, is_empty, size and remove from UnorderedList. | OrderedList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrderedList:
"""Ordered List class, a collection of nodes indexed, but the numbers inside must be in order. Inherits __init__, is_empty, size and remove from UnorderedList."""
def search(self, item):
"""Return True if the item is on the list. O(n)."""
<|body_0|>
def add(... | stack_v2_sparse_classes_36k_train_002562 | 3,468 | no_license | [
{
"docstring": "Return True if the item is on the list. O(n).",
"name": "search",
"signature": "def search(self, item)"
},
{
"docstring": "Add a new item on the correct position.",
"name": "add",
"signature": "def add(self, item)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002035 | Implement the Python class `OrderedList` described below.
Class description:
Ordered List class, a collection of nodes indexed, but the numbers inside must be in order. Inherits __init__, is_empty, size and remove from UnorderedList.
Method signatures and docstrings:
- def search(self, item): Return True if the item ... | Implement the Python class `OrderedList` described below.
Class description:
Ordered List class, a collection of nodes indexed, but the numbers inside must be in order. Inherits __init__, is_empty, size and remove from UnorderedList.
Method signatures and docstrings:
- def search(self, item): Return True if the item ... | 8b01517c9cc3a9b07e6a103d52b87b5f56c4d394 | <|skeleton|>
class OrderedList:
"""Ordered List class, a collection of nodes indexed, but the numbers inside must be in order. Inherits __init__, is_empty, size and remove from UnorderedList."""
def search(self, item):
"""Return True if the item is on the list. O(n)."""
<|body_0|>
def add(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OrderedList:
"""Ordered List class, a collection of nodes indexed, but the numbers inside must be in order. Inherits __init__, is_empty, size and remove from UnorderedList."""
def search(self, item):
"""Return True if the item is on the list. O(n)."""
current = self.head
while cur... | the_stack_v2_python_sparse | LinearStructures/LinkedList/linkedlist.py | ohduran/problemsolvingalgorithms | train | 0 |
64e533586c7071fd91ca81903cd3a1fa77ebd982 | [
"if not digits:\n return [1]\nelif digits[-1] == 9:\n digits[-1] = 0\n digits[:-1] = self.plusOne(digits[:-1])\nelse:\n digits[-1] += 1\nreturn digits",
"if len(digits) == 0:\n return [1]\nif digits[-1] == 9:\n return self.plusOne(digits[:-1]) + [0]\nreturn digits[:-1] + [digits[-1] + 1]",
"n ... | <|body_start_0|>
if not digits:
return [1]
elif digits[-1] == 9:
digits[-1] = 0
digits[:-1] = self.plusOne(digits[:-1])
else:
digits[-1] += 1
return digits
<|end_body_0|>
<|body_start_1|>
if len(digits) == 0:
return [1]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def plusOne(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_0|>
def plusOne1(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_1|>
def plusOne2(self, digits):
""":type digits: List[int] :rtype: ... | stack_v2_sparse_classes_36k_train_002563 | 1,164 | no_license | [
{
"docstring": ":type digits: List[int] :rtype: List[int]",
"name": "plusOne",
"signature": "def plusOne(self, digits)"
},
{
"docstring": ":type digits: List[int] :rtype: List[int]",
"name": "plusOne1",
"signature": "def plusOne1(self, digits)"
},
{
"docstring": ":type digits: Li... | 3 | stack_v2_sparse_classes_30k_train_017186 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def plusOne(self, digits): :type digits: List[int] :rtype: List[int]
- def plusOne1(self, digits): :type digits: List[int] :rtype: List[int]
- def plusOne2(self, digits): :type d... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def plusOne(self, digits): :type digits: List[int] :rtype: List[int]
- def plusOne1(self, digits): :type digits: List[int] :rtype: List[int]
- def plusOne2(self, digits): :type d... | 863b89be674a82eef60c0f33d726ac08d43f2e01 | <|skeleton|>
class Solution:
def plusOne(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_0|>
def plusOne1(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_1|>
def plusOne2(self, digits):
""":type digits: List[int] :rtype: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def plusOne(self, digits):
""":type digits: List[int] :rtype: List[int]"""
if not digits:
return [1]
elif digits[-1] == 9:
digits[-1] = 0
digits[:-1] = self.plusOne(digits[:-1])
else:
digits[-1] += 1
return digit... | the_stack_v2_python_sparse | q66_Plus_One.py | Ryuya1995/leetcode | train | 0 | |
67cae395decd2f28d9dd7f4305297142fa716c20 | [
"num_dens_mean = {}\nnum_dens_std = {}\nfor key in HOD_params['tracer_flags'].keys():\n if HOD_params['tracer_flags'][key]:\n num_dens_mean[key] = data_params['tracer_density_mean'][key]\n num_dens_std[key] = data_params['tracer_density_std'][key]\nself.num_dens_mean = num_dens_mean\nself.num_dens_... | <|body_start_0|>
num_dens_mean = {}
num_dens_std = {}
for key in HOD_params['tracer_flags'].keys():
if HOD_params['tracer_flags'][key]:
num_dens_mean[key] = data_params['tracer_density_mean'][key]
num_dens_std[key] = data_params['tracer_density_std'][k... | Dummy object for calculating a likelihood | wp_Data | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class wp_Data:
"""Dummy object for calculating a likelihood"""
def __init__(self, data_params, HOD_params):
"""Constructor of the power spectrum data"""
<|body_0|>
def compute_likelihood(self, theory_clustering, theory_density):
"""Computes the likelihood using informa... | stack_v2_sparse_classes_36k_train_002564 | 5,451 | no_license | [
{
"docstring": "Constructor of the power spectrum data",
"name": "__init__",
"signature": "def __init__(self, data_params, HOD_params)"
},
{
"docstring": "Computes the likelihood using information from the context",
"name": "compute_likelihood",
"signature": "def compute_likelihood(self,... | 2 | stack_v2_sparse_classes_30k_val_000506 | Implement the Python class `wp_Data` described below.
Class description:
Dummy object for calculating a likelihood
Method signatures and docstrings:
- def __init__(self, data_params, HOD_params): Constructor of the power spectrum data
- def compute_likelihood(self, theory_clustering, theory_density): Computes the lik... | Implement the Python class `wp_Data` described below.
Class description:
Dummy object for calculating a likelihood
Method signatures and docstrings:
- def __init__(self, data_params, HOD_params): Constructor of the power spectrum data
- def compute_likelihood(self, theory_clustering, theory_density): Computes the lik... | 1323009ee34c4a9111b52a4810d8e9d0b0bc62ee | <|skeleton|>
class wp_Data:
"""Dummy object for calculating a likelihood"""
def __init__(self, data_params, HOD_params):
"""Constructor of the power spectrum data"""
<|body_0|>
def compute_likelihood(self, theory_clustering, theory_density):
"""Computes the likelihood using informa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class wp_Data:
"""Dummy object for calculating a likelihood"""
def __init__(self, data_params, HOD_params):
"""Constructor of the power spectrum data"""
num_dens_mean = {}
num_dens_std = {}
for key in HOD_params['tracer_flags'].keys():
if HOD_params['tracer_flags'][k... | the_stack_v2_python_sparse | likelihood_lowz.py | SandyYuan/BOSSfits | train | 0 |
d030816cb68fe663794ef6b2575728c2615b53ad | [
"super(ExternalNNLOReweighter, self).__init__('NNLO reweighter', *executable_path)\nself.add_keyword('NNLO_reweighting_inputs')\nself.add_keyword('NNLO_output_weights')",
"self.expose()\nif len(self.NNLO_reweighting_inputs) == 0:\n return False\nif not isinstance(self.NNLO_reweighting_inputs, collections.Order... | <|body_start_0|>
super(ExternalNNLOReweighter, self).__init__('NNLO reweighter', *executable_path)
self.add_keyword('NNLO_reweighting_inputs')
self.add_keyword('NNLO_output_weights')
<|end_body_0|>
<|body_start_1|>
self.expose()
if len(self.NNLO_reweighting_inputs) == 0:
... | ! Class for running external NNLO reweighting process. @author James Robinson <james.robinson@cern.ch> | ExternalNNLOReweighter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExternalNNLOReweighter:
"""! Class for running external NNLO reweighting process. @author James Robinson <james.robinson@cern.ch>"""
def __init__(self, *executable_path):
"""! Constructor. @param executable_path path to appropriate PowhegBox executable."""
<|body_0|>
def... | stack_v2_sparse_classes_36k_train_002565 | 2,456 | no_license | [
{
"docstring": "! Constructor. @param executable_path path to appropriate PowhegBox executable.",
"name": "__init__",
"signature": "def __init__(self, *executable_path)"
},
{
"docstring": "! Report whether the NNLO reweighting process should be scheduled. @param process PowhegBox process.",
... | 2 | null | Implement the Python class `ExternalNNLOReweighter` described below.
Class description:
! Class for running external NNLO reweighting process. @author James Robinson <james.robinson@cern.ch>
Method signatures and docstrings:
- def __init__(self, *executable_path): ! Constructor. @param executable_path path to appropr... | Implement the Python class `ExternalNNLOReweighter` described below.
Class description:
! Class for running external NNLO reweighting process. @author James Robinson <james.robinson@cern.ch>
Method signatures and docstrings:
- def __init__(self, *executable_path): ! Constructor. @param executable_path path to appropr... | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | <|skeleton|>
class ExternalNNLOReweighter:
"""! Class for running external NNLO reweighting process. @author James Robinson <james.robinson@cern.ch>"""
def __init__(self, *executable_path):
"""! Constructor. @param executable_path path to appropriate PowhegBox executable."""
<|body_0|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExternalNNLOReweighter:
"""! Class for running external NNLO reweighting process. @author James Robinson <james.robinson@cern.ch>"""
def __init__(self, *executable_path):
"""! Constructor. @param executable_path path to appropriate PowhegBox executable."""
super(ExternalNNLOReweighter, se... | the_stack_v2_python_sparse | athena/Generators/PowhegControl/python/processes/external/external_nnlo_reweighter.py | rushioda/PIXELVALID_athena | train | 1 |
552c7c695cc01b96fb04ccf415654e6bb5787d78 | [
"EasyFrame.__init__(self, title='Tax Calculator')\nself.addLabel(text='Gross Income', row=0, column=0)\nself.incomeField = self.addFloatField(value=0.0, row=0, column=1, precision=2)\nself.addLabel(text='Dependents', row=1, column=0)\nself.depField = self.addIntegerField(value=0, row=1, column=1)\nself.addLabel(tex... | <|body_start_0|>
EasyFrame.__init__(self, title='Tax Calculator')
self.addLabel(text='Gross Income', row=0, column=0)
self.incomeField = self.addFloatField(value=0.0, row=0, column=1, precision=2)
self.addLabel(text='Dependents', row=1, column=0)
self.depField = self.addIntegerFi... | Application window for the tax calculator. | TaxCalculator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaxCalculator:
"""Application window for the tax calculator."""
def __init__(self):
"""Sets up the window and the widgets."""
<|body_0|>
def computeTax(self):
"""Obtains the data from the input field and uses them to compute the tax, which is sent to the output f... | stack_v2_sparse_classes_36k_train_002566 | 3,290 | no_license | [
{
"docstring": "Sets up the window and the widgets.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Obtains the data from the input field and uses them to compute the tax, which is sent to the output field.",
"name": "computeTax",
"signature": "def computeTax(s... | 2 | null | Implement the Python class `TaxCalculator` described below.
Class description:
Application window for the tax calculator.
Method signatures and docstrings:
- def __init__(self): Sets up the window and the widgets.
- def computeTax(self): Obtains the data from the input field and uses them to compute the tax, which is... | Implement the Python class `TaxCalculator` described below.
Class description:
Application window for the tax calculator.
Method signatures and docstrings:
- def __init__(self): Sets up the window and the widgets.
- def computeTax(self): Obtains the data from the input field and uses them to compute the tax, which is... | 30375264cf0103e3455fdf92c35a2c5c15b5d7ef | <|skeleton|>
class TaxCalculator:
"""Application window for the tax calculator."""
def __init__(self):
"""Sets up the window and the widgets."""
<|body_0|>
def computeTax(self):
"""Obtains the data from the input field and uses them to compute the tax, which is sent to the output f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TaxCalculator:
"""Application window for the tax calculator."""
def __init__(self):
"""Sets up the window and the widgets."""
EasyFrame.__init__(self, title='Tax Calculator')
self.addLabel(text='Gross Income', row=0, column=0)
self.incomeField = self.addFloatField(value=0.... | the_stack_v2_python_sparse | Ch8 exercises/taxformwithgui.py | davelpat/Fundamentals_of_Python | train | 1 |
61b76cb111914bf25a41549bc5d479cf805cda94 | [
"self.capacity = capacity\nself.counter = 0\nself.key_time = {}\nself.key_value = {}",
"self.counter += 1\nif self.key_value.has_key(key):\n self.key_time[key] = self.counter\n return self.key_value[key]\nelse:\n return -1",
"self.key_value[key] = value\nself.counter += 1\nself.key_time[key] = self.cou... | <|body_start_0|>
self.capacity = capacity
self.counter = 0
self.key_time = {}
self.key_value = {}
<|end_body_0|>
<|body_start_1|>
self.counter += 1
if self.key_value.has_key(key):
self.key_time[key] = self.counter
return self.key_value[key]
... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_002567 | 1,082 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_002990 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | c8f6ec8033486aa4b38e6f8170b6482527e30860 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.counter = 0
self.key_time = {}
self.key_value = {}
def get(self, key):
""":type key: int :rtype: int"""
self.counter += 1
if self.key_value.has_k... | the_stack_v2_python_sparse | leetcode/lru-cache.py | jasujaayush/Random | train | 0 | |
0c8edfac9360108f11124e1f3a2617f5cd4d674b | [
"self.count = 0\n\ndef dfs(nums, target):\n if target == 0:\n self.count += 1\n return\n if target < 0:\n return\n for n in nums:\n dfs(nums, target - n)\ndfs(nums, target)\nreturn self.count",
"def dfs(nums, temp_sum, target, d):\n if target == temp_sum:\n return 1\... | <|body_start_0|>
self.count = 0
def dfs(nums, target):
if target == 0:
self.count += 1
return
if target < 0:
return
for n in nums:
dfs(nums, target - n)
dfs(nums, target)
return self.coun... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combinationSum4(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def combinationSum41(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
def combinationSum42(se... | stack_v2_sparse_classes_36k_train_002568 | 2,690 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "combinationSum4",
"signature": "def combinationSum4(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "combinationSum41",
"signature": "def combinationSum41(... | 3 | stack_v2_sparse_classes_30k_train_013965 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum4(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def combinationSum41(self, nums, target): :type nums: List[int] :type target: int :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum4(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def combinationSum41(self, nums, target): :type nums: List[int] :type target: int :... | 857b8c7fccfe8216da59228c1cf3675444855673 | <|skeleton|>
class Solution:
def combinationSum4(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def combinationSum41(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
def combinationSum42(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def combinationSum4(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
self.count = 0
def dfs(nums, target):
if target == 0:
self.count += 1
return
if target < 0:
return
... | the_stack_v2_python_sparse | algorithm/Combination-Sum-IV.py | atashi/LLL | train | 0 | |
aa0fc492a88134af7edba77475dac41edbea8cb0 | [
"data = get_enum_items_row_by_id(pk)\nif not data:\n raise NotFound\nresult = marshal(data, fields_item_enum_items_cn, envelope=structure_key_item_cn)\nreturn jsonify(result)",
"result = delete_enum_items(pk)\nif result:\n success_msg = SUCCESS_MSG.copy()\n return make_response(jsonify(success_msg), 204)... | <|body_start_0|>
data = get_enum_items_row_by_id(pk)
if not data:
raise NotFound
result = marshal(data, fields_item_enum_items_cn, envelope=structure_key_item_cn)
return jsonify(result)
<|end_body_0|>
<|body_start_1|>
result = delete_enum_items(pk)
if result:... | EnumItemsResource | EnumItemsResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnumItemsResource:
"""EnumItemsResource"""
def get(self, pk):
"""Example: curl http://0.0.0.0:5000/yonyou/enum_item/1 :param pk: :return:"""
<|body_0|>
def delete(self, pk):
"""Example: curl http://0.0.0.0:5000/yonyou/enum_item/1 -X DELETE :param pk: :return:"""
... | stack_v2_sparse_classes_36k_train_002569 | 4,160 | permissive | [
{
"docstring": "Example: curl http://0.0.0.0:5000/yonyou/enum_item/1 :param pk: :return:",
"name": "get",
"signature": "def get(self, pk)"
},
{
"docstring": "Example: curl http://0.0.0.0:5000/yonyou/enum_item/1 -X DELETE :param pk: :return:",
"name": "delete",
"signature": "def delete(se... | 2 | stack_v2_sparse_classes_30k_train_007053 | Implement the Python class `EnumItemsResource` described below.
Class description:
EnumItemsResource
Method signatures and docstrings:
- def get(self, pk): Example: curl http://0.0.0.0:5000/yonyou/enum_item/1 :param pk: :return:
- def delete(self, pk): Example: curl http://0.0.0.0:5000/yonyou/enum_item/1 -X DELETE :p... | Implement the Python class `EnumItemsResource` described below.
Class description:
EnumItemsResource
Method signatures and docstrings:
- def get(self, pk): Example: curl http://0.0.0.0:5000/yonyou/enum_item/1 :param pk: :return:
- def delete(self, pk): Example: curl http://0.0.0.0:5000/yonyou/enum_item/1 -X DELETE :p... | 6ef54f3f7efbbaff6169e963dcf45ab25e11e593 | <|skeleton|>
class EnumItemsResource:
"""EnumItemsResource"""
def get(self, pk):
"""Example: curl http://0.0.0.0:5000/yonyou/enum_item/1 :param pk: :return:"""
<|body_0|>
def delete(self, pk):
"""Example: curl http://0.0.0.0:5000/yonyou/enum_item/1 -X DELETE :param pk: :return:"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EnumItemsResource:
"""EnumItemsResource"""
def get(self, pk):
"""Example: curl http://0.0.0.0:5000/yonyou/enum_item/1 :param pk: :return:"""
data = get_enum_items_row_by_id(pk)
if not data:
raise NotFound
result = marshal(data, fields_item_enum_items_cn, envelo... | the_stack_v2_python_sparse | web_api/yonyou/resources/enum_items.py | zhanghe06/flask_restful | train | 2 |
ebd0adda3d25ec5a178f55e622ebaa639de6de45 | [
"if image_meta is None:\n image_meta = {}\nimage_meta = copy.deepcopy(image_meta)\nimage_meta['properties'] = objects.ImageMetaProps.from_dict(image_meta.get('properties', {}))\nfor fld in NULLABLE_STRING_FIELDS:\n if fld in image_meta and image_meta[fld] is None:\n image_meta[fld] = ''\nfor fld in NUL... | <|body_start_0|>
if image_meta is None:
image_meta = {}
image_meta = copy.deepcopy(image_meta)
image_meta['properties'] = objects.ImageMetaProps.from_dict(image_meta.get('properties', {}))
for fld in NULLABLE_STRING_FIELDS:
if fld in image_meta and image_meta[fld]... | ImageMeta | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageMeta:
def from_dict(cls, image_meta):
"""Create instance from image metadata dict :param image_meta: image metadata dictionary Creates a new object instance, initializing from the properties associated with the image metadata instance :returns: an ImageMeta instance"""
<|bod... | stack_v2_sparse_classes_36k_train_002570 | 31,126 | permissive | [
{
"docstring": "Create instance from image metadata dict :param image_meta: image metadata dictionary Creates a new object instance, initializing from the properties associated with the image metadata instance :returns: an ImageMeta instance",
"name": "from_dict",
"signature": "def from_dict(cls, image_... | 3 | stack_v2_sparse_classes_30k_train_015090 | Implement the Python class `ImageMeta` described below.
Class description:
Implement the ImageMeta class.
Method signatures and docstrings:
- def from_dict(cls, image_meta): Create instance from image metadata dict :param image_meta: image metadata dictionary Creates a new object instance, initializing from the prope... | Implement the Python class `ImageMeta` described below.
Class description:
Implement the ImageMeta class.
Method signatures and docstrings:
- def from_dict(cls, image_meta): Create instance from image metadata dict :param image_meta: image metadata dictionary Creates a new object instance, initializing from the prope... | 065c5906d2da3e2bb6eeb3a7a15d4cd8d98b35e9 | <|skeleton|>
class ImageMeta:
def from_dict(cls, image_meta):
"""Create instance from image metadata dict :param image_meta: image metadata dictionary Creates a new object instance, initializing from the properties associated with the image metadata instance :returns: an ImageMeta instance"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageMeta:
def from_dict(cls, image_meta):
"""Create instance from image metadata dict :param image_meta: image metadata dictionary Creates a new object instance, initializing from the properties associated with the image metadata instance :returns: an ImageMeta instance"""
if image_meta is No... | the_stack_v2_python_sparse | nova/objects/image_meta.py | openstack/nova | train | 2,287 | |
d424df40745d721af56378752862d40ed6d8a0b6 | [
"super(Encoder, self).__init__()\nself.length = length\nself.stride = self.length // _OVERLAP_FACTOR\nself.num_filters = num_filters\nself.conv_layer = layers.Conv1D(filters=num_filters, kernel_size=length, strides=self.stride, use_bias=False, padding='SAME')",
"x_in = tf.expand_dims(x_in, axis=2)\nencoded_signal... | <|body_start_0|>
super(Encoder, self).__init__()
self.length = length
self.stride = self.length // _OVERLAP_FACTOR
self.num_filters = num_filters
self.conv_layer = layers.Conv1D(filters=num_filters, kernel_size=length, strides=self.stride, use_bias=False, padding='SAME')
<|end_bo... | The encoder model for the learned decomposition, overlap between decomposed winodws is 50% by default following the Conv-TasNet paper. | Encoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
"""The encoder model for the learned decomposition, overlap between decomposed winodws is 50% by default following the Conv-TasNet paper."""
def __init__(self, length, num_filters):
"""The initiliazer for the Encoder model. Args: length: The length (in samples) of the filter... | stack_v2_sparse_classes_36k_train_002571 | 6,582 | permissive | [
{
"docstring": "The initiliazer for the Encoder model. Args: length: The length (in samples) of the filters. num_filters: The number of filters.",
"name": "__init__",
"signature": "def __init__(self, length, num_filters)"
},
{
"docstring": "Applies the Encoder model, decomposing the input signal... | 2 | stack_v2_sparse_classes_30k_train_002066 | Implement the Python class `Encoder` described below.
Class description:
The encoder model for the learned decomposition, overlap between decomposed winodws is 50% by default following the Conv-TasNet paper.
Method signatures and docstrings:
- def __init__(self, length, num_filters): The initiliazer for the Encoder m... | Implement the Python class `Encoder` described below.
Class description:
The encoder model for the learned decomposition, overlap between decomposed winodws is 50% by default following the Conv-TasNet paper.
Method signatures and docstrings:
- def __init__(self, length, num_filters): The initiliazer for the Encoder m... | 732abbbe0953553d3e3c6d52f99abc5ef10612fc | <|skeleton|>
class Encoder:
"""The encoder model for the learned decomposition, overlap between decomposed winodws is 50% by default following the Conv-TasNet paper."""
def __init__(self, length, num_filters):
"""The initiliazer for the Encoder model. Args: length: The length (in samples) of the filter... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Encoder:
"""The encoder model for the learned decomposition, overlap between decomposed winodws is 50% by default following the Conv-TasNet paper."""
def __init__(self, length, num_filters):
"""The initiliazer for the Encoder model. Args: length: The length (in samples) of the filters. num_filter... | the_stack_v2_python_sparse | structures/learned_basis_function.py | googleinterns/audio_synthesis | train | 0 |
e50d4668751b33b8d5505a300d5236347070edc0 | [
"if not isinstance(typecode, ElementDeclaration):\n return False\ntry:\n nsuri, ncname = typecode.substitutionGroup\nexcept (AttributeError, TypeError):\n return False\nif (nsuri, ncname) != (self.schema, self.literal):\n if not nsuri and (not self.schema) and (ncname == self.literal):\n return T... | <|body_start_0|>
if not isinstance(typecode, ElementDeclaration):
return False
try:
nsuri, ncname = typecode.substitutionGroup
except (AttributeError, TypeError):
return False
if (nsuri, ncname) != (self.schema, self.literal):
if not nsuri ... | Typecodes subclass to represent a Global Element Declaration by setting class variables schema and literal. schema = namespaceURI literal = NCName substitutionGroup -- GED reference of form, (namespaceURI,NCName) | ElementDeclaration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElementDeclaration:
"""Typecodes subclass to represent a Global Element Declaration by setting class variables schema and literal. schema = namespaceURI literal = NCName substitutionGroup -- GED reference of form, (namespaceURI,NCName)"""
def checkSubstitute(self, typecode):
"""If th... | stack_v2_sparse_classes_36k_train_002572 | 14,557 | permissive | [
{
"docstring": "If this is True, allow typecode to be substituted for \"self\" typecode.",
"name": "checkSubstitute",
"signature": "def checkSubstitute(self, typecode)"
},
{
"docstring": "if elt matches a member of the head substitutionGroup, return the GED typecode representation of the member.... | 2 | stack_v2_sparse_classes_30k_train_018964 | Implement the Python class `ElementDeclaration` described below.
Class description:
Typecodes subclass to represent a Global Element Declaration by setting class variables schema and literal. schema = namespaceURI literal = NCName substitutionGroup -- GED reference of form, (namespaceURI,NCName)
Method signatures and... | Implement the Python class `ElementDeclaration` described below.
Class description:
Typecodes subclass to represent a Global Element Declaration by setting class variables schema and literal. schema = namespaceURI literal = NCName substitutionGroup -- GED reference of form, (namespaceURI,NCName)
Method signatures and... | 9b890e6a25471037b7485e4999b480de7c86b656 | <|skeleton|>
class ElementDeclaration:
"""Typecodes subclass to represent a Global Element Declaration by setting class variables schema and literal. schema = namespaceURI literal = NCName substitutionGroup -- GED reference of form, (namespaceURI,NCName)"""
def checkSubstitute(self, typecode):
"""If th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ElementDeclaration:
"""Typecodes subclass to represent a Global Element Declaration by setting class variables schema and literal. schema = namespaceURI literal = NCName substitutionGroup -- GED reference of form, (namespaceURI,NCName)"""
def checkSubstitute(self, typecode):
"""If this is True, a... | the_stack_v2_python_sparse | Libraries/DUTs/Community/di_vsphere/pysphere/pysphere/ZSI/schema.py | Spirent/iTest-assets | train | 10 |
0553f7c8d65c7de7e6a356f9cbde0261789f139b | [
"self.py3_wrapper = py3_wrapper\nself.pyudev_available = pyudev is not None\nself.throttle = defaultdict(Counter)\nself.udev_consumers = defaultdict(list)\nself.udev_observer = None",
"context = pyudev.Context()\nmonitor = pyudev.Monitor.from_netlink(context)\nself.udev_observer = pyudev.MonitorObserver(monitor, ... | <|body_start_0|>
self.py3_wrapper = py3_wrapper
self.pyudev_available = pyudev is not None
self.throttle = defaultdict(Counter)
self.udev_consumers = defaultdict(list)
self.udev_observer = None
<|end_body_0|>
<|body_start_1|>
context = pyudev.Context()
monitor = ... | This class allows us to react to udev events. | UdevMonitor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UdevMonitor:
"""This class allows us to react to udev events."""
def __init__(self, py3_wrapper):
"""The udev monitoring will be lazy loaded if a module uses it."""
<|body_0|>
def _setup_pyudev_monitoring(self):
"""Setup the udev monitor."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_002573 | 3,726 | permissive | [
{
"docstring": "The udev monitoring will be lazy loaded if a module uses it.",
"name": "__init__",
"signature": "def __init__(self, py3_wrapper)"
},
{
"docstring": "Setup the udev monitor.",
"name": "_setup_pyudev_monitoring",
"signature": "def _setup_pyudev_monitoring(self)"
},
{
... | 5 | null | Implement the Python class `UdevMonitor` described below.
Class description:
This class allows us to react to udev events.
Method signatures and docstrings:
- def __init__(self, py3_wrapper): The udev monitoring will be lazy loaded if a module uses it.
- def _setup_pyudev_monitoring(self): Setup the udev monitor.
- d... | Implement the Python class `UdevMonitor` described below.
Class description:
This class allows us to react to udev events.
Method signatures and docstrings:
- def __init__(self, py3_wrapper): The udev monitoring will be lazy loaded if a module uses it.
- def _setup_pyudev_monitoring(self): Setup the udev monitor.
- d... | 7ada9276ee12fe80491768d60603f8c5e1dc0639 | <|skeleton|>
class UdevMonitor:
"""This class allows us to react to udev events."""
def __init__(self, py3_wrapper):
"""The udev monitoring will be lazy loaded if a module uses it."""
<|body_0|>
def _setup_pyudev_monitoring(self):
"""Setup the udev monitor."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UdevMonitor:
"""This class allows us to react to udev events."""
def __init__(self, py3_wrapper):
"""The udev monitoring will be lazy loaded if a module uses it."""
self.py3_wrapper = py3_wrapper
self.pyudev_available = pyudev is not None
self.throttle = defaultdict(Counte... | the_stack_v2_python_sparse | py3status/udev_monitor.py | ultrabug/py3status | train | 934 |
a79e83e724826424d0ad40aa50db2a2fe92303f5 | [
"super(DictFormatter, self).__init__()\nself._format_dict = format_dict\nself._fallback_formatter = formatter",
"if self._fallback_formatter:\n fallback_strings = self._fallback_formatter(direction, factor, values)\nelse:\n fallback_strings = [''] * len(values)\nr = [self._format_dict.get(k, v) for k, v in ... | <|body_start_0|>
super(DictFormatter, self).__init__()
self._format_dict = format_dict
self._fallback_formatter = formatter
<|end_body_0|>
<|body_start_1|>
if self._fallback_formatter:
fallback_strings = self._fallback_formatter(direction, factor, values)
else:
... | DictFormatter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DictFormatter:
def __init__(self, format_dict, formatter=None):
"""format_dict : dictionary for format strings to be used. formatter : fall-back formatter"""
<|body_0|>
def __call__(self, direction, factor, values):
"""factor is ignored if value is found in the dicti... | stack_v2_sparse_classes_36k_train_002574 | 11,863 | permissive | [
{
"docstring": "format_dict : dictionary for format strings to be used. formatter : fall-back formatter",
"name": "__init__",
"signature": "def __init__(self, format_dict, formatter=None)"
},
{
"docstring": "factor is ignored if value is found in the dictionary",
"name": "__call__",
"sig... | 2 | null | Implement the Python class `DictFormatter` described below.
Class description:
Implement the DictFormatter class.
Method signatures and docstrings:
- def __init__(self, format_dict, formatter=None): format_dict : dictionary for format strings to be used. formatter : fall-back formatter
- def __call__(self, direction,... | Implement the Python class `DictFormatter` described below.
Class description:
Implement the DictFormatter class.
Method signatures and docstrings:
- def __init__(self, format_dict, formatter=None): format_dict : dictionary for format strings to be used. formatter : fall-back formatter
- def __call__(self, direction,... | f5042e35b945aded77b23470ead62d7eacefde92 | <|skeleton|>
class DictFormatter:
def __init__(self, format_dict, formatter=None):
"""format_dict : dictionary for format strings to be used. formatter : fall-back formatter"""
<|body_0|>
def __call__(self, direction, factor, values):
"""factor is ignored if value is found in the dicti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DictFormatter:
def __init__(self, format_dict, formatter=None):
"""format_dict : dictionary for format strings to be used. formatter : fall-back formatter"""
super(DictFormatter, self).__init__()
self._format_dict = format_dict
self._fallback_formatter = formatter
def __ca... | the_stack_v2_python_sparse | contrib/python/matplotlib/py2/mpl_toolkits/axisartist/grid_finder.py | catboost/catboost | train | 8,012 | |
e3eae854e9f84efcaf06bf64ba15bddc09275ad3 | [
"self.glasses = glasses\nself.matrix_bitmap = self.ring_bitmap = None\nself.rings_on_top = rings_on_top\nif matrix_filename:\n self.matrix_bitmap, self.matrix_palette = adafruit_imageload.load(matrix_filename, bitmap=displayio.Bitmap, palette=displayio.Palette)\n if self.matrix_bitmap.width < glasses.width or... | <|body_start_0|>
self.glasses = glasses
self.matrix_bitmap = self.ring_bitmap = None
self.rings_on_top = rings_on_top
if matrix_filename:
self.matrix_bitmap, self.matrix_palette = adafruit_imageload.load(matrix_filename, bitmap=displayio.Bitmap, palette=displayio.Palette)
... | Class encapsulating BMP image-based frame animation for the matrix and rings of an LED_Glasses object. | EyeLightsAnim | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EyeLightsAnim:
"""Class encapsulating BMP image-based frame animation for the matrix and rings of an LED_Glasses object."""
def __init__(self, glasses, matrix_filename, ring_filename, rings_on_top=True):
"""Constructor for EyeLightsAnim. Accepts an LED_Glasses object and filenames fo... | stack_v2_sparse_classes_36k_train_002575 | 6,892 | permissive | [
{
"docstring": "Constructor for EyeLightsAnim. Accepts an LED_Glasses object and filenames for two indexed-color BMP images: first is a \"sprite sheet\" for animating on the matrix portion of the glasses, second is a pixels-over-time graph for the rings portion. Either filename may be None if not used. Because ... | 4 | null | Implement the Python class `EyeLightsAnim` described below.
Class description:
Class encapsulating BMP image-based frame animation for the matrix and rings of an LED_Glasses object.
Method signatures and docstrings:
- def __init__(self, glasses, matrix_filename, ring_filename, rings_on_top=True): Constructor for EyeL... | Implement the Python class `EyeLightsAnim` described below.
Class description:
Class encapsulating BMP image-based frame animation for the matrix and rings of an LED_Glasses object.
Method signatures and docstrings:
- def __init__(self, glasses, matrix_filename, ring_filename, rings_on_top=True): Constructor for EyeL... | 5eaa7a15a437c533b89f359a25983e24bb6b5438 | <|skeleton|>
class EyeLightsAnim:
"""Class encapsulating BMP image-based frame animation for the matrix and rings of an LED_Glasses object."""
def __init__(self, glasses, matrix_filename, ring_filename, rings_on_top=True):
"""Constructor for EyeLightsAnim. Accepts an LED_Glasses object and filenames fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EyeLightsAnim:
"""Class encapsulating BMP image-based frame animation for the matrix and rings of an LED_Glasses object."""
def __init__(self, glasses, matrix_filename, ring_filename, rings_on_top=True):
"""Constructor for EyeLightsAnim. Accepts an LED_Glasses object and filenames for two indexed... | the_stack_v2_python_sparse | EyeLights_BMP_Animation/eyelights_anim.py | adafruit/Adafruit_Learning_System_Guides | train | 937 |
8f67d59da3bc32ceb80cb28e394e6aca85cb7f3c | [
"if version:\n if version == 4:\n return Command.executeIp(logger, IpConstant.IPV4, IpOption.NEIGHBOUR, IpAction.SHOW)\n elif version == 6:\n return Command.executeIp(logger, IpConstant.IPV6, IpOption.NEIGHBOUR, IpAction.SHOW)\nrc = Command.executeIp(logger, IpOption.NEIGHBOUR, IpAction.SHOW)\nr... | <|body_start_0|>
if version:
if version == 4:
return Command.executeIp(logger, IpConstant.IPV4, IpOption.NEIGHBOUR, IpAction.SHOW)
elif version == 6:
return Command.executeIp(logger, IpConstant.IPV6, IpOption.NEIGHBOUR, IpAction.SHOW)
rc = Command.... | IpNeighbour | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IpNeighbour:
def showNeighbours(logger, version=None):
"""This function list neighbour entries Args: logger version - IPv4 or IPv6 as an integer, 4 or 6 Return: tuple (rc, stdout, stderr) Raise: None"""
<|body_0|>
def showNeighboursByDevice(logger, device, version=None):
... | stack_v2_sparse_classes_36k_train_002576 | 10,343 | no_license | [
{
"docstring": "This function list neighbour entries Args: logger version - IPv4 or IPv6 as an integer, 4 or 6 Return: tuple (rc, stdout, stderr) Raise: None",
"name": "showNeighbours",
"signature": "def showNeighbours(logger, version=None)"
},
{
"docstring": "This function list neighbour entrie... | 2 | stack_v2_sparse_classes_30k_train_001155 | Implement the Python class `IpNeighbour` described below.
Class description:
Implement the IpNeighbour class.
Method signatures and docstrings:
- def showNeighbours(logger, version=None): This function list neighbour entries Args: logger version - IPv4 or IPv6 as an integer, 4 or 6 Return: tuple (rc, stdout, stderr) ... | Implement the Python class `IpNeighbour` described below.
Class description:
Implement the IpNeighbour class.
Method signatures and docstrings:
- def showNeighbours(logger, version=None): This function list neighbour entries Args: logger version - IPv4 or IPv6 as an integer, 4 or 6 Return: tuple (rc, stdout, stderr) ... | 81bcc74fe7c0ca036ec483f634d7be0bab19a6d0 | <|skeleton|>
class IpNeighbour:
def showNeighbours(logger, version=None):
"""This function list neighbour entries Args: logger version - IPv4 or IPv6 as an integer, 4 or 6 Return: tuple (rc, stdout, stderr) Raise: None"""
<|body_0|>
def showNeighboursByDevice(logger, device, version=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IpNeighbour:
def showNeighbours(logger, version=None):
"""This function list neighbour entries Args: logger version - IPv4 or IPv6 as an integer, 4 or 6 Return: tuple (rc, stdout, stderr) Raise: None"""
if version:
if version == 4:
return Command.executeIp(logger, I... | the_stack_v2_python_sparse | oscar/a/sys/net/lnx/neighbour.py | afeset/miner2-tools | train | 0 | |
dc36fe0f57f19ba2b5eccb864fc0ccd864ca56e7 | [
"if len(s) == 0:\n return 0\nlongest = 0\ncount = 1\nletterList = {s[0]}\nlastFix = 1\nct = 1\nwhile ct < len(s):\n letter = s[ct]\n if letter in letterList:\n if count > longest:\n longest = count\n count = 0\n letterList = {s[lastFix]}\n lastFix += 1\n ct = l... | <|body_start_0|>
if len(s) == 0:
return 0
longest = 0
count = 1
letterList = {s[0]}
lastFix = 1
ct = 1
while ct < len(s):
letter = s[ct]
if letter in letterList:
if count > longest:
longest = ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLongestSubstringTooSlow(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(s) == 0:
return 0... | stack_v2_sparse_classes_36k_train_002577 | 34,573 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLongestSubstringTooSlow",
"signature": "def lengthOfLongestSubstringTooSlow(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLongestSubstring",
"signature": "def lengthOfLongestSubstring(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstringTooSlow(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstring(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 lengthOfLongestSubstringTooSlow(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstring(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def le... | 3adfe9b7ab044d87ac07d6c54ada2f941d6262a7 | <|skeleton|>
class Solution:
def lengthOfLongestSubstringTooSlow(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLongestSubstringTooSlow(self, s):
""":type s: str :rtype: int"""
if len(s) == 0:
return 0
longest = 0
count = 1
letterList = {s[0]}
lastFix = 1
ct = 1
while ct < len(s):
letter = s[ct]
if ... | the_stack_v2_python_sparse | archive pre 2021/003. Longest Substring Without Repeating Characters.py | young24601/leetcode | train | 0 | |
4891cd65025a677d4f9f1828be8222c27826e829 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('jguerero_mgarcia7', 'jguerero_mgarcia7')\nnstats = repo['jguerero_mgarcia7.neighborhoodstatistics'].find()\nfoodscores = []\nincome = []\nobesity = []\nfor nb in nstats:\n foodscores.append(nb['FoodSc... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('jguerero_mgarcia7', 'jguerero_mgarcia7')
nstats = repo['jguerero_mgarcia7.neighborhoodstatistics'].find()
foodscores = []
income = []
... | statisticsanalysis | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class statisticsanalysis:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing every... | stack_v2_sparse_classes_36k_train_002578 | 3,448 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_013139 | Implement the Python class `statisticsanalysis` described below.
Class description:
Implement the statisticsanalysis class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTi... | Implement the Python class `statisticsanalysis` described below.
Class description:
Implement the statisticsanalysis class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTi... | 0df485d0469c5451ebdcd684bed2a0960ba3ab84 | <|skeleton|>
class statisticsanalysis:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing every... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class statisticsanalysis:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('jguerero_mgarcia7', 'jguerero_mg... | the_stack_v2_python_sparse | jguerero_mgarcia7/statisticsanalysis.py | lingyigu/course-2017-spr-proj | train | 0 | |
0bb2f224649499ffc60d6ec6107ea01b78aa751d | [
"N = len(nums)\nif N == 0:\n return -1\nfor i in range(N):\n if not (nums[i] >= 0 and nums[i] <= N - 1):\n return -1\nsorted(nums)\nfor i in range(N):\n if i != nums[i]:\n return nums[i]\nreturn -1",
"N = len(nums)\nif N == 0:\n return -1\nfor i in range(N):\n if not (nums[i] >= 0 and... | <|body_start_0|>
N = len(nums)
if N == 0:
return -1
for i in range(N):
if not (nums[i] >= 0 and nums[i] <= N - 1):
return -1
sorted(nums)
for i in range(N):
if i != nums[i]:
return nums[i]
return -1
<|end... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sort(self, nums):
"""将数组重新排列,再依次遍历数组,如果nums[i]!=i,则输出。-1表示没有重复数字。 time complexity: O(nlogn) space coomplexity: O(1)"""
<|body_0|>
def hash_map(self, nums):
"""借用字典结构;key元素,遍历数组,如果元素不在字典里,则跳过,否则,该元素重复 time complexity: O(n) space complexity: O(n)"""
... | stack_v2_sparse_classes_36k_train_002579 | 2,580 | permissive | [
{
"docstring": "将数组重新排列,再依次遍历数组,如果nums[i]!=i,则输出。-1表示没有重复数字。 time complexity: O(nlogn) space coomplexity: O(1)",
"name": "sort",
"signature": "def sort(self, nums)"
},
{
"docstring": "借用字典结构;key元素,遍历数组,如果元素不在字典里,则跳过,否则,该元素重复 time complexity: O(n) space complexity: O(n)",
"name": "hash_map",
... | 3 | stack_v2_sparse_classes_30k_train_005195 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sort(self, nums): 将数组重新排列,再依次遍历数组,如果nums[i]!=i,则输出。-1表示没有重复数字。 time complexity: O(nlogn) space coomplexity: O(1)
- def hash_map(self, nums): 借用字典结构;key元素,遍历数组,如果元素不在字典里,则跳过,否... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sort(self, nums): 将数组重新排列,再依次遍历数组,如果nums[i]!=i,则输出。-1表示没有重复数字。 time complexity: O(nlogn) space coomplexity: O(1)
- def hash_map(self, nums): 借用字典结构;key元素,遍历数组,如果元素不在字典里,则跳过,否... | 187a485de0774561eb843d8ee640236adda97b90 | <|skeleton|>
class Solution:
def sort(self, nums):
"""将数组重新排列,再依次遍历数组,如果nums[i]!=i,则输出。-1表示没有重复数字。 time complexity: O(nlogn) space coomplexity: O(1)"""
<|body_0|>
def hash_map(self, nums):
"""借用字典结构;key元素,遍历数组,如果元素不在字典里,则跳过,否则,该元素重复 time complexity: O(n) space complexity: O(n)"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sort(self, nums):
"""将数组重新排列,再依次遍历数组,如果nums[i]!=i,则输出。-1表示没有重复数字。 time complexity: O(nlogn) space coomplexity: O(1)"""
N = len(nums)
if N == 0:
return -1
for i in range(N):
if not (nums[i] >= 0 and nums[i] <= N - 1):
return ... | the_stack_v2_python_sparse | code/at_offer/array/coding_interview3_1.py | zhangrong1722/interview | train | 2 | |
db3e3911f5ec49b418f45b6b40d367a93c564cdb | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn SearchHitsContainer()",
"from .search_aggregation import SearchAggregation\nfrom .search_hit import SearchHit\nfrom .search_aggregation import SearchAggregation\nfrom .search_hit import SearchHit\nfields: Dict[str, Callable[[Any], None... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return SearchHitsContainer()
<|end_body_0|>
<|body_start_1|>
from .search_aggregation import SearchAggregation
from .search_hit import SearchHit
from .search_aggregation import SearchAg... | SearchHitsContainer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchHitsContainer:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SearchHitsContainer:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ob... | stack_v2_sparse_classes_36k_train_002580 | 3,824 | 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: SearchHitsContainer",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator... | 3 | null | Implement the Python class `SearchHitsContainer` described below.
Class description:
Implement the SearchHitsContainer class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SearchHitsContainer: Creates a new instance of the appropriate class based on d... | Implement the Python class `SearchHitsContainer` described below.
Class description:
Implement the SearchHitsContainer class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SearchHitsContainer: Creates a new instance of the appropriate class based on d... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class SearchHitsContainer:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SearchHitsContainer:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ob... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SearchHitsContainer:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SearchHitsContainer:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ... | the_stack_v2_python_sparse | msgraph/generated/models/search_hits_container.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
82926fd660f3dd408d025d5c3978b53daf4ed874 | [
"self.meetup = meetup\nself.createdBy = createdBy\nself.response = response",
"rsvp_data = dict(meetup=self.meetup, createdBy=self.createdBy, response=self.response)\ndata = {'response': 'response'}\ntable = 'rsvps'\ncolumns = ', '.join(rsvp_data.keys())\nvalues = \"', '\".join(map(str, rsvp_data.values()))\ndeta... | <|body_start_0|>
self.meetup = meetup
self.createdBy = createdBy
self.response = response
<|end_body_0|>
<|body_start_1|>
rsvp_data = dict(meetup=self.meetup, createdBy=self.createdBy, response=self.response)
data = {'response': 'response'}
table = 'rsvps'
column... | Class for rsvp CRUD operations | RsvpModels | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RsvpModels:
"""Class for rsvp CRUD operations"""
def __init__(self, meetup, createdBy, response):
"""Initialize the rsvp models"""
<|body_0|>
def create_rsvp(self):
"""Method for creating rsvp"""
<|body_1|>
def check_user(self, createdBy, meetupId):
... | stack_v2_sparse_classes_36k_train_002581 | 1,812 | no_license | [
{
"docstring": "Initialize the rsvp models",
"name": "__init__",
"signature": "def __init__(self, meetup, createdBy, response)"
},
{
"docstring": "Method for creating rsvp",
"name": "create_rsvp",
"signature": "def create_rsvp(self)"
},
{
"docstring": "Method to check user",
... | 4 | stack_v2_sparse_classes_30k_train_006500 | Implement the Python class `RsvpModels` described below.
Class description:
Class for rsvp CRUD operations
Method signatures and docstrings:
- def __init__(self, meetup, createdBy, response): Initialize the rsvp models
- def create_rsvp(self): Method for creating rsvp
- def check_user(self, createdBy, meetupId): Meth... | Implement the Python class `RsvpModels` described below.
Class description:
Class for rsvp CRUD operations
Method signatures and docstrings:
- def __init__(self, meetup, createdBy, response): Initialize the rsvp models
- def create_rsvp(self): Method for creating rsvp
- def check_user(self, createdBy, meetupId): Meth... | 93c7aeb54c240b6312e6164859acd2c878e85825 | <|skeleton|>
class RsvpModels:
"""Class for rsvp CRUD operations"""
def __init__(self, meetup, createdBy, response):
"""Initialize the rsvp models"""
<|body_0|>
def create_rsvp(self):
"""Method for creating rsvp"""
<|body_1|>
def check_user(self, createdBy, meetupId):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RsvpModels:
"""Class for rsvp CRUD operations"""
def __init__(self, meetup, createdBy, response):
"""Initialize the rsvp models"""
self.meetup = meetup
self.createdBy = createdBy
self.response = response
def create_rsvp(self):
"""Method for creating rsvp"""
... | the_stack_v2_python_sparse | app/api/v2/models/rsvp_models.py | matthenge/Questioner-api-v2 | train | 0 |
24833fab55a0eac01251a49c2813503f038fb1fd | [
"ENFORCER.enforce_call(action='identity:get_protocol')\nref = PROVIDERS.federation_api.get_protocol(idp_id, protocol_id)\nreturn self.wrap_member(ref)",
"ENFORCER.enforce_call(action='identity:create_protocol')\nprotocol = self.request_body_json.get('protocol', {})\nvalidation.lazy_validate(schema.protocol_create... | <|body_start_0|>
ENFORCER.enforce_call(action='identity:get_protocol')
ref = PROVIDERS.federation_api.get_protocol(idp_id, protocol_id)
return self.wrap_member(ref)
<|end_body_0|>
<|body_start_1|>
ENFORCER.enforce_call(action='identity:create_protocol')
protocol = self.request_b... | IDPProtocolsCRUDResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IDPProtocolsCRUDResource:
def get(self, idp_id, protocol_id):
"""Get protocols for an IDP. HEAD/GET /OS-FEDERATION/identity_providers/ {idp_id}/protocols/{protocol_id}"""
<|body_0|>
def put(self, idp_id, protocol_id):
"""Create protocol for an IDP. PUT /OS-Federation... | stack_v2_sparse_classes_36k_train_002582 | 19,051 | permissive | [
{
"docstring": "Get protocols for an IDP. HEAD/GET /OS-FEDERATION/identity_providers/ {idp_id}/protocols/{protocol_id}",
"name": "get",
"signature": "def get(self, idp_id, protocol_id)"
},
{
"docstring": "Create protocol for an IDP. PUT /OS-Federation/identity_providers/{idp_id}/protocols/{proto... | 4 | null | Implement the Python class `IDPProtocolsCRUDResource` described below.
Class description:
Implement the IDPProtocolsCRUDResource class.
Method signatures and docstrings:
- def get(self, idp_id, protocol_id): Get protocols for an IDP. HEAD/GET /OS-FEDERATION/identity_providers/ {idp_id}/protocols/{protocol_id}
- def p... | Implement the Python class `IDPProtocolsCRUDResource` described below.
Class description:
Implement the IDPProtocolsCRUDResource class.
Method signatures and docstrings:
- def get(self, idp_id, protocol_id): Get protocols for an IDP. HEAD/GET /OS-FEDERATION/identity_providers/ {idp_id}/protocols/{protocol_id}
- def p... | 03a0a8146a78682ede9eca12a5a7fdacde2035c8 | <|skeleton|>
class IDPProtocolsCRUDResource:
def get(self, idp_id, protocol_id):
"""Get protocols for an IDP. HEAD/GET /OS-FEDERATION/identity_providers/ {idp_id}/protocols/{protocol_id}"""
<|body_0|>
def put(self, idp_id, protocol_id):
"""Create protocol for an IDP. PUT /OS-Federation... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IDPProtocolsCRUDResource:
def get(self, idp_id, protocol_id):
"""Get protocols for an IDP. HEAD/GET /OS-FEDERATION/identity_providers/ {idp_id}/protocols/{protocol_id}"""
ENFORCER.enforce_call(action='identity:get_protocol')
ref = PROVIDERS.federation_api.get_protocol(idp_id, protocol_... | the_stack_v2_python_sparse | keystone/api/os_federation.py | sapcc/keystone | train | 0 | |
3b59d990cec137e4aca27315ec4ed313ce22570d | [
"slug = self.kwargs.get('community_slug')\ntry:\n community = Tag.objects.get(slug=slug)\nexcept Tag.DoesNotExist:\n return Response(data=None, status=HTTP_404_NOT_FOUND)\nelse:\n self.check_object_permissions(self.request, community)\n return community",
"session_sub = Sub.objects.get(user=request.us... | <|body_start_0|>
slug = self.kwargs.get('community_slug')
try:
community = Tag.objects.get(slug=slug)
except Tag.DoesNotExist:
return Response(data=None, status=HTTP_404_NOT_FOUND)
else:
self.check_object_permissions(self.request, community)
... | endpoint to add and remove communities from Sub.communities | CommunitiesFollowed | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommunitiesFollowed:
"""endpoint to add and remove communities from Sub.communities"""
def get_object(self):
"""get community tag"""
<|body_0|>
def put(self, request, *args, **kwargs):
"""add community to sub.communities"""
<|body_1|>
def delete(self... | stack_v2_sparse_classes_36k_train_002583 | 1,499 | no_license | [
{
"docstring": "get community tag",
"name": "get_object",
"signature": "def get_object(self)"
},
{
"docstring": "add community to sub.communities",
"name": "put",
"signature": "def put(self, request, *args, **kwargs)"
},
{
"docstring": "remove community from sub.communities",
... | 3 | stack_v2_sparse_classes_30k_train_008250 | Implement the Python class `CommunitiesFollowed` described below.
Class description:
endpoint to add and remove communities from Sub.communities
Method signatures and docstrings:
- def get_object(self): get community tag
- def put(self, request, *args, **kwargs): add community to sub.communities
- def delete(self, re... | Implement the Python class `CommunitiesFollowed` described below.
Class description:
endpoint to add and remove communities from Sub.communities
Method signatures and docstrings:
- def get_object(self): get community tag
- def put(self, request, *args, **kwargs): add community to sub.communities
- def delete(self, re... | a20bc7b0be7092788df720e48f163bacaa508b3d | <|skeleton|>
class CommunitiesFollowed:
"""endpoint to add and remove communities from Sub.communities"""
def get_object(self):
"""get community tag"""
<|body_0|>
def put(self, request, *args, **kwargs):
"""add community to sub.communities"""
<|body_1|>
def delete(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommunitiesFollowed:
"""endpoint to add and remove communities from Sub.communities"""
def get_object(self):
"""get community tag"""
slug = self.kwargs.get('community_slug')
try:
community = Tag.objects.get(slug=slug)
except Tag.DoesNotExist:
return... | the_stack_v2_python_sparse | src/users_app/views/CommunitiesFollowed.py | mrpiggy97/bloggit_api | train | 0 |
05501b6ce329db9dde3d1a76567473870b817b25 | [
"try:\n response_text = response.read()\nexcept AttributeError:\n response_text = response\nself.version, self.status, self.error_type, self.message = (None, None, None, None)\ntry:\n response = json.loads(response_text)\n self.version = response['version']\n self.status = response['status']\n sel... | <|body_start_0|>
try:
response_text = response.read()
except AttributeError:
response_text = response
self.version, self.status, self.error_type, self.message = (None, None, None, None)
try:
response = json.loads(response_text)
self.version... | Object representation of a response received from the Resolve API See http://developer.factual.com/display/docs/Places+API+-+Resolve for details. | ResolveResponse | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResolveResponse:
"""Object representation of a response received from the Resolve API See http://developer.factual.com/display/docs/Places+API+-+Resolve for details."""
def __init__(self, response):
"""response can be string or file-like object"""
<|body_0|>
def get_reso... | stack_v2_sparse_classes_36k_train_002584 | 4,243 | no_license | [
{
"docstring": "response can be string or file-like object",
"name": "__init__",
"signature": "def __init__(self, response)"
},
{
"docstring": "Returns the one and only \"resolved\" result, if it exists. Return False if it doesnt. Return value is a dict containing place components as well as res... | 2 | stack_v2_sparse_classes_30k_train_017641 | Implement the Python class `ResolveResponse` described below.
Class description:
Object representation of a response received from the Resolve API See http://developer.factual.com/display/docs/Places+API+-+Resolve for details.
Method signatures and docstrings:
- def __init__(self, response): response can be string or... | Implement the Python class `ResolveResponse` described below.
Class description:
Object representation of a response received from the Resolve API See http://developer.factual.com/display/docs/Places+API+-+Resolve for details.
Method signatures and docstrings:
- def __init__(self, response): response can be string or... | baad13c5812f541478b914575ffba42128edce65 | <|skeleton|>
class ResolveResponse:
"""Object representation of a response received from the Resolve API See http://developer.factual.com/display/docs/Places+API+-+Resolve for details."""
def __init__(self, response):
"""response can be string or file-like object"""
<|body_0|>
def get_reso... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResolveResponse:
"""Object representation of a response received from the Resolve API See http://developer.factual.com/display/docs/Places+API+-+Resolve for details."""
def __init__(self, response):
"""response can be string or file-like object"""
try:
response_text = response... | the_stack_v2_python_sparse | outsourcing/apitools/factual.py | Crockcharterings/onlyinpgh | train | 0 |
e9041bf6895a7290e36592c39c90a306e27f420f | [
"global new_\nnew = []\nstr = str.strip()\nif not str[0].isdigit():\n return 0\nelif str[0].isdigit():\n new.append(str[0])\n for i in range(1, len(str)):\n if not str[i].isdigit():\n break\n else:\n new.append(str[i])\n new_m = ''.join(new)\n new_ = int(new_m)\nel... | <|body_start_0|>
global new_
new = []
str = str.strip()
if not str[0].isdigit():
return 0
elif str[0].isdigit():
new.append(str[0])
for i in range(1, len(str)):
if not str[i].isdigit():
break
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def myAtoi_me(self, str):
""":type str: str :rtype: int"""
<|body_0|>
def myAtoi(self, str):
""":type str: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
global new_
new = []
str = str.strip()
if no... | stack_v2_sparse_classes_36k_train_002585 | 3,441 | no_license | [
{
"docstring": ":type str: str :rtype: int",
"name": "myAtoi_me",
"signature": "def myAtoi_me(self, str)"
},
{
"docstring": ":type str: str :rtype: int",
"name": "myAtoi",
"signature": "def myAtoi(self, str)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012328 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myAtoi_me(self, str): :type str: str :rtype: int
- def myAtoi(self, str): :type str: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myAtoi_me(self, str): :type str: str :rtype: int
- def myAtoi(self, str): :type str: str :rtype: int
<|skeleton|>
class Solution:
def myAtoi_me(self, str):
""":... | 2d15a0cd998bb03c390d8219d6db28a5ae6b51b8 | <|skeleton|>
class Solution:
def myAtoi_me(self, str):
""":type str: str :rtype: int"""
<|body_0|>
def myAtoi(self, str):
""":type str: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def myAtoi_me(self, str):
""":type str: str :rtype: int"""
global new_
new = []
str = str.strip()
if not str[0].isdigit():
return 0
elif str[0].isdigit():
new.append(str[0])
for i in range(1, len(str)):
... | the_stack_v2_python_sparse | str_to_int.py | UESTCYangHR/leecode_test | train | 1 | |
b53d7b55a5e90249b9f7db3ebaa27f91c7248ee0 | [
"self.data = band.ReadAsArray(x_offset, y_offset, x_size, y_size)\nself.x_size = x_size\nself.y_size = y_size\nself.x_offset = x_offset\nself.y_offset = y_offset",
"return_str = ''\nreturn_str += '\\nBlock origin: ('\nreturn_str += repr(self.x_offset) + ', ' + repr(self.y_offset) + ')'\nreturn_str += '\\nBlock si... | <|body_start_0|>
self.data = band.ReadAsArray(x_offset, y_offset, x_size, y_size)
self.x_size = x_size
self.y_size = y_size
self.x_offset = x_offset
self.y_offset = y_offset
<|end_body_0|>
<|body_start_1|>
return_str = ''
return_str += '\nBlock origin: ('
... | Class to represent a chunk of a GDAL Band. Typically, these are generated from the generator get_blocks() which reads on block boundaries. However, it should be generic enough to use with any window. | RasterBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RasterBlock:
"""Class to represent a chunk of a GDAL Band. Typically, these are generated from the generator get_blocks() which reads on block boundaries. However, it should be generic enough to use with any window."""
def __init__(self, band, x_size, y_size, x_offset, y_offset):
"""... | stack_v2_sparse_classes_36k_train_002586 | 8,781 | no_license | [
{
"docstring": "Create an instance using a valid GDAL Band and window information. Stores the pixel information in the self.data property Parameters ---------- band : gdal.Band A raster band from a valid gdal.Dataset x_size : int Number of columns to extract y_size : int Number of rows to extract x_offset : int... | 2 | stack_v2_sparse_classes_30k_train_016188 | Implement the Python class `RasterBlock` described below.
Class description:
Class to represent a chunk of a GDAL Band. Typically, these are generated from the generator get_blocks() which reads on block boundaries. However, it should be generic enough to use with any window.
Method signatures and docstrings:
- def _... | Implement the Python class `RasterBlock` described below.
Class description:
Class to represent a chunk of a GDAL Band. Typically, these are generated from the generator get_blocks() which reads on block boundaries. However, it should be generic enough to use with any window.
Method signatures and docstrings:
- def _... | f8ab7ab4971f4c13f7eb66d5449d011e481c44d1 | <|skeleton|>
class RasterBlock:
"""Class to represent a chunk of a GDAL Band. Typically, these are generated from the generator get_blocks() which reads on block boundaries. However, it should be generic enough to use with any window."""
def __init__(self, band, x_size, y_size, x_offset, y_offset):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RasterBlock:
"""Class to represent a chunk of a GDAL Band. Typically, these are generated from the generator get_blocks() which reads on block boundaries. However, it should be generic enough to use with any window."""
def __init__(self, band, x_size, y_size, x_offset, y_offset):
"""Create an ins... | the_stack_v2_python_sparse | pynnmap/misc/gdal_utilities.py | lemma-osu/pynnmap | train | 8 |
f9e7fead436b149db2096f71f4c710d2a1a0881a | [
"comp = lambda x, y: 0 if x == y else -1 if x < y else 1\nself.sa = mysort([document[i:] for i in range(len(document))], comp)\npass",
"out = []\nfor x in range(0, len(self.sa)):\n sub = self.sa[x]\n if searchstr == sub[0:len(searchstr)]:\n out.append(x)\n return out\npass",
"for x in self.s... | <|body_start_0|>
comp = lambda x, y: 0 if x == y else -1 if x < y else 1
self.sa = mysort([document[i:] for i in range(len(document))], comp)
pass
<|end_body_0|>
<|body_start_1|>
out = []
for x in range(0, len(self.sa)):
sub = self.sa[x]
if searchstr == s... | SuffixArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuffixArray:
def __init__(self, document: str):
"""Creates a suffix array for document (a string)."""
<|body_0|>
def positions(self, searchstr: str):
"""Returns all the positions of searchstr in the documented indexed by the suffix array."""
<|body_1|>
d... | stack_v2_sparse_classes_36k_train_002587 | 8,672 | no_license | [
{
"docstring": "Creates a suffix array for document (a string).",
"name": "__init__",
"signature": "def __init__(self, document: str)"
},
{
"docstring": "Returns all the positions of searchstr in the documented indexed by the suffix array.",
"name": "positions",
"signature": "def positio... | 3 | stack_v2_sparse_classes_30k_train_004608 | Implement the Python class `SuffixArray` described below.
Class description:
Implement the SuffixArray class.
Method signatures and docstrings:
- def __init__(self, document: str): Creates a suffix array for document (a string).
- def positions(self, searchstr: str): Returns all the positions of searchstr in the docu... | Implement the Python class `SuffixArray` described below.
Class description:
Implement the SuffixArray class.
Method signatures and docstrings:
- def __init__(self, document: str): Creates a suffix array for document (a string).
- def positions(self, searchstr: str): Returns all the positions of searchstr in the docu... | b4edf759b2916ab44f08741a6f19b103a9070203 | <|skeleton|>
class SuffixArray:
def __init__(self, document: str):
"""Creates a suffix array for document (a string)."""
<|body_0|>
def positions(self, searchstr: str):
"""Returns all the positions of searchstr in the documented indexed by the suffix array."""
<|body_1|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SuffixArray:
def __init__(self, document: str):
"""Creates a suffix array for document (a string)."""
comp = lambda x, y: 0 if x == y else -1 if x < y else 1
self.sa = mysort([document[i:] for i in range(len(document))], comp)
pass
def positions(self, searchstr: str):
... | the_stack_v2_python_sparse | lab03/lab03.py | saronson/cs331-s21-jmallett2 | train | 2 | |
805b7c4293bb9197bfcf130b32f01a273cc026b8 | [
"try:\n user = Traveler.objects.get(pk=pk)\n serializer = TravelerSerializer(user, context={'request': request})\n return Response(serializer.data)\nexcept Exception as ex:\n return HttpResponseServerError(ex)",
"users = Traveler.objects.all()\nserializer = TravelerSerializer(users, many=True, context... | <|body_start_0|>
try:
user = Traveler.objects.get(pk=pk)
serializer = TravelerSerializer(user, context={'request': request})
return Response(serializer.data)
except Exception as ex:
return HttpResponseServerError(ex)
<|end_body_0|>
<|body_start_1|>
... | To see traveler specific information | TravelerView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TravelerView:
"""To see traveler specific information"""
def retrieve(self, request, pk=None):
"""Handle GET requests for single traveler Returns: Response -- JSON serialized traveler instance"""
<|body_0|>
def list(self, request):
"""Handle GET requests to profi... | stack_v2_sparse_classes_36k_train_002588 | 1,649 | no_license | [
{
"docstring": "Handle GET requests for single traveler Returns: Response -- JSON serialized traveler instance",
"name": "retrieve",
"signature": "def retrieve(self, request, pk=None)"
},
{
"docstring": "Handle GET requests to profile resource Returns: Response -- JSON representation of user inf... | 2 | stack_v2_sparse_classes_30k_train_018979 | Implement the Python class `TravelerView` described below.
Class description:
To see traveler specific information
Method signatures and docstrings:
- def retrieve(self, request, pk=None): Handle GET requests for single traveler Returns: Response -- JSON serialized traveler instance
- def list(self, request): Handle ... | Implement the Python class `TravelerView` described below.
Class description:
To see traveler specific information
Method signatures and docstrings:
- def retrieve(self, request, pk=None): Handle GET requests for single traveler Returns: Response -- JSON serialized traveler instance
- def list(self, request): Handle ... | c32f40f862cb06354d9f987d79e199faa239d3c5 | <|skeleton|>
class TravelerView:
"""To see traveler specific information"""
def retrieve(self, request, pk=None):
"""Handle GET requests for single traveler Returns: Response -- JSON serialized traveler instance"""
<|body_0|>
def list(self, request):
"""Handle GET requests to profi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TravelerView:
"""To see traveler specific information"""
def retrieve(self, request, pk=None):
"""Handle GET requests for single traveler Returns: Response -- JSON serialized traveler instance"""
try:
user = Traveler.objects.get(pk=pk)
serializer = TravelerSerializ... | the_stack_v2_python_sparse | blessipeapi/views/traveler.py | gqgonzales/blessipe-api | train | 0 |
bc8097356575db9297b9480752625b51cc7fbb3f | [
"self.is_entire_drive_required = is_entire_drive_required\nself.restore_drive_id = restore_drive_id\nself.restore_item_vec = restore_item_vec",
"if dictionary is None:\n return None\nis_entire_drive_required = dictionary.get('isEntireDriveRequired')\nrestore_drive_id = dictionary.get('restoreDriveId')\nrestore... | <|body_start_0|>
self.is_entire_drive_required = is_entire_drive_required
self.restore_drive_id = restore_drive_id
self.restore_item_vec = restore_item_vec
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
is_entire_drive_required = dictionary.get('i... | Implementation of the 'RestoreOneDriveParams_DriveOwner_Drive' model. TODO: type description here. Attributes: is_entire_drive_required (bool): Specify if the entire drive is to be restored. This field should be false if restore_item_vec size > 0. restore_drive_id (string): Id of the drive whose items are being restore... | RestoreOneDriveParams_DriveOwner_Drive | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoreOneDriveParams_DriveOwner_Drive:
"""Implementation of the 'RestoreOneDriveParams_DriveOwner_Drive' model. TODO: type description here. Attributes: is_entire_drive_required (bool): Specify if the entire drive is to be restored. This field should be false if restore_item_vec size > 0. restor... | stack_v2_sparse_classes_36k_train_002589 | 2,626 | permissive | [
{
"docstring": "Constructor for the RestoreOneDriveParams_DriveOwner_Drive class",
"name": "__init__",
"signature": "def __init__(self, is_entire_drive_required=None, restore_drive_id=None, restore_item_vec=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dicti... | 2 | null | Implement the Python class `RestoreOneDriveParams_DriveOwner_Drive` described below.
Class description:
Implementation of the 'RestoreOneDriveParams_DriveOwner_Drive' model. TODO: type description here. Attributes: is_entire_drive_required (bool): Specify if the entire drive is to be restored. This field should be fal... | Implement the Python class `RestoreOneDriveParams_DriveOwner_Drive` described below.
Class description:
Implementation of the 'RestoreOneDriveParams_DriveOwner_Drive' model. TODO: type description here. Attributes: is_entire_drive_required (bool): Specify if the entire drive is to be restored. This field should be fal... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RestoreOneDriveParams_DriveOwner_Drive:
"""Implementation of the 'RestoreOneDriveParams_DriveOwner_Drive' model. TODO: type description here. Attributes: is_entire_drive_required (bool): Specify if the entire drive is to be restored. This field should be false if restore_item_vec size > 0. restor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RestoreOneDriveParams_DriveOwner_Drive:
"""Implementation of the 'RestoreOneDriveParams_DriveOwner_Drive' model. TODO: type description here. Attributes: is_entire_drive_required (bool): Specify if the entire drive is to be restored. This field should be false if restore_item_vec size > 0. restore_drive_id (s... | the_stack_v2_python_sparse | cohesity_management_sdk/models/restore_one_drive_params_drive_owner_drive.py | cohesity/management-sdk-python | train | 24 |
01a4e851b177f90ba5a321a0e77a5195ec456767 | [
"_LOGGER.debug('async_step_ssdp: started')\nif not _is_complete_discovery(discovery_info):\n _LOGGER.debug('async_step_ssdp: Incomplete discovery, ignoring')\n return self.async_abort(reason='incomplete_discovery')\n_LOGGER.debug('async_step_ssdp: setting unique id %s', discovery_info.upnp[ATTR_UPNP_UDN])\naw... | <|body_start_0|>
_LOGGER.debug('async_step_ssdp: started')
if not _is_complete_discovery(discovery_info):
_LOGGER.debug('async_step_ssdp: Incomplete discovery, ignoring')
return self.async_abort(reason='incomplete_discovery')
_LOGGER.debug('async_step_ssdp: setting unique... | Handle an Openhome config flow. | OpenhomeConfigFlow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenhomeConfigFlow:
"""Handle an Openhome config flow."""
async def async_step_ssdp(self, discovery_info: SsdpServiceInfo) -> FlowResult:
"""Handle a flow initialized by discovery."""
<|body_0|>
async def async_step_confirm(self, user_input: dict[str, Any] | None=None) -... | stack_v2_sparse_classes_36k_train_002590 | 2,231 | permissive | [
{
"docstring": "Handle a flow initialized by discovery.",
"name": "async_step_ssdp",
"signature": "async def async_step_ssdp(self, discovery_info: SsdpServiceInfo) -> FlowResult"
},
{
"docstring": "Handle user-confirmation of discovered node.",
"name": "async_step_confirm",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_015273 | Implement the Python class `OpenhomeConfigFlow` described below.
Class description:
Handle an Openhome config flow.
Method signatures and docstrings:
- async def async_step_ssdp(self, discovery_info: SsdpServiceInfo) -> FlowResult: Handle a flow initialized by discovery.
- async def async_step_confirm(self, user_inpu... | Implement the Python class `OpenhomeConfigFlow` described below.
Class description:
Handle an Openhome config flow.
Method signatures and docstrings:
- async def async_step_ssdp(self, discovery_info: SsdpServiceInfo) -> FlowResult: Handle a flow initialized by discovery.
- async def async_step_confirm(self, user_inpu... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class OpenhomeConfigFlow:
"""Handle an Openhome config flow."""
async def async_step_ssdp(self, discovery_info: SsdpServiceInfo) -> FlowResult:
"""Handle a flow initialized by discovery."""
<|body_0|>
async def async_step_confirm(self, user_input: dict[str, Any] | None=None) -... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OpenhomeConfigFlow:
"""Handle an Openhome config flow."""
async def async_step_ssdp(self, discovery_info: SsdpServiceInfo) -> FlowResult:
"""Handle a flow initialized by discovery."""
_LOGGER.debug('async_step_ssdp: started')
if not _is_complete_discovery(discovery_info):
... | the_stack_v2_python_sparse | homeassistant/components/openhome/config_flow.py | home-assistant/core | train | 35,501 |
ef10982b6e273e7456dff909c70456075cd34d19 | [
"logs.log_info('You are using a K+ Leak channel')\nself.time_unit = 1.0\nself.vrev = -65\nself.m = np.ones(self.data_length)\nself.h = np.ones(self.data_length)\nself._mpower = 0\nself._hpower = 0",
"self._mInf = 1\nself._mTau = 1\nself._hInf = 1\nself._hTau = 1"
] | <|body_start_0|>
logs.log_info('You are using a K+ Leak channel')
self.time_unit = 1.0
self.vrev = -65
self.m = np.ones(self.data_length)
self.h = np.ones(self.data_length)
self._mpower = 0
self._hpower = 0
<|end_body_0|>
<|body_start_1|>
self._mInf = 1
... | Simple potassium leak channel -- always open -- for substance modulation. | KLeak | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KLeak:
"""Simple potassium leak channel -- always open -- for substance modulation."""
def _init_state(self, V):
"""Run initialization calculation for m and h gates of the channel at starting Vmem value."""
<|body_0|>
def _calculate_state(self, V):
"""Update the ... | stack_v2_sparse_classes_36k_train_002591 | 24,227 | no_license | [
{
"docstring": "Run initialization calculation for m and h gates of the channel at starting Vmem value.",
"name": "_init_state",
"signature": "def _init_state(self, V)"
},
{
"docstring": "Update the state of m and h gates of the channel given their present value and present simulation Vmem.",
... | 2 | null | Implement the Python class `KLeak` described below.
Class description:
Simple potassium leak channel -- always open -- for substance modulation.
Method signatures and docstrings:
- def _init_state(self, V): Run initialization calculation for m and h gates of the channel at starting Vmem value.
- def _calculate_state(... | Implement the Python class `KLeak` described below.
Class description:
Simple potassium leak channel -- always open -- for substance modulation.
Method signatures and docstrings:
- def _init_state(self, V): Run initialization calculation for m and h gates of the channel at starting Vmem value.
- def _calculate_state(... | dd03ff5e3df3ef48d887a6566a6286fcd168880b | <|skeleton|>
class KLeak:
"""Simple potassium leak channel -- always open -- for substance modulation."""
def _init_state(self, V):
"""Run initialization calculation for m and h gates of the channel at starting Vmem value."""
<|body_0|>
def _calculate_state(self, V):
"""Update the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KLeak:
"""Simple potassium leak channel -- always open -- for substance modulation."""
def _init_state(self, V):
"""Run initialization calculation for m and h gates of the channel at starting Vmem value."""
logs.log_info('You are using a K+ Leak channel')
self.time_unit = 1.0
... | the_stack_v2_python_sparse | betse/science/channels/vg_k.py | R-Stefano/betse-ml | train | 0 |
a15244f3110db244d202e422e1c41d84ea9ffe93 | [
"try:\n logger.info('切换成英文测试')\n self.login()\n self.switch_english()\n self.driver.refresh()\n sleep(5)\n self.driver.switch_to.frame('content')\n self.assertEqual(self.gettext(self.tips), 'Remark:The browser will automatically refresh!')\nexcept Exception as msg:\n logger.error(u'异常原因:%s' ... | <|body_start_0|>
try:
logger.info('切换成英文测试')
self.login()
self.switch_english()
self.driver.refresh()
sleep(5)
self.driver.switch_to.frame('content')
self.assertEqual(self.gettext(self.tips), 'Remark:The browser will automatical... | 语言切换测试 | LanguagesTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LanguagesTest:
"""语言切换测试"""
def test1_switch_english(self):
"""切换成英文"""
<|body_0|>
def test2_switch_Chinese(self):
"""切换成中文"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
logger.info('切换成英文测试')
self.login()
... | stack_v2_sparse_classes_36k_train_002592 | 1,867 | no_license | [
{
"docstring": "切换成英文",
"name": "test1_switch_english",
"signature": "def test1_switch_english(self)"
},
{
"docstring": "切换成中文",
"name": "test2_switch_Chinese",
"signature": "def test2_switch_Chinese(self)"
}
] | 2 | null | Implement the Python class `LanguagesTest` described below.
Class description:
语言切换测试
Method signatures and docstrings:
- def test1_switch_english(self): 切换成英文
- def test2_switch_Chinese(self): 切换成中文 | Implement the Python class `LanguagesTest` described below.
Class description:
语言切换测试
Method signatures and docstrings:
- def test1_switch_english(self): 切换成英文
- def test2_switch_Chinese(self): 切换成中文
<|skeleton|>
class LanguagesTest:
"""语言切换测试"""
def test1_switch_english(self):
"""切换成英文"""
<... | fd552eeb47fd4838c2c5caef4deea7480ab75ce9 | <|skeleton|>
class LanguagesTest:
"""语言切换测试"""
def test1_switch_english(self):
"""切换成英文"""
<|body_0|>
def test2_switch_Chinese(self):
"""切换成中文"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LanguagesTest:
"""语言切换测试"""
def test1_switch_english(self):
"""切换成英文"""
try:
logger.info('切换成英文测试')
self.login()
self.switch_english()
self.driver.refresh()
sleep(5)
self.driver.switch_to.frame('content')
... | the_stack_v2_python_sparse | test_case/C006_language_test.py | luhuifnag/AVA_UIauto_test | train | 0 |
205a72bd295953f65bf374c61a3efa7c02c839ec | [
"super().__init__()\nself.dropout_rate = dropout_rate\nout_features = out_features or in_features\nhidden_features = hidden_features or in_features\nself.fc1 = nn.Linear(in_features, hidden_features)\nself.act = act_layer()\nself.fc2 = nn.Linear(hidden_features, out_features)\nif self.dropout_rate > 0.0:\n self.... | <|body_start_0|>
super().__init__()
self.dropout_rate = dropout_rate
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_f... | A MLP block that contains two linear layers with a normalization layer. The MLP block is used in a transformer model after the attention block. :: Linear (in_features, hidden_features) ↓ Normalization (act_layer) ↓ Dropout (p=dropout_rate) ↓ Linear (hidden_features, out_features) ↓ Dropout (p=dropout_rate) | Mlp | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mlp:
"""A MLP block that contains two linear layers with a normalization layer. The MLP block is used in a transformer model after the attention block. :: Linear (in_features, hidden_features) ↓ Normalization (act_layer) ↓ Dropout (p=dropout_rate) ↓ Linear (hidden_features, out_features) ↓ Dropou... | stack_v2_sparse_classes_36k_train_002593 | 21,342 | permissive | [
{
"docstring": "Args: in_features (int): Input feature dimension. hidden_features (Optional[int]): Hidden feature dimension. By default, hidden feature is set to input feature dimension. out_features (Optional[int]): Output feature dimension. By default, output features dimension is set to input feature dimensi... | 2 | stack_v2_sparse_classes_30k_train_002419 | Implement the Python class `Mlp` described below.
Class description:
A MLP block that contains two linear layers with a normalization layer. The MLP block is used in a transformer model after the attention block. :: Linear (in_features, hidden_features) ↓ Normalization (act_layer) ↓ Dropout (p=dropout_rate) ↓ Linear (... | Implement the Python class `Mlp` described below.
Class description:
A MLP block that contains two linear layers with a normalization layer. The MLP block is used in a transformer model after the attention block. :: Linear (in_features, hidden_features) ↓ Normalization (act_layer) ↓ Dropout (p=dropout_rate) ↓ Linear (... | 16f2abf2f8aa174915316007622bbb260215dee8 | <|skeleton|>
class Mlp:
"""A MLP block that contains two linear layers with a normalization layer. The MLP block is used in a transformer model after the attention block. :: Linear (in_features, hidden_features) ↓ Normalization (act_layer) ↓ Dropout (p=dropout_rate) ↓ Linear (hidden_features, out_features) ↓ Dropou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Mlp:
"""A MLP block that contains two linear layers with a normalization layer. The MLP block is used in a transformer model after the attention block. :: Linear (in_features, hidden_features) ↓ Normalization (act_layer) ↓ Dropout (p=dropout_rate) ↓ Linear (hidden_features, out_features) ↓ Dropout (p=dropout_... | the_stack_v2_python_sparse | pytorchvideo/layers/attention.py | xchani/pytorchvideo | train | 0 |
2233001bea66d63faf59e89fe08d1fd62a758355 | [
"if self.kwargs == {}:\n self.kwargs['username'] = self.request.user.get_username()\nreturn super().get(*args, **kwargs)",
"context = super().get_context_data(**kwargs)\nusername = context['profile'].user.username\nowner = False\nif username == '':\n username = self.request.user.get_username()\n owner = ... | <|body_start_0|>
if self.kwargs == {}:
self.kwargs['username'] = self.request.user.get_username()
return super().get(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
context = super().get_context_data(**kwargs)
username = context['profile'].user.username
owner = Fals... | Define the ProfileView class. | ProfileView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileView:
"""Define the ProfileView class."""
def get(self, *args, **kwargs):
"""Get args and kwargs."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Get all the context, filter and determine what to display by username."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k_train_002594 | 3,593 | permissive | [
{
"docstring": "Get args and kwargs.",
"name": "get",
"signature": "def get(self, *args, **kwargs)"
},
{
"docstring": "Get all the context, filter and determine what to display by username.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005827 | Implement the Python class `ProfileView` described below.
Class description:
Define the ProfileView class.
Method signatures and docstrings:
- def get(self, *args, **kwargs): Get args and kwargs.
- def get_context_data(self, **kwargs): Get all the context, filter and determine what to display by username. | Implement the Python class `ProfileView` described below.
Class description:
Define the ProfileView class.
Method signatures and docstrings:
- def get(self, *args, **kwargs): Get args and kwargs.
- def get_context_data(self, **kwargs): Get all the context, filter and determine what to display by username.
<|skeleton... | bd78a0c7442d90db8af26bdd93f6170d36dd2385 | <|skeleton|>
class ProfileView:
"""Define the ProfileView class."""
def get(self, *args, **kwargs):
"""Get args and kwargs."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Get all the context, filter and determine what to display by username."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProfileView:
"""Define the ProfileView class."""
def get(self, *args, **kwargs):
"""Get args and kwargs."""
if self.kwargs == {}:
self.kwargs['username'] = self.request.user.get_username()
return super().get(*args, **kwargs)
def get_context_data(self, **kwargs):
... | the_stack_v2_python_sparse | imagersite/imager_profile/views.py | ShannonTully/django-imager | train | 1 |
ecc92716dfd0d6e6a7f65199741a6378aa6c24a9 | [
"losses = []\nfor obs in batch_handler.val_data:\n gen = self._tf_generate(obs.low_res, obs.high_res[..., -1:])\n loss, _ = self.calc_loss(obs.high_res, gen, weight_gen_advers=weight_gen_advers, train_gen=True, train_disc=True)\n losses.append(float(loss))\nreturn losses",
"losses = []\nfor obs in batch_... | <|body_start_0|>
losses = []
for obs in batch_handler.val_data:
gen = self._tf_generate(obs.low_res, obs.high_res[..., -1:])
loss, _ = self.calc_loss(obs.high_res, gen, weight_gen_advers=weight_gen_advers, train_gen=True, train_disc=True)
losses.append(float(loss))
... | Data-centric model using loss across time bins to select training observations with handling of low and high res topography inputs. | WindGanDC | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WindGanDC:
"""Data-centric model using loss across time bins to select training observations with handling of low and high res topography inputs."""
def calc_val_loss_gen(self, batch_handler, weight_gen_advers):
"""Calculate the validation total loss across the validation samples. e.... | stack_v2_sparse_classes_36k_train_002595 | 11,269 | permissive | [
{
"docstring": "Calculate the validation total loss across the validation samples. e.g. If the sample domain has 100 steps and the validation set has 10 bins then this will get a list of losses across step 0 to 10, 10 to 20, etc. Use this to determine performance within bins and to update how observations are s... | 2 | stack_v2_sparse_classes_30k_train_000873 | Implement the Python class `WindGanDC` described below.
Class description:
Data-centric model using loss across time bins to select training observations with handling of low and high res topography inputs.
Method signatures and docstrings:
- def calc_val_loss_gen(self, batch_handler, weight_gen_advers): Calculate th... | Implement the Python class `WindGanDC` described below.
Class description:
Data-centric model using loss across time bins to select training observations with handling of low and high res topography inputs.
Method signatures and docstrings:
- def calc_val_loss_gen(self, batch_handler, weight_gen_advers): Calculate th... | f3803a823c7bb0afd7ab6064625908dca0be3476 | <|skeleton|>
class WindGanDC:
"""Data-centric model using loss across time bins to select training observations with handling of low and high res topography inputs."""
def calc_val_loss_gen(self, batch_handler, weight_gen_advers):
"""Calculate the validation total loss across the validation samples. e.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WindGanDC:
"""Data-centric model using loss across time bins to select training observations with handling of low and high res topography inputs."""
def calc_val_loss_gen(self, batch_handler, weight_gen_advers):
"""Calculate the validation total loss across the validation samples. e.g. If the sam... | the_stack_v2_python_sparse | sup3r/models/data_centric.py | NREL/sup3r | train | 20 |
5a9dc19b1836494b723f03cd680fa9bb02845fd9 | [
"self.connstr = ConnectionString.parse(str(connection_string))\nself.bucket_factory = bucket_factory\nself.authenticator = None\nself._buckets = {}\nif self.connstr.bucket:\n raise ValueError('Cannot pass bucket to connection string: ' + self.connstr.bucket)\nif 'username' in self.connstr.options:\n raise Val... | <|body_start_0|>
self.connstr = ConnectionString.parse(str(connection_string))
self.bucket_factory = bucket_factory
self.authenticator = None
self._buckets = {}
if self.connstr.bucket:
raise ValueError('Cannot pass bucket to connection string: ' + self.connstr.bucket)... | _Cluster | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Cluster:
def __init__(self, connection_string='couchbase://localhost', bucket_factory=Client):
"""Creates a new Cluster object :param connection_string: Base connection string. It is an error to specify a bucket in the string. :param Callable bucket_factory: factory that open_bucket wil... | stack_v2_sparse_classes_36k_train_002596 | 13,327 | permissive | [
{
"docstring": "Creates a new Cluster object :param connection_string: Base connection string. It is an error to specify a bucket in the string. :param Callable bucket_factory: factory that open_bucket will use to instantiate buckets",
"name": "__init__",
"signature": "def __init__(self, connection_stri... | 3 | stack_v2_sparse_classes_30k_train_003939 | Implement the Python class `_Cluster` described below.
Class description:
Implement the _Cluster class.
Method signatures and docstrings:
- def __init__(self, connection_string='couchbase://localhost', bucket_factory=Client): Creates a new Cluster object :param connection_string: Base connection string. It is an erro... | Implement the Python class `_Cluster` described below.
Class description:
Implement the _Cluster class.
Method signatures and docstrings:
- def __init__(self, connection_string='couchbase://localhost', bucket_factory=Client): Creates a new Cluster object :param connection_string: Base connection string. It is an erro... | b1f3a9d69071831a37329a8c156cd8cb141f584a | <|skeleton|>
class _Cluster:
def __init__(self, connection_string='couchbase://localhost', bucket_factory=Client):
"""Creates a new Cluster object :param connection_string: Base connection string. It is an error to specify a bucket in the string. :param Callable bucket_factory: factory that open_bucket wil... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _Cluster:
def __init__(self, connection_string='couchbase://localhost', bucket_factory=Client):
"""Creates a new Cluster object :param connection_string: Base connection string. It is an error to specify a bucket in the string. :param Callable bucket_factory: factory that open_bucket will use to insta... | the_stack_v2_python_sparse | couchbase_core/cluster.py | iutinvg/couchbase-python-client | train | 0 | |
a02973ab654184e9a2235a29a74dbb64485b8e23 | [
"self.p = p\nself.i = i\nself.d = d\nself.memory = memory\nself.setpoint = setpoint\nself._pv = np.zeros(self.memory)\nself.cv = 0\nself.error = 0",
"if p is not None:\n self.p = p\nif i is not None:\n self.i = i\nif d is not None:\n self.d = d\nif memory is not None:\n self.memory = memory\nif setpoi... | <|body_start_0|>
self.p = p
self.i = i
self.d = d
self.memory = memory
self.setpoint = setpoint
self._pv = np.zeros(self.memory)
self.cv = 0
self.error = 0
<|end_body_0|>
<|body_start_1|>
if p is not None:
self.p = p
if i is no... | Generic class for PID locking | PID | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PID:
"""Generic class for PID locking"""
def __init__(self, p=0, i=0, d=0, setpoint=0, memory=20):
"""Constructor for PID class :rtype: object :param p: proportional gain :param i: integral :param d: differential :param setpoint: setpoint for process variable :param memory: number of... | stack_v2_sparse_classes_36k_train_002597 | 2,713 | permissive | [
{
"docstring": "Constructor for PID class :rtype: object :param p: proportional gain :param i: integral :param d: differential :param setpoint: setpoint for process variable :param memory: number of samples for integral memory",
"name": "__init__",
"signature": "def __init__(self, p=0, i=0, d=0, setpoin... | 4 | stack_v2_sparse_classes_30k_train_011889 | Implement the Python class `PID` described below.
Class description:
Generic class for PID locking
Method signatures and docstrings:
- def __init__(self, p=0, i=0, d=0, setpoint=0, memory=20): Constructor for PID class :rtype: object :param p: proportional gain :param i: integral :param d: differential :param setpoin... | Implement the Python class `PID` described below.
Class description:
Generic class for PID locking
Method signatures and docstrings:
- def __init__(self, p=0, i=0, d=0, setpoint=0, memory=20): Constructor for PID class :rtype: object :param p: proportional gain :param i: integral :param d: differential :param setpoin... | c8794a342d30119a6be93b2dd30ea61b5c946d8a | <|skeleton|>
class PID:
"""Generic class for PID locking"""
def __init__(self, p=0, i=0, d=0, setpoint=0, memory=20):
"""Constructor for PID class :rtype: object :param p: proportional gain :param i: integral :param d: differential :param setpoint: setpoint for process variable :param memory: number of... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PID:
"""Generic class for PID locking"""
def __init__(self, p=0, i=0, d=0, setpoint=0, memory=20):
"""Constructor for PID class :rtype: object :param p: proportional gain :param i: integral :param d: differential :param setpoint: setpoint for process variable :param memory: number of samples for ... | the_stack_v2_python_sparse | pylabnet/scripts/pid.py | lukingroup/pylabnet | train | 15 |
40e0a7dc076abea856e2b79a6f647c93acab3e12 | [
"tip_label1 = widgets.Label(u'策略相关性交叉验证暂不支持实时网络数据模式', layout=widgets.Layout(width='300px'))\ntip_label2 = widgets.Label(u\"需先用'数据下载界面操作'进行下载\", layout=widgets.Layout(width='300px'))\nself.bf = BuyFactorWGManager()\nself.sf = SellFactorWGManager(show_add_buy=True)\nsub_widget_tab = widgets.Tab()\nsub_widget_tab.chil... | <|body_start_0|>
tip_label1 = widgets.Label(u'策略相关性交叉验证暂不支持实时网络数据模式', layout=widgets.Layout(width='300px'))
tip_label2 = widgets.Label(u"需先用'数据下载界面操作'进行下载", layout=widgets.Layout(width='300px'))
self.bf = BuyFactorWGManager()
self.sf = SellFactorWGManager(show_add_buy=True)
sub_w... | 策略相关性交叉验证ui类 | WidgetCrossVal | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WidgetCrossVal:
"""策略相关性交叉验证ui类"""
def __init__(self):
"""构建回测需要的各个组件形成tab"""
<|body_0|>
def run_cross_val(self, bt):
"""交叉相关性验证策略有效性的button按钮"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
tip_label1 = widgets.Label(u'策略相关性交叉验证暂不支持实时网络数据模式', l... | stack_v2_sparse_classes_36k_train_002598 | 3,865 | permissive | [
{
"docstring": "构建回测需要的各个组件形成tab",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "交叉相关性验证策略有效性的button按钮",
"name": "run_cross_val",
"signature": "def run_cross_val(self, bt)"
}
] | 2 | null | Implement the Python class `WidgetCrossVal` described below.
Class description:
策略相关性交叉验证ui类
Method signatures and docstrings:
- def __init__(self): 构建回测需要的各个组件形成tab
- def run_cross_val(self, bt): 交叉相关性验证策略有效性的button按钮 | Implement the Python class `WidgetCrossVal` described below.
Class description:
策略相关性交叉验证ui类
Method signatures and docstrings:
- def __init__(self): 构建回测需要的各个组件形成tab
- def run_cross_val(self, bt): 交叉相关性验证策略有效性的button按钮
<|skeleton|>
class WidgetCrossVal:
"""策略相关性交叉验证ui类"""
def __init__(self):
"""构建回测... | 2e5ab17f2d20deb3c68c927f6208ea89db7c639d | <|skeleton|>
class WidgetCrossVal:
"""策略相关性交叉验证ui类"""
def __init__(self):
"""构建回测需要的各个组件形成tab"""
<|body_0|>
def run_cross_val(self, bt):
"""交叉相关性验证策略有效性的button按钮"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WidgetCrossVal:
"""策略相关性交叉验证ui类"""
def __init__(self):
"""构建回测需要的各个组件形成tab"""
tip_label1 = widgets.Label(u'策略相关性交叉验证暂不支持实时网络数据模式', layout=widgets.Layout(width='300px'))
tip_label2 = widgets.Label(u"需先用'数据下载界面操作'进行下载", layout=widgets.Layout(width='300px'))
self.bf = BuyFact... | the_stack_v2_python_sparse | abupy/WidgetBu/ABuWGCrossVal.py | luqin/firefly | train | 1 |
6227349e50a3342bba8833ce3ea221cf5796cba0 | [
"super()._init_layers()\nself.ref_point_head = MLP(self.embed_dims * 2, self.embed_dims, self.embed_dims, 2)\nself.norm = nn.LayerNorm(self.embed_dims)",
"intermediate = []\nintermediate_reference_points = [reference_points]\nfor lid, layer in enumerate(self.layers):\n if reference_points.shape[-1] == 4:\n ... | <|body_start_0|>
super()._init_layers()
self.ref_point_head = MLP(self.embed_dims * 2, self.embed_dims, self.embed_dims, 2)
self.norm = nn.LayerNorm(self.embed_dims)
<|end_body_0|>
<|body_start_1|>
intermediate = []
intermediate_reference_points = [reference_points]
for ... | Transformer encoder of DINO. | DinoTransformerDecoder | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DinoTransformerDecoder:
"""Transformer encoder of DINO."""
def _init_layers(self) -> None:
"""Initialize decoder layers."""
<|body_0|>
def forward(self, query: Tensor, value: Tensor, key_padding_mask: Tensor, self_attn_mask: Tensor, reference_points: Tensor, spatial_shap... | stack_v2_sparse_classes_36k_train_002599 | 26,710 | permissive | [
{
"docstring": "Initialize decoder layers.",
"name": "_init_layers",
"signature": "def _init_layers(self) -> None"
},
{
"docstring": "Forward function of Transformer encoder. Args: query (Tensor): The input query, has shape (num_queries, bs, dim). value (Tensor): The input values, has shape (num... | 2 | stack_v2_sparse_classes_30k_train_004690 | Implement the Python class `DinoTransformerDecoder` described below.
Class description:
Transformer encoder of DINO.
Method signatures and docstrings:
- def _init_layers(self) -> None: Initialize decoder layers.
- def forward(self, query: Tensor, value: Tensor, key_padding_mask: Tensor, self_attn_mask: Tensor, refere... | Implement the Python class `DinoTransformerDecoder` described below.
Class description:
Transformer encoder of DINO.
Method signatures and docstrings:
- def _init_layers(self) -> None: Initialize decoder layers.
- def forward(self, query: Tensor, value: Tensor, key_padding_mask: Tensor, self_attn_mask: Tensor, refere... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class DinoTransformerDecoder:
"""Transformer encoder of DINO."""
def _init_layers(self) -> None:
"""Initialize decoder layers."""
<|body_0|>
def forward(self, query: Tensor, value: Tensor, key_padding_mask: Tensor, self_attn_mask: Tensor, reference_points: Tensor, spatial_shap... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DinoTransformerDecoder:
"""Transformer encoder of DINO."""
def _init_layers(self) -> None:
"""Initialize decoder layers."""
super()._init_layers()
self.ref_point_head = MLP(self.embed_dims * 2, self.embed_dims, self.embed_dims, 2)
self.norm = nn.LayerNorm(self.embed_dims)
... | the_stack_v2_python_sparse | ai/mmdetection/mmdet/models/layers/transformer/dino_layers.py | alldatacenter/alldata | train | 774 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.