blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
66700b042f02ed0edec9cae8a9dc13a8237e6ad1 | [
"self.object_attributes_param = object_attributes_param\nself.object_param = object_param\nself.mtype = mtype",
"if dictionary is None:\n return None\nobject_attributes_param = cohesity_management_sdk.models.ad_attribute_restore_param.ADAttributeRestoreParam.from_dictionary(dictionary.get('objectAttributesPara... | <|body_start_0|>
self.object_attributes_param = object_attributes_param
self.object_param = object_param
self.mtype = mtype
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
object_attributes_param = cohesity_management_sdk.models.ad_attribute_restor... | Implementation of the 'ADUpdateRestoreTaskOptions' model. TODO: type description here. Attributes: object_attributes_param (ADAttributeRestoreParam): Object attributes restore params with the list of attributes to be restored. This is set only when type is kObjectAttributes. object_param (ADObjectRestoreParam): Object ... | ADUpdateRestoreTaskOptions | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ADUpdateRestoreTaskOptions:
"""Implementation of the 'ADUpdateRestoreTaskOptions' model. TODO: type description here. Attributes: object_attributes_param (ADAttributeRestoreParam): Object attributes restore params with the list of attributes to be restored. This is set only when type is kObjectAt... | stack_v2_sparse_classes_10k_train_002000 | 2,578 | permissive | [
{
"docstring": "Constructor for the ADUpdateRestoreTaskOptions class",
"name": "__init__",
"signature": "def __init__(self, object_attributes_param=None, object_param=None, mtype=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictio... | 2 | null | Implement the Python class `ADUpdateRestoreTaskOptions` described below.
Class description:
Implementation of the 'ADUpdateRestoreTaskOptions' model. TODO: type description here. Attributes: object_attributes_param (ADAttributeRestoreParam): Object attributes restore params with the list of attributes to be restored. ... | Implement the Python class `ADUpdateRestoreTaskOptions` described below.
Class description:
Implementation of the 'ADUpdateRestoreTaskOptions' model. TODO: type description here. Attributes: object_attributes_param (ADAttributeRestoreParam): Object attributes restore params with the list of attributes to be restored. ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ADUpdateRestoreTaskOptions:
"""Implementation of the 'ADUpdateRestoreTaskOptions' model. TODO: type description here. Attributes: object_attributes_param (ADAttributeRestoreParam): Object attributes restore params with the list of attributes to be restored. This is set only when type is kObjectAt... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ADUpdateRestoreTaskOptions:
"""Implementation of the 'ADUpdateRestoreTaskOptions' model. TODO: type description here. Attributes: object_attributes_param (ADAttributeRestoreParam): Object attributes restore params with the list of attributes to be restored. This is set only when type is kObjectAttributes. obj... | the_stack_v2_python_sparse | cohesity_management_sdk/models/ad_update_restore_task_options.py | cohesity/management-sdk-python | train | 24 |
0e75736743add8059cec445c7b5c76e389d92d80 | [
"expected = ['man']\nactual = get_top_n_words({'happy': 2, 'man': 3}, 1)\nself.assertEqual(expected, actual)",
"expected = ['happy', 'man']\nactual = get_top_n_words({'happy': 2, 'man': 2}, 2)\nself.assertEqual(expected, actual)\nexpected = ['happy']\nactual = get_top_n_words({'happy': 2, 'man': 2}, 1)\nself.asse... | <|body_start_0|>
expected = ['man']
actual = get_top_n_words({'happy': 2, 'man': 3}, 1)
self.assertEqual(expected, actual)
<|end_body_0|>
<|body_start_1|>
expected = ['happy', 'man']
actual = get_top_n_words({'happy': 2, 'man': 2}, 2)
self.assertEqual(expected, actual)
... | Tests get top number of words function | GetTopNWordsTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetTopNWordsTest:
"""Tests get top number of words function"""
def test_get_top_n_words_ideal(self):
"""Ideal get top number of words scenario"""
<|body_0|>
def test_get_top_n_words_same_frequency(self):
"""Get top number of words with the same frequency check"""... | stack_v2_sparse_classes_10k_train_002001 | 2,104 | permissive | [
{
"docstring": "Ideal get top number of words scenario",
"name": "test_get_top_n_words_ideal",
"signature": "def test_get_top_n_words_ideal(self)"
},
{
"docstring": "Get top number of words with the same frequency check",
"name": "test_get_top_n_words_same_frequency",
"signature": "def t... | 6 | stack_v2_sparse_classes_30k_train_000173 | Implement the Python class `GetTopNWordsTest` described below.
Class description:
Tests get top number of words function
Method signatures and docstrings:
- def test_get_top_n_words_ideal(self): Ideal get top number of words scenario
- def test_get_top_n_words_same_frequency(self): Get top number of words with the sa... | Implement the Python class `GetTopNWordsTest` described below.
Class description:
Tests get top number of words function
Method signatures and docstrings:
- def test_get_top_n_words_ideal(self): Ideal get top number of words scenario
- def test_get_top_n_words_same_frequency(self): Get top number of words with the sa... | ada4bec878dd1cbc19058cb4e87893946ae21498 | <|skeleton|>
class GetTopNWordsTest:
"""Tests get top number of words function"""
def test_get_top_n_words_ideal(self):
"""Ideal get top number of words scenario"""
<|body_0|>
def test_get_top_n_words_same_frequency(self):
"""Get top number of words with the same frequency check"""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GetTopNWordsTest:
"""Tests get top number of words function"""
def test_get_top_n_words_ideal(self):
"""Ideal get top number of words scenario"""
expected = ['man']
actual = get_top_n_words({'happy': 2, 'man': 3}, 1)
self.assertEqual(expected, actual)
def test_get_top... | the_stack_v2_python_sparse | lab_1/get_top_n_words_test.py | WhiteJaeger/2020-2-level-labs | train | 0 |
76d2c3f74e8fae160396b4015ccec478dba97b87 | [
"self.id_ds_conf_ds = id_ds_conf_ds\nself.value_configuration = value_configuration\nself.FK_id_configuration_DCT_DCD = FK_id_configuration_DCT_DCD\nself.FK_id_dataset_DS_DCD = FK_id_dataset_DS_DCD",
"listOfDatasetDSConfig = []\nsqlObj = _DS_config_DS_SQL()\nresults = sqlObj.select_all_DDI_DB()\nfor element in re... | <|body_start_0|>
self.id_ds_conf_ds = id_ds_conf_ds
self.value_configuration = value_configuration
self.FK_id_configuration_DCT_DCD = FK_id_configuration_DCT_DCD
self.FK_id_dataset_DS_DCD = FK_id_dataset_DS_DCD
<|end_body_0|>
<|body_start_1|>
listOfDatasetDSConfig = []
s... | This class treat the datasets configuration connection tables object has it exists in DATASET_CONF_DS table database NOTE: It consistes on a conection class (N to N) to know for each dataset with a given configuration By default, all FK are in the lasts positions in the parameters declaration | Dataset_conf_ds | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dataset_conf_ds:
"""This class treat the datasets configuration connection tables object has it exists in DATASET_CONF_DS table database NOTE: It consistes on a conection class (N to N) to know for each dataset with a given configuration By default, all FK are in the lasts positions in the parame... | stack_v2_sparse_classes_10k_train_002002 | 2,721 | permissive | [
{
"docstring": "Constructor of the DDI_interactionDB object. All the parameters have a default value :param id_ds_conf_ds: id of the configurations dataset - -1 if unknown :param value_configuration: value of the bins - -1 if unknown :param FK_id_configuration_DCT_DCD: FK of the configurations (see table DATASE... | 3 | stack_v2_sparse_classes_30k_train_003623 | Implement the Python class `Dataset_conf_ds` described below.
Class description:
This class treat the datasets configuration connection tables object has it exists in DATASET_CONF_DS table database NOTE: It consistes on a conection class (N to N) to know for each dataset with a given configuration By default, all FK a... | Implement the Python class `Dataset_conf_ds` described below.
Class description:
This class treat the datasets configuration connection tables object has it exists in DATASET_CONF_DS table database NOTE: It consistes on a conection class (N to N) to know for each dataset with a given configuration By default, all FK a... | 862eb85746e8a3a9bbc0d6aef9abbd5eebe9765f | <|skeleton|>
class Dataset_conf_ds:
"""This class treat the datasets configuration connection tables object has it exists in DATASET_CONF_DS table database NOTE: It consistes on a conection class (N to N) to know for each dataset with a given configuration By default, all FK are in the lasts positions in the parame... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Dataset_conf_ds:
"""This class treat the datasets configuration connection tables object has it exists in DATASET_CONF_DS table database NOTE: It consistes on a conection class (N to N) to know for each dataset with a given configuration By default, all FK are in the lasts positions in the parameters declarat... | the_stack_v2_python_sparse | objects_new/Dataset_config_dataset_new.py | diogo1790/inphinity | train | 1 |
d71e749841df41e6b6c65a5ce2ab2e833d2c51a8 | [
"super(GCN_3, self).__init__()\nself.node_num = 2 * frames * slice * slice\nself.frames = frames\nself.batch = batch\nself.slice = slice\nself.fc1 = nn.Linear(in_features=2048, out_features=2048, bias=False)\nself.layer1 = nn.Sequential(nn.Linear(in_features=2048, out_features=2048, bias=False), nn.LayerNorm(normal... | <|body_start_0|>
super(GCN_3, self).__init__()
self.node_num = 2 * frames * slice * slice
self.frames = frames
self.batch = batch
self.slice = slice
self.fc1 = nn.Linear(in_features=2048, out_features=2048, bias=False)
self.layer1 = nn.Sequential(nn.Linear(in_feat... | base class for STGCN | GCN_3 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GCN_3:
"""base class for STGCN"""
def __init__(self, frames, slice, batch):
"""layer 3 node_num: number of nodes, int (usually 2N * SLICE * SLICE) :param frames: get 2 * 'frames' frames in total. int :param slice: how many patches each frame is divided into in each direction, int :pa... | stack_v2_sparse_classes_10k_train_002003 | 8,501 | no_license | [
{
"docstring": "layer 3 node_num: number of nodes, int (usually 2N * SLICE * SLICE) :param frames: get 2 * 'frames' frames in total. int :param slice: how many patches each frame is divided into in each direction, int :param batch: batch size divided by gpu number, int",
"name": "__init__",
"signature":... | 3 | stack_v2_sparse_classes_30k_train_002097 | Implement the Python class `GCN_3` described below.
Class description:
base class for STGCN
Method signatures and docstrings:
- def __init__(self, frames, slice, batch): layer 3 node_num: number of nodes, int (usually 2N * SLICE * SLICE) :param frames: get 2 * 'frames' frames in total. int :param slice: how many patc... | Implement the Python class `GCN_3` described below.
Class description:
base class for STGCN
Method signatures and docstrings:
- def __init__(self, frames, slice, batch): layer 3 node_num: number of nodes, int (usually 2N * SLICE * SLICE) :param frames: get 2 * 'frames' frames in total. int :param slice: how many patc... | 9b0324b3d3a863d45680b09efef6d88bd4ddc3fb | <|skeleton|>
class GCN_3:
"""base class for STGCN"""
def __init__(self, frames, slice, batch):
"""layer 3 node_num: number of nodes, int (usually 2N * SLICE * SLICE) :param frames: get 2 * 'frames' frames in total. int :param slice: how many patches each frame is divided into in each direction, int :pa... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GCN_3:
"""base class for STGCN"""
def __init__(self, frames, slice, batch):
"""layer 3 node_num: number of nodes, int (usually 2N * SLICE * SLICE) :param frames: get 2 * 'frames' frames in total. int :param slice: how many patches each frame is divided into in each direction, int :param batch: ba... | the_stack_v2_python_sparse | models/GCN_model.py | Timon0327/Video-inpainting | train | 1 |
15e1a85868167b095c08f3b0c857620bcf167583 | [
"l, r = (0, len(height) - 1)\nmaxArea = -1\nwhile l < r:\n maxArea = max(maxArea, min(height[l], height[r]) * (r - l))\n if height[l] < height[r]:\n l += 1\n else:\n r -= 1\nreturn maxArea",
"maxHeight = -1\nmaxPos = -1\nfor i in range(len(height)):\n if height[i] >= maxHeight:\n ... | <|body_start_0|>
l, r = (0, len(height) - 1)
maxArea = -1
while l < r:
maxArea = max(maxArea, min(height[l], height[r]) * (r - l))
if height[l] < height[r]:
l += 1
else:
r -= 1
return maxArea
<|end_body_0|>
<|body_start... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l, r = (0, len(height) - 1)
maxArea =... | stack_v2_sparse_classes_10k_train_002004 | 1,827 | no_license | [
{
"docstring": ":type height: List[int] :rtype: int",
"name": "maxArea",
"signature": "def maxArea(self, height)"
},
{
"docstring": ":type height: List[int] :rtype: int",
"name": "maxArea",
"signature": "def maxArea(self, height)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006369 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea(self, height): :type height: List[int] :rtype: int
- def maxArea(self, height): :type height: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea(self, height): :type height: List[int] :rtype: int
- def maxArea(self, height): :type height: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxArea(sel... | 31012a004ba14ddfb468a91925d86bc2dfb60dd4 | <|skeleton|>
class Solution:
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
l, r = (0, len(height) - 1)
maxArea = -1
while l < r:
maxArea = max(maxArea, min(height[l], height[r]) * (r - l))
if height[l] < height[r]:
l += 1
... | the_stack_v2_python_sparse | top100like/ContainerWithMostWater.py | yuhangxiaocs/LeetCodePy | train | 1 | |
3a9f1d6cfcabd6edf49287abd5c0d48ce76d0036 | [
"self.rasterpath = rasterpath\nself.num_chunks = num_chunks\nself.chunk_list = chunk_list\nself.metadata = metadata\nself.force_scv = force_scv\nreturn",
"for chunk_obj in self.chunk_list:\n if chunk_obj.index == index:\n return chunk_obj\nelse:\n raise Exception('No chunk with chunk_id = {0}'.format... | <|body_start_0|>
self.rasterpath = rasterpath
self.num_chunks = num_chunks
self.chunk_list = chunk_list
self.metadata = metadata
self.force_scv = force_scv
return
<|end_body_0|>
<|body_start_1|>
for chunk_obj in self.chunk_list:
if chunk_obj.index == ... | Creates a chunk bundle object. it can be used to pass smaller pieces of raster data to complex functions and reduce memory consumption in those functions. Presently, chunks are not saved individually, but are always bundled to form the undivided raster image. This allows chunks to be passed individually and sequentiall... | chunk_bundle | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-us-govt-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class chunk_bundle:
"""Creates a chunk bundle object. it can be used to pass smaller pieces of raster data to complex functions and reduce memory consumption in those functions. Presently, chunks are not saved individually, but are always bundled to form the undivided raster image. This allows chunks t... | stack_v2_sparse_classes_10k_train_002005 | 5,063 | permissive | [
{
"docstring": "Creates a chunk bundle. Two probable use cases: 1) loading raster to split into smaller chunks with: inchunk = chunk_bundle(rasterpath, num_chunks = #) inchunk.load() 2) building new chunk_bundle with processed data, passing on old chunks metadata: outchunk = chunk_bundle(rasterpath, chunk_list ... | 5 | stack_v2_sparse_classes_30k_train_004940 | Implement the Python class `chunk_bundle` described below.
Class description:
Creates a chunk bundle object. it can be used to pass smaller pieces of raster data to complex functions and reduce memory consumption in those functions. Presently, chunks are not saved individually, but are always bundled to form the undiv... | Implement the Python class `chunk_bundle` described below.
Class description:
Creates a chunk bundle object. it can be used to pass smaller pieces of raster data to complex functions and reduce memory consumption in those functions. Presently, chunks are not saved individually, but are always bundled to form the undiv... | 372ba1481a155dca102612307a8e354dcf975eaa | <|skeleton|>
class chunk_bundle:
"""Creates a chunk bundle object. it can be used to pass smaller pieces of raster data to complex functions and reduce memory consumption in those functions. Presently, chunks are not saved individually, but are always bundled to form the undivided raster image. This allows chunks t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class chunk_bundle:
"""Creates a chunk bundle object. it can be used to pass smaller pieces of raster data to complex functions and reduce memory consumption in those functions. Presently, chunks are not saved individually, but are always bundled to form the undivided raster image. This allows chunks to be passed i... | the_stack_v2_python_sparse | dnppy_install/chunking/chunking.py | lmakely/dnppy | train | 0 |
646a4472c7b7854f7b7535e3468135850692b274 | [
"Polynomial.__init__(self, coefficients)\nif self.getDegree() != 2:\n raise PolynomialError('Not a quadratic polynomial.')",
"a, b, c = (self.getCoefficients()[2], self.getCoefficients()[1], self.getCoefficients()[0])\ndelta = b ** 2 - 4 * a * c\nif delta >= 0:\n roots = sorted([(-b - math.sqrt(delta)) / (2... | <|body_start_0|>
Polynomial.__init__(self, coefficients)
if self.getDegree() != 2:
raise PolynomialError('Not a quadratic polynomial.')
<|end_body_0|>
<|body_start_1|>
a, b, c = (self.getCoefficients()[2], self.getCoefficients()[1], self.getCoefficients()[0])
delta = b ** 2 ... | QuadraticPolynomial | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuadraticPolynomial:
def __init__(self, coefficients):
"""Exercise 10"""
<|body_0|>
def getRoots(self):
"""Exercise 11 Get roots of a quadratic polynomial"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Polynomial.__init__(self, coefficients)
... | stack_v2_sparse_classes_10k_train_002006 | 12,688 | no_license | [
{
"docstring": "Exercise 10",
"name": "__init__",
"signature": "def __init__(self, coefficients)"
},
{
"docstring": "Exercise 11 Get roots of a quadratic polynomial",
"name": "getRoots",
"signature": "def getRoots(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001445 | Implement the Python class `QuadraticPolynomial` described below.
Class description:
Implement the QuadraticPolynomial class.
Method signatures and docstrings:
- def __init__(self, coefficients): Exercise 10
- def getRoots(self): Exercise 11 Get roots of a quadratic polynomial | Implement the Python class `QuadraticPolynomial` described below.
Class description:
Implement the QuadraticPolynomial class.
Method signatures and docstrings:
- def __init__(self, coefficients): Exercise 10
- def getRoots(self): Exercise 11 Get roots of a quadratic polynomial
<|skeleton|>
class QuadraticPolynomial:... | a47c529a7085233ba7d7f484316d1cdd3b542df4 | <|skeleton|>
class QuadraticPolynomial:
def __init__(self, coefficients):
"""Exercise 10"""
<|body_0|>
def getRoots(self):
"""Exercise 11 Get roots of a quadratic polynomial"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class QuadraticPolynomial:
def __init__(self, coefficients):
"""Exercise 10"""
Polynomial.__init__(self, coefficients)
if self.getDegree() != 2:
raise PolynomialError('Not a quadratic polynomial.')
def getRoots(self):
"""Exercise 11 Get roots of a quadratic polynomia... | the_stack_v2_python_sparse | Lesson2/TD/Polynomial_Solutions.py | riduan91/DSC101 | train | 0 | |
878b449a69805e34d28be822bc45eccfb2609c2f | [
"super().__init__(name=name)\nself.logger.debug('%s.__init__()' % self.__class__.__name__)\nself.blackboard = self.attach_blackboard_client()\nself.blackboard.register_key(key='/foo/bar/wow', access=py_trees.common.Access.WRITE, remap_to=remap_to['/foo/bar/wow'])",
"self.logger.debug('%s.update()' % self.__class_... | <|body_start_0|>
super().__init__(name=name)
self.logger.debug('%s.__init__()' % self.__class__.__name__)
self.blackboard = self.attach_blackboard_client()
self.blackboard.register_key(key='/foo/bar/wow', access=py_trees.common.Access.WRITE, remap_to=remap_to['/foo/bar/wow'])
<|end_body_... | Custom writer that submits a more complicated variable to the blackboard. | Remap | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Remap:
"""Custom writer that submits a more complicated variable to the blackboard."""
def __init__(self, name: str, remap_to: typing.Dict[str, str]):
"""Set up the blackboard and remap variables. Args: name: behaviour name remap_to: remappings (from variable name to variable name)""... | stack_v2_sparse_classes_10k_train_002007 | 4,268 | permissive | [
{
"docstring": "Set up the blackboard and remap variables. Args: name: behaviour name remap_to: remappings (from variable name to variable name)",
"name": "__init__",
"signature": "def __init__(self, name: str, remap_to: typing.Dict[str, str])"
},
{
"docstring": "Write a dictionary to the blackb... | 2 | stack_v2_sparse_classes_30k_train_002239 | Implement the Python class `Remap` described below.
Class description:
Custom writer that submits a more complicated variable to the blackboard.
Method signatures and docstrings:
- def __init__(self, name: str, remap_to: typing.Dict[str, str]): Set up the blackboard and remap variables. Args: name: behaviour name rem... | Implement the Python class `Remap` described below.
Class description:
Custom writer that submits a more complicated variable to the blackboard.
Method signatures and docstrings:
- def __init__(self, name: str, remap_to: typing.Dict[str, str]): Set up the blackboard and remap variables. Args: name: behaviour name rem... | 17fc0aeed83ec57b1494deac848324ff61e64232 | <|skeleton|>
class Remap:
"""Custom writer that submits a more complicated variable to the blackboard."""
def __init__(self, name: str, remap_to: typing.Dict[str, str]):
"""Set up the blackboard and remap variables. Args: name: behaviour name remap_to: remappings (from variable name to variable name)""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Remap:
"""Custom writer that submits a more complicated variable to the blackboard."""
def __init__(self, name: str, remap_to: typing.Dict[str, str]):
"""Set up the blackboard and remap variables. Args: name: behaviour name remap_to: remappings (from variable name to variable name)"""
sup... | the_stack_v2_python_sparse | py_trees/demos/blackboard_remappings.py | jstyrud/py_trees | train | 0 |
b97993ad146bdcd399e7f6300f951abdfa953880 | [
"if not matrix:\n return []\nm, n = (len(matrix), len(matrix[0]))\nd = -1\nans = []\nfor s in range(m + n - 1):\n _min = max(0, s - n + 1)\n _max = min(s, m - 1)\n if d == -1:\n for i in range(_max, _min - 1, -1):\n ans.append(matrix[i][s - i])\n else:\n for i in range(_min, ... | <|body_start_0|>
if not matrix:
return []
m, n = (len(matrix), len(matrix[0]))
d = -1
ans = []
for s in range(m + n - 1):
_min = max(0, s - n + 1)
_max = min(s, m - 1)
if d == -1:
for i in range(_max, _min - 1, -1):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDiagonalOrder1(self, matrix: List[List[int]]) -> List[int]:
"""for loop"""
<|body_0|>
def findDiagonalOrder2(self, matrix: List[List[int]]) -> List[int]:
"""while loop"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not matrix:
... | stack_v2_sparse_classes_10k_train_002008 | 1,766 | no_license | [
{
"docstring": "for loop",
"name": "findDiagonalOrder1",
"signature": "def findDiagonalOrder1(self, matrix: List[List[int]]) -> List[int]"
},
{
"docstring": "while loop",
"name": "findDiagonalOrder2",
"signature": "def findDiagonalOrder2(self, matrix: List[List[int]]) -> List[int]"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDiagonalOrder1(self, matrix: List[List[int]]) -> List[int]: for loop
- def findDiagonalOrder2(self, matrix: List[List[int]]) -> List[int]: while loop | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDiagonalOrder1(self, matrix: List[List[int]]) -> List[int]: for loop
- def findDiagonalOrder2(self, matrix: List[List[int]]) -> List[int]: while loop
<|skeleton|>
class ... | 6ff1941ff213a843013100ac7033e2d4f90fbd6a | <|skeleton|>
class Solution:
def findDiagonalOrder1(self, matrix: List[List[int]]) -> List[int]:
"""for loop"""
<|body_0|>
def findDiagonalOrder2(self, matrix: List[List[int]]) -> List[int]:
"""while loop"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findDiagonalOrder1(self, matrix: List[List[int]]) -> List[int]:
"""for loop"""
if not matrix:
return []
m, n = (len(matrix), len(matrix[0]))
d = -1
ans = []
for s in range(m + n - 1):
_min = max(0, s - n + 1)
_ma... | the_stack_v2_python_sparse | Leetcode 0498. Diagonal Traversal.py | Chaoran-sjsu/leetcode | train | 0 | |
791703677db4c430ebf7f448ff773c7f55b5083a | [
"plt.figure()\naxes = plt.gca()\ndata_lab = self.meta['OBS-FREQ'][0:2] + ' ' + self.meta['OBS-FREQ'][2:5]\naxes.plot(self.data.index, self.data, label=data_lab)\naxes.set_yscale('log')\naxes.set_ylim(0.0001, 1)\naxes.set_title('Nobeyama Radioheliograph')\naxes.set_xlabel('Start time: ' + self.data.index[0].strftime... | <|body_start_0|>
plt.figure()
axes = plt.gca()
data_lab = self.meta['OBS-FREQ'][0:2] + ' ' + self.meta['OBS-FREQ'][2:5]
axes.plot(self.data.index, self.data, label=data_lab)
axes.set_yscale('log')
axes.set_ylim(0.0001, 1)
axes.set_title('Nobeyama Radioheliograph')... | Nobeyama Radioheliograph Correlation LightCurve. Nobeyama Radioheliograph (NoRH) is a radio telescope dedicated to observing the Sun. It consists of 84 parabolic antennas with 80 cm diameter, sitting on lines of 490 m long in the east/west and of 220 m long in the north/south. It observes the full solar disk at 17 GHz ... | NoRHLightCurve | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoRHLightCurve:
"""Nobeyama Radioheliograph Correlation LightCurve. Nobeyama Radioheliograph (NoRH) is a radio telescope dedicated to observing the Sun. It consists of 84 parabolic antennas with 80 cm diameter, sitting on lines of 490 m long in the east/west and of 220 m long in the north/south. ... | stack_v2_sparse_classes_10k_train_002009 | 4,421 | permissive | [
{
"docstring": "Plots the NoRH lightcurve .. plot:: from sunpy import lightcurve as lc from sunpy.data.sample import NORH_TIMESERIES norh = lc.NoRHLightCurve.create(NORH_TIMESERIES) norh.peek() Parameters ---------- **kwargs : dict Any additional plot arguments that should be used when plotting.",
"name": "... | 3 | stack_v2_sparse_classes_30k_train_000421 | Implement the Python class `NoRHLightCurve` described below.
Class description:
Nobeyama Radioheliograph Correlation LightCurve. Nobeyama Radioheliograph (NoRH) is a radio telescope dedicated to observing the Sun. It consists of 84 parabolic antennas with 80 cm diameter, sitting on lines of 490 m long in the east/west... | Implement the Python class `NoRHLightCurve` described below.
Class description:
Nobeyama Radioheliograph Correlation LightCurve. Nobeyama Radioheliograph (NoRH) is a radio telescope dedicated to observing the Sun. It consists of 84 parabolic antennas with 80 cm diameter, sitting on lines of 490 m long in the east/west... | 52fb75ece4677e554d5a6a5b43fa116a66d1fcdc | <|skeleton|>
class NoRHLightCurve:
"""Nobeyama Radioheliograph Correlation LightCurve. Nobeyama Radioheliograph (NoRH) is a radio telescope dedicated to observing the Sun. It consists of 84 parabolic antennas with 80 cm diameter, sitting on lines of 490 m long in the east/west and of 220 m long in the north/south. ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NoRHLightCurve:
"""Nobeyama Radioheliograph Correlation LightCurve. Nobeyama Radioheliograph (NoRH) is a radio telescope dedicated to observing the Sun. It consists of 84 parabolic antennas with 80 cm diameter, sitting on lines of 490 m long in the east/west and of 220 m long in the north/south. It observes t... | the_stack_v2_python_sparse | sunpy/lightcurve/sources/norh.py | cosmologist10/sunpy | train | 1 |
61c24e6a861cbd9e3f4b822619c6d42c9b293c2a | [
"max_sieve = 1000000\nif n > max_sieve:\n print('%d is too large to compute sieve' % d)\n sys.exit(-1)\nself.mx = n * n\nself.sieve(n)",
"if n > self.mx:\n print('%d is too large to factor. Max size is %d' % (n, mx))\n return False\nsq = int(math.ceil(math.sqrt(n)))\nm = n\nf = []\nfor p in self.plist... | <|body_start_0|>
max_sieve = 1000000
if n > max_sieve:
print('%d is too large to compute sieve' % d)
sys.exit(-1)
self.mx = n * n
self.sieve(n)
<|end_body_0|>
<|body_start_1|>
if n > self.mx:
print('%d is too large to factor. Max size is %d' %... | sieve | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class sieve:
def __init__(self, n=10000):
"""Computes the sieve"""
<|body_0|>
def factor(self, n):
"""Factors in into its prime components and their exponents. Returns a list of tuples (p,e), where p is a prime factor and e is the exponent of p."""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_002010 | 3,579 | no_license | [
{
"docstring": "Computes the sieve",
"name": "__init__",
"signature": "def __init__(self, n=10000)"
},
{
"docstring": "Factors in into its prime components and their exponents. Returns a list of tuples (p,e), where p is a prime factor and e is the exponent of p.",
"name": "factor",
"sign... | 5 | stack_v2_sparse_classes_30k_train_002736 | Implement the Python class `sieve` described below.
Class description:
Implement the sieve class.
Method signatures and docstrings:
- def __init__(self, n=10000): Computes the sieve
- def factor(self, n): Factors in into its prime components and their exponents. Returns a list of tuples (p,e), where p is a prime fact... | Implement the Python class `sieve` described below.
Class description:
Implement the sieve class.
Method signatures and docstrings:
- def __init__(self, n=10000): Computes the sieve
- def factor(self, n): Factors in into its prime components and their exponents. Returns a list of tuples (p,e), where p is a prime fact... | a34f151d4ec4f1f6b90ad65afc8ef70e78adb28d | <|skeleton|>
class sieve:
def __init__(self, n=10000):
"""Computes the sieve"""
<|body_0|>
def factor(self, n):
"""Factors in into its prime components and their exponents. Returns a list of tuples (p,e), where p is a prime factor and e is the exponent of p."""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class sieve:
def __init__(self, n=10000):
"""Computes the sieve"""
max_sieve = 1000000
if n > max_sieve:
print('%d is too large to compute sieve' % d)
sys.exit(-1)
self.mx = n * n
self.sieve(n)
def factor(self, n):
"""Factors in into its p... | the_stack_v2_python_sparse | euler/utilities/primes.py | khmacdonald/Misc | train | 0 | |
ac5495659c703eaf21bbb892bd562988171ff67b | [
"super(RNN, self).__init__()\nself.output_size = output_size\nself.n_layers = n_layers\nself.hidden_dim = hidden_dim\nself.embedding = nn.Embedding(vocab_size, embedding_dim)\nself.lstm = nn.LSTM(embedding_dim, hidden_dim, n_layers, dropout=dropout, batch_first=True)\nself.fc = nn.Linear(hidden_dim, output_size)\ns... | <|body_start_0|>
super(RNN, self).__init__()
self.output_size = output_size
self.n_layers = n_layers
self.hidden_dim = hidden_dim
self.embedding = nn.Embedding(vocab_size, embedding_dim)
self.lstm = nn.LSTM(embedding_dim, hidden_dim, n_layers, dropout=dropout, batch_first... | RNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNN:
def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5):
"""Initialize the PyTorch RNN Module :param vocab_size: The number of input dimensions of the neural network (the size of the vocabulary) :param output_size: The number of output dimension... | stack_v2_sparse_classes_10k_train_002011 | 11,384 | permissive | [
{
"docstring": "Initialize the PyTorch RNN Module :param vocab_size: The number of input dimensions of the neural network (the size of the vocabulary) :param output_size: The number of output dimensions of the neural network :param embedding_dim: The size of embeddings, should you choose to use them :param hidd... | 3 | stack_v2_sparse_classes_30k_train_006169 | Implement the Python class `RNN` described below.
Class description:
Implement the RNN class.
Method signatures and docstrings:
- def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5): Initialize the PyTorch RNN Module :param vocab_size: The number of input dimensions of the ne... | Implement the Python class `RNN` described below.
Class description:
Implement the RNN class.
Method signatures and docstrings:
- def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5): Initialize the PyTorch RNN Module :param vocab_size: The number of input dimensions of the ne... | b9b54564f94aadfc3c71ff513da0f05ef85d22a8 | <|skeleton|>
class RNN:
def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5):
"""Initialize the PyTorch RNN Module :param vocab_size: The number of input dimensions of the neural network (the size of the vocabulary) :param output_size: The number of output dimension... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RNN:
def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5):
"""Initialize the PyTorch RNN Module :param vocab_size: The number of input dimensions of the neural network (the size of the vocabulary) :param output_size: The number of output dimensions of the neura... | the_stack_v2_python_sparse | dl/pytorch/rnn/tv_script.py | xta0/Python-Playground | train | 0 | |
e2ac8c6d73d64d13a2a867a527fb4b8478e53d7e | [
"i = int(len(nums) > 0)\nfor n in nums:\n if n > nums[i - 1]:\n nums[i] = n\n i += 1\nreturn i",
"i, j = (0, 1)\nwhile j < len(nums):\n if nums[i] == nums[j]:\n j += 1\n else:\n i += 1\n nums[i] = nums[j]\n j += 1\nreturn i + 1"
] | <|body_start_0|>
i = int(len(nums) > 0)
for n in nums:
if n > nums[i - 1]:
nums[i] = n
i += 1
return i
<|end_body_0|>
<|body_start_1|>
i, j = (0, 1)
while j < len(nums):
if nums[i] == nums[j]:
j += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def remove_duplicates(self, nums):
""":type nums: List[int] :rtype: int 我比较喜欢这种写法,没有采用传统的 old-style indexed looping,正好结合 python 的遍历形式, 在遍历过程中,比较当前值是否大于前值,要与前值比较,当然至少要从第二个位置(如果有的话)开始, 利用 i = int(len(nums) > 0) 的写法,可以省略对 i 的判断,直接定位出初始位置。对应空数组和只有一个 元素的数组,i 值即为数组长度;对于长度大于 1 的数组,因为每... | stack_v2_sparse_classes_10k_train_002012 | 2,169 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int 我比较喜欢这种写法,没有采用传统的 old-style indexed looping,正好结合 python 的遍历形式, 在遍历过程中,比较当前值是否大于前值,要与前值比较,当然至少要从第二个位置(如果有的话)开始, 利用 i = int(len(nums) > 0) 的写法,可以省略对 i 的判断,直接定位出初始位置。对应空数组和只有一个 元素的数组,i 值即为数组长度;对于长度大于 1 的数组,因为每次在前后值不等时,i 后移了一位,直接返回 i 的值即为 有效数组长度",
"name": "remov... | 2 | stack_v2_sparse_classes_30k_train_006539 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def remove_duplicates(self, nums): :type nums: List[int] :rtype: int 我比较喜欢这种写法,没有采用传统的 old-style indexed looping,正好结合 python 的遍历形式, 在遍历过程中,比较当前值是否大于前值,要与前值比较,当然至少要从第二个位置(如果有的话)开始... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def remove_duplicates(self, nums): :type nums: List[int] :rtype: int 我比较喜欢这种写法,没有采用传统的 old-style indexed looping,正好结合 python 的遍历形式, 在遍历过程中,比较当前值是否大于前值,要与前值比较,当然至少要从第二个位置(如果有的话)开始... | 2b7f4a9fefbfd358f8ff31362d60e2007641ca29 | <|skeleton|>
class Solution:
def remove_duplicates(self, nums):
""":type nums: List[int] :rtype: int 我比较喜欢这种写法,没有采用传统的 old-style indexed looping,正好结合 python 的遍历形式, 在遍历过程中,比较当前值是否大于前值,要与前值比较,当然至少要从第二个位置(如果有的话)开始, 利用 i = int(len(nums) > 0) 的写法,可以省略对 i 的判断,直接定位出初始位置。对应空数组和只有一个 元素的数组,i 值即为数组长度;对于长度大于 1 的数组,因为每... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def remove_duplicates(self, nums):
""":type nums: List[int] :rtype: int 我比较喜欢这种写法,没有采用传统的 old-style indexed looping,正好结合 python 的遍历形式, 在遍历过程中,比较当前值是否大于前值,要与前值比较,当然至少要从第二个位置(如果有的话)开始, 利用 i = int(len(nums) > 0) 的写法,可以省略对 i 的判断,直接定位出初始位置。对应空数组和只有一个 元素的数组,i 值即为数组长度;对于长度大于 1 的数组,因为每次在前后值不等时,i 后移了... | the_stack_v2_python_sparse | Week_01/G20190343020166/LeetCode_26_0166.py | algorithm005-class01/algorithm005-class01 | train | 27 | |
9e3b840c54734cffbcb4fa7481f0ee433f2b74f0 | [
"super(BinaryFocalLoss, self).__init__(name=name)\nself.gamma = gamma\nself.alpha = alpha",
"y_true = tf.cast(y_true, tf.float32)\nepsilon = K.epsilon()\ny_pred = K.clip(y_pred, epsilon, 1.0 - epsilon)\np_t = tf.where(K.equal(y_true, 1), y_pred, 1 - y_pred)\nalpha_factor = K.ones_like(y_true) * self.alpha\nalpha_... | <|body_start_0|>
super(BinaryFocalLoss, self).__init__(name=name)
self.gamma = gamma
self.alpha = alpha
<|end_body_0|>
<|body_start_1|>
y_true = tf.cast(y_true, tf.float32)
epsilon = K.epsilon()
y_pred = K.clip(y_pred, epsilon, 1.0 - epsilon)
p_t = tf.where(K.equ... | Implementation of simple binary focal loss. | BinaryFocalLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinaryFocalLoss:
"""Implementation of simple binary focal loss."""
def __init__(self, name=None, gamma=2.0, alpha=0.25):
""":param name: displayed name for loss function :param gamma: gamma constant used in focal loss. gamma > 0 reduces the relative loss for well-classified examples ... | stack_v2_sparse_classes_10k_train_002013 | 3,619 | permissive | [
{
"docstring": ":param name: displayed name for loss function :param gamma: gamma constant used in focal loss. gamma > 0 reduces the relative loss for well-classified examples (p>0.5) putting more focus on hard misclassified example :param alpha: alpha constant used in focal loss equation. scalar factor to redu... | 2 | stack_v2_sparse_classes_30k_train_007013 | Implement the Python class `BinaryFocalLoss` described below.
Class description:
Implementation of simple binary focal loss.
Method signatures and docstrings:
- def __init__(self, name=None, gamma=2.0, alpha=0.25): :param name: displayed name for loss function :param gamma: gamma constant used in focal loss. gamma > ... | Implement the Python class `BinaryFocalLoss` described below.
Class description:
Implementation of simple binary focal loss.
Method signatures and docstrings:
- def __init__(self, name=None, gamma=2.0, alpha=0.25): :param name: displayed name for loss function :param gamma: gamma constant used in focal loss. gamma > ... | 391b4d84c9994e9abda64c6e48f2eac6b374b052 | <|skeleton|>
class BinaryFocalLoss:
"""Implementation of simple binary focal loss."""
def __init__(self, name=None, gamma=2.0, alpha=0.25):
""":param name: displayed name for loss function :param gamma: gamma constant used in focal loss. gamma > 0 reduces the relative loss for well-classified examples ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BinaryFocalLoss:
"""Implementation of simple binary focal loss."""
def __init__(self, name=None, gamma=2.0, alpha=0.25):
""":param name: displayed name for loss function :param gamma: gamma constant used in focal loss. gamma > 0 reduces the relative loss for well-classified examples (p>0.5) putti... | the_stack_v2_python_sparse | losses/focal_loss.py | Barchid/Indoor_Segmentation | train | 2 |
2fc7f12b22a41be1f79d3732d18a82c818a8f2e9 | [
"super().__init__(name=name)\nself.input_size = None\nself.output_size = output_size\nself.with_bias = with_bias\nself.w_init = w_init\nself.b_init = b_init or jnp.zeros",
"if not inputs.shape:\n raise ValueError('Input must not be scalar.')\ninput_size = self.input_size = inputs.shape[-1]\noutput_size = self.... | <|body_start_0|>
super().__init__(name=name)
self.input_size = None
self.output_size = output_size
self.with_bias = with_bias
self.w_init = w_init
self.b_init = b_init or jnp.zeros
<|end_body_0|>
<|body_start_1|>
if not inputs.shape:
raise ValueError(... | Linear module. | Linear | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Linear:
"""Linear module."""
def __init__(self, output_size: int, with_bias: bool=True, w_init: Optional[hk.initializers.Initializer]=None, b_init: Optional[hk.initializers.Initializer]=None, name: Optional[str]=None):
"""Constructs the Linear module. Args: output_size: Output dimens... | stack_v2_sparse_classes_10k_train_002014 | 11,578 | permissive | [
{
"docstring": "Constructs the Linear module. Args: output_size: Output dimensionality. with_bias: Whether to add a bias to the output. w_init: Optional initializer for weights. By default, uses random values from truncated normal, with stddev ``1 / sqrt(fan_in)``. See https://arxiv.org/abs/1502.03167v3. b_init... | 2 | stack_v2_sparse_classes_30k_train_000368 | Implement the Python class `Linear` described below.
Class description:
Linear module.
Method signatures and docstrings:
- def __init__(self, output_size: int, with_bias: bool=True, w_init: Optional[hk.initializers.Initializer]=None, b_init: Optional[hk.initializers.Initializer]=None, name: Optional[str]=None): Const... | Implement the Python class `Linear` described below.
Class description:
Linear module.
Method signatures and docstrings:
- def __init__(self, output_size: int, with_bias: bool=True, w_init: Optional[hk.initializers.Initializer]=None, b_init: Optional[hk.initializers.Initializer]=None, name: Optional[str]=None): Const... | 66f9c69353a6259a3523875fdc24ca35c5f27131 | <|skeleton|>
class Linear:
"""Linear module."""
def __init__(self, output_size: int, with_bias: bool=True, w_init: Optional[hk.initializers.Initializer]=None, b_init: Optional[hk.initializers.Initializer]=None, name: Optional[str]=None):
"""Constructs the Linear module. Args: output_size: Output dimens... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Linear:
"""Linear module."""
def __init__(self, output_size: int, with_bias: bool=True, w_init: Optional[hk.initializers.Initializer]=None, b_init: Optional[hk.initializers.Initializer]=None, name: Optional[str]=None):
"""Constructs the Linear module. Args: output_size: Output dimensionality. wit... | the_stack_v2_python_sparse | haiku/_src/basic.py | arita37/dm-haiku | train | 1 |
d7bd925d86bc94029018158283007d12061bbb81 | [
"if max_iter < 0:\n raise ValueError('Argument, max_iter must be positive')\nif min_change < 0:\n raise ValueError('Arguement: min_change must be positive')\nself._max_iter = max_iter\nself._min_change = min_change\nsuper().__init__()",
"if gradients is None:\n raise TypeError('Argument: gradients must b... | <|body_start_0|>
if max_iter < 0:
raise ValueError('Argument, max_iter must be positive')
if min_change < 0:
raise ValueError('Arguement: min_change must be positive')
self._max_iter = max_iter
self._min_change = min_change
super().__init__()
<|end_body_0|... | FrankWolfeSolver class. Inherits from the COPSolver class. FrankWolfeSolver is used to calculate the numerical solutions for the QCOP for 2 or more gradients Attributes: max_iter: max number of iterations for the algorithm min_change: minimum change stopping criterion. The algorithms stop when the difference between it... | FrankWolfeSolver | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FrankWolfeSolver:
"""FrankWolfeSolver class. Inherits from the COPSolver class. FrankWolfeSolver is used to calculate the numerical solutions for the QCOP for 2 or more gradients Attributes: max_iter: max number of iterations for the algorithm min_change: minimum change stopping criterion. The al... | stack_v2_sparse_classes_10k_train_002015 | 4,848 | permissive | [
{
"docstring": "Inits FrankWolfeSolver with hyperparameters values Args: max_iter: maximum number of iterations. Must be <= 1. default value is 100. min_change: minimum change stopping criterion. Must be < 0 default value is 1e-3",
"name": "__init__",
"signature": "def __init__(self, max_iter=100, min_c... | 3 | stack_v2_sparse_classes_30k_train_002528 | Implement the Python class `FrankWolfeSolver` described below.
Class description:
FrankWolfeSolver class. Inherits from the COPSolver class. FrankWolfeSolver is used to calculate the numerical solutions for the QCOP for 2 or more gradients Attributes: max_iter: max number of iterations for the algorithm min_change: mi... | Implement the Python class `FrankWolfeSolver` described below.
Class description:
FrankWolfeSolver class. Inherits from the COPSolver class. FrankWolfeSolver is used to calculate the numerical solutions for the QCOP for 2 or more gradients Attributes: max_iter: max number of iterations for the algorithm min_change: mi... | 26d6a08c8c7e7d33ad60d7e6896b0ffeede41bc1 | <|skeleton|>
class FrankWolfeSolver:
"""FrankWolfeSolver class. Inherits from the COPSolver class. FrankWolfeSolver is used to calculate the numerical solutions for the QCOP for 2 or more gradients Attributes: max_iter: max number of iterations for the algorithm min_change: minimum change stopping criterion. The al... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FrankWolfeSolver:
"""FrankWolfeSolver class. Inherits from the COPSolver class. FrankWolfeSolver is used to calculate the numerical solutions for the QCOP for 2 or more gradients Attributes: max_iter: max number of iterations for the algorithm min_change: minimum change stopping criterion. The algorithms stop... | the_stack_v2_python_sparse | copsolver/frank_wolfe_solver.py | swisscom/ai-research-mamo-framework | train | 30 |
53685b4dccb641ea5d11ed199971c3222b883dc8 | [
"while True:\n container = scan_q.get()\n self.process_container(container)\n scan_q.task_done()",
"j = journal.Reader(path='/host/var/log/journal')\nj.log_level(journal.LOG_INFO)\nj.this_boot()\nj.add_match(_SYSTEMD_UNIT=u'atomic-openshift-node.service')\nj.seek_tail()\nj.get_previous()\npollobj = selec... | <|body_start_0|>
while True:
container = scan_q.get()
self.process_container(container)
scan_q.task_done()
<|end_body_0|>
<|body_start_1|>
j = journal.Reader(path='/host/var/log/journal')
j.log_level(journal.LOG_INFO)
j.this_boot()
j.add_match... | Class to receive and report scan results. | PlegEventListener | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlegEventListener:
"""Class to receive and report scan results."""
def scan_worker(self, scan_q):
"""Worker thread function."""
<|body_0|>
def catch_creates(scan_q):
"""Watch the host node journal for creates."""
<|body_1|>
def process_container(cont... | stack_v2_sparse_classes_10k_train_002016 | 3,450 | permissive | [
{
"docstring": "Worker thread function.",
"name": "scan_worker",
"signature": "def scan_worker(self, scan_q)"
},
{
"docstring": "Watch the host node journal for creates.",
"name": "catch_creates",
"signature": "def catch_creates(scan_q)"
},
{
"docstring": "Check if provided conta... | 4 | null | Implement the Python class `PlegEventListener` described below.
Class description:
Class to receive and report scan results.
Method signatures and docstrings:
- def scan_worker(self, scan_q): Worker thread function.
- def catch_creates(scan_q): Watch the host node journal for creates.
- def process_container(containe... | Implement the Python class `PlegEventListener` described below.
Class description:
Class to receive and report scan results.
Method signatures and docstrings:
- def scan_worker(self, scan_q): Worker thread function.
- def catch_creates(scan_q): Watch the host node journal for creates.
- def process_container(containe... | e342f6659a4ef1a188ff403e2fc6b06ac6d119c7 | <|skeleton|>
class PlegEventListener:
"""Class to receive and report scan results."""
def scan_worker(self, scan_q):
"""Worker thread function."""
<|body_0|>
def catch_creates(scan_q):
"""Watch the host node journal for creates."""
<|body_1|>
def process_container(cont... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PlegEventListener:
"""Class to receive and report scan results."""
def scan_worker(self, scan_q):
"""Worker thread function."""
while True:
container = scan_q.get()
self.process_container(container)
scan_q.task_done()
def catch_creates(scan_q):
... | the_stack_v2_python_sparse | docker/oso-image-inspector/src/scripts/orchestrator | openshift/openshift-tools | train | 170 |
55c5973e55454d5964633acfd8b357c427964929 | [
"self.code = code\nself.language = language\nself.tokennames = tokennames\nself.lexer = None\nif language in ('', 'text') or tokennames == 'none':\n return\nif not with_pygments:\n raise LexerError('Cannot analyze code. Pygments package not found.')\ntry:\n self.lexer = get_lexer_by_name(self.language)\nex... | <|body_start_0|>
self.code = code
self.language = language
self.tokennames = tokennames
self.lexer = None
if language in ('', 'text') or tokennames == 'none':
return
if not with_pygments:
raise LexerError('Cannot analyze code. Pygments package not ... | Parse `code` lines and yield "classified" tokens. Arguments code -- string of source code to parse, language -- formal language the code is written in, tokennames -- either 'long', 'short', or '' (see below). Merge subsequent tokens of the same token-type. Iterating over an instance yields the tokens as ``(tokentype, v... | Lexer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Lexer:
"""Parse `code` lines and yield "classified" tokens. Arguments code -- string of source code to parse, language -- formal language the code is written in, tokennames -- either 'long', 'short', or '' (see below). Merge subsequent tokens of the same token-type. Iterating over an instance yie... | stack_v2_sparse_classes_10k_train_002017 | 4,872 | permissive | [
{
"docstring": "Set up a lexical analyzer for `code` in `language`.",
"name": "__init__",
"signature": "def __init__(self, code, language, tokennames='short')"
},
{
"docstring": "Merge subsequent tokens of same token-type. Also strip the final newline (added by pygments).",
"name": "merge",
... | 3 | stack_v2_sparse_classes_30k_train_002860 | Implement the Python class `Lexer` described below.
Class description:
Parse `code` lines and yield "classified" tokens. Arguments code -- string of source code to parse, language -- formal language the code is written in, tokennames -- either 'long', 'short', or '' (see below). Merge subsequent tokens of the same tok... | Implement the Python class `Lexer` described below.
Class description:
Parse `code` lines and yield "classified" tokens. Arguments code -- string of source code to parse, language -- formal language the code is written in, tokennames -- either 'long', 'short', or '' (see below). Merge subsequent tokens of the same tok... | 05dbd4575d01a213f3f4d69aa4968473f2536142 | <|skeleton|>
class Lexer:
"""Parse `code` lines and yield "classified" tokens. Arguments code -- string of source code to parse, language -- formal language the code is written in, tokennames -- either 'long', 'short', or '' (see below). Merge subsequent tokens of the same token-type. Iterating over an instance yie... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Lexer:
"""Parse `code` lines and yield "classified" tokens. Arguments code -- string of source code to parse, language -- formal language the code is written in, tokennames -- either 'long', 'short', or '' (see below). Merge subsequent tokens of the same token-type. Iterating over an instance yields the token... | the_stack_v2_python_sparse | python/helpers/py2only/docutils/utils/code_analyzer.py | JetBrains/intellij-community | train | 16,288 |
d6697b69f888aa83ef7cbd034c6a20d4dd7f0745 | [
"super(DeepLPFParameterPrediction, self).__init__()\nself.num_in_channels = num_in_channels\nself.num_out_channels = num_out_channels\nself.cubic_filter = CubicFilter()\nself.graduated_filter = GraduatedFilter()\nself.elliptical_filter = EllipticalFilter()",
"x.contiguous()\nx.cuda()\nfeat = x[:, 3:64, :, :]\nimg... | <|body_start_0|>
super(DeepLPFParameterPrediction, self).__init__()
self.num_in_channels = num_in_channels
self.num_out_channels = num_out_channels
self.cubic_filter = CubicFilter()
self.graduated_filter = GraduatedFilter()
self.elliptical_filter = EllipticalFilter()
<|en... | DeepLPFParameterPrediction | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeepLPFParameterPrediction:
def __init__(self, num_in_channels=64, num_out_channels=64, batch_size=1):
"""Initialisation function :param num_in_channels: Number of input feature maps :param num_out_channels: Number of output feature maps :param batch_size: Size of image batch :returns: N... | stack_v2_sparse_classes_10k_train_002018 | 38,578 | permissive | [
{
"docstring": "Initialisation function :param num_in_channels: Number of input feature maps :param num_out_channels: Number of output feature maps :param batch_size: Size of image batch :returns: N/A :rtype: N/A",
"name": "__init__",
"signature": "def __init__(self, num_in_channels=64, num_out_channels... | 2 | stack_v2_sparse_classes_30k_train_000246 | Implement the Python class `DeepLPFParameterPrediction` described below.
Class description:
Implement the DeepLPFParameterPrediction class.
Method signatures and docstrings:
- def __init__(self, num_in_channels=64, num_out_channels=64, batch_size=1): Initialisation function :param num_in_channels: Number of input fea... | Implement the Python class `DeepLPFParameterPrediction` described below.
Class description:
Implement the DeepLPFParameterPrediction class.
Method signatures and docstrings:
- def __init__(self, num_in_channels=64, num_out_channels=64, batch_size=1): Initialisation function :param num_in_channels: Number of input fea... | 82c49c36b76987a46dec8479793f7cf0150839c6 | <|skeleton|>
class DeepLPFParameterPrediction:
def __init__(self, num_in_channels=64, num_out_channels=64, batch_size=1):
"""Initialisation function :param num_in_channels: Number of input feature maps :param num_out_channels: Number of output feature maps :param batch_size: Size of image batch :returns: N... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DeepLPFParameterPrediction:
def __init__(self, num_in_channels=64, num_out_channels=64, batch_size=1):
"""Initialisation function :param num_in_channels: Number of input feature maps :param num_out_channels: Number of output feature maps :param batch_size: Size of image batch :returns: N/A :rtype: N/A... | the_stack_v2_python_sparse | DeepLPF/model.py | huawei-noah/noah-research | train | 816 | |
240095c0488be53dfe26b4c0c5b361b176b79cf8 | [
"self.login()\nclient = Clients.objects.first()\nng = NotificationGroups.objects.first()\nresponse = self.client.get(reverse('linkednotifcationgroups'), {'client_id': client.id}, format='json')\nexpected = NotificationGroups.objects.filter(contacts__client_id=client.id)\nserializer = DropDownSerializer(expected, ma... | <|body_start_0|>
self.login()
client = Clients.objects.first()
ng = NotificationGroups.objects.first()
response = self.client.get(reverse('linkednotifcationgroups'), {'client_id': client.id}, format='json')
expected = NotificationGroups.objects.filter(contacts__client_id=client.i... | GetSamplesTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetSamplesTest:
def test_get_linked_notify_groups(self):
"""This test ensures that notification groups attached to the client id are returned"""
<|body_0|>
def test_get_all_samples(self):
"""This test ensures that all samples added in the setUp method exist when loop... | stack_v2_sparse_classes_10k_train_002019 | 19,832 | no_license | [
{
"docstring": "This test ensures that notification groups attached to the client id are returned",
"name": "test_get_linked_notify_groups",
"signature": "def test_get_linked_notify_groups(self)"
},
{
"docstring": "This test ensures that all samples added in the setUp method exist when loop thro... | 3 | stack_v2_sparse_classes_30k_train_007229 | Implement the Python class `GetSamplesTest` described below.
Class description:
Implement the GetSamplesTest class.
Method signatures and docstrings:
- def test_get_linked_notify_groups(self): This test ensures that notification groups attached to the client id are returned
- def test_get_all_samples(self): This test... | Implement the Python class `GetSamplesTest` described below.
Class description:
Implement the GetSamplesTest class.
Method signatures and docstrings:
- def test_get_linked_notify_groups(self): This test ensures that notification groups attached to the client id are returned
- def test_get_all_samples(self): This test... | 1c6e2cf3b0d347e68d4b105e4d2b12824a2ae0fb | <|skeleton|>
class GetSamplesTest:
def test_get_linked_notify_groups(self):
"""This test ensures that notification groups attached to the client id are returned"""
<|body_0|>
def test_get_all_samples(self):
"""This test ensures that all samples added in the setUp method exist when loop... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GetSamplesTest:
def test_get_linked_notify_groups(self):
"""This test ensures that notification groups attached to the client id are returned"""
self.login()
client = Clients.objects.first()
ng = NotificationGroups.objects.first()
response = self.client.get(reverse('lin... | the_stack_v2_python_sparse | eldashboard/tests.py | ahmedsaatci/lims | train | 0 | |
0d20c6f7ff0f58faade08b1e5b77340fd3878fec | [
"self.am_coeffs = None\nself.alt_coeffs = None\nself.reference_transmission = 1.0\nself.poly_am = None\nself.poly_alt = None\nself.configure_options(options)",
"if not isinstance(options, dict):\n raise ValueError(f'Options must be a {dict}. Received {options}.')\nam_coeffs = get_float_list(options.get('amcoe... | <|body_start_0|>
self.am_coeffs = None
self.alt_coeffs = None
self.reference_transmission = 1.0
self.poly_am = None
self.poly_alt = None
self.configure_options(options)
<|end_body_0|>
<|body_start_1|>
if not isinstance(options, dict):
raise ValueError... | AtranModel | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AtranModel:
def __init__(self, options):
"""Initialize the ATRAN model for SOFIA. The ATRAN model is used to derive the relative transmission correction factor for a given altitude above the Earth's surface, observing a source at a given elevation. This can be used to determine the atmos... | stack_v2_sparse_classes_10k_train_002020 | 6,143 | permissive | [
{
"docstring": "Initialize the ATRAN model for SOFIA. The ATRAN model is used to derive the relative transmission correction factor for a given altitude above the Earth's surface, observing a source at a given elevation. This can be used to determine the atmospheric opacity. Please see :func:`AtranModel.get_rel... | 4 | null | Implement the Python class `AtranModel` described below.
Class description:
Implement the AtranModel class.
Method signatures and docstrings:
- def __init__(self, options): Initialize the ATRAN model for SOFIA. The ATRAN model is used to derive the relative transmission correction factor for a given altitude above th... | Implement the Python class `AtranModel` described below.
Class description:
Implement the AtranModel class.
Method signatures and docstrings:
- def __init__(self, options): Initialize the ATRAN model for SOFIA. The ATRAN model is used to derive the relative transmission correction factor for a given altitude above th... | 493700340cd34d5f319af6f3a562a82135bb30dd | <|skeleton|>
class AtranModel:
def __init__(self, options):
"""Initialize the ATRAN model for SOFIA. The ATRAN model is used to derive the relative transmission correction factor for a given altitude above the Earth's surface, observing a source at a given elevation. This can be used to determine the atmos... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AtranModel:
def __init__(self, options):
"""Initialize the ATRAN model for SOFIA. The ATRAN model is used to derive the relative transmission correction factor for a given altitude above the Earth's surface, observing a source at a given elevation. This can be used to determine the atmospheric opacity... | the_stack_v2_python_sparse | sofia_redux/scan/custom/sofia/integration/models/atran.py | SOFIA-USRA/sofia_redux | train | 12 | |
883249bc722c818afa6852428188d5bd6414be2a | [
"layers_ = list()\nlayers_.append(nn.Conv1d(in_channels=32, out_channels=32, kernel_size=3))\nlayers_.append(nn.Conv1d(in_channels=32, out_channels=32, kernel_size=3))\nlayers_.append(nn.Conv1d(in_channels=32, out_channels=32, kernel_size=3))\nmodes = ['concat', 'sum', 'mean', 'prod', 'max', 'min', 'logsumexp', 'el... | <|body_start_0|>
layers_ = list()
layers_.append(nn.Conv1d(in_channels=32, out_channels=32, kernel_size=3))
layers_.append(nn.Conv1d(in_channels=32, out_channels=32, kernel_size=3))
layers_.append(nn.Conv1d(in_channels=32, out_channels=32, kernel_size=3))
modes = ['concat', 'sum'... | Tests MergeLayer. | MergeLayerTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MergeLayerTest:
"""Tests MergeLayer."""
def test_layer_logic(self):
"""Test the logic of MergeLayer."""
<|body_0|>
def test_empty_merge_layer(self):
"""Test the output of MergeLayer with empty layers."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_002021 | 6,335 | permissive | [
{
"docstring": "Test the logic of MergeLayer.",
"name": "test_layer_logic",
"signature": "def test_layer_logic(self)"
},
{
"docstring": "Test the output of MergeLayer with empty layers.",
"name": "test_empty_merge_layer",
"signature": "def test_empty_merge_layer(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006093 | Implement the Python class `MergeLayerTest` described below.
Class description:
Tests MergeLayer.
Method signatures and docstrings:
- def test_layer_logic(self): Test the logic of MergeLayer.
- def test_empty_merge_layer(self): Test the output of MergeLayer with empty layers. | Implement the Python class `MergeLayerTest` described below.
Class description:
Tests MergeLayer.
Method signatures and docstrings:
- def test_layer_logic(self): Test the logic of MergeLayer.
- def test_empty_merge_layer(self): Test the output of MergeLayer with empty layers.
<|skeleton|>
class MergeLayerTest:
"... | 931ead9222ca90bfc75c3045dc79fb118de340c9 | <|skeleton|>
class MergeLayerTest:
"""Tests MergeLayer."""
def test_layer_logic(self):
"""Test the logic of MergeLayer."""
<|body_0|>
def test_empty_merge_layer(self):
"""Test the output of MergeLayer with empty layers."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MergeLayerTest:
"""Tests MergeLayer."""
def test_layer_logic(self):
"""Test the logic of MergeLayer."""
layers_ = list()
layers_.append(nn.Conv1d(in_channels=32, out_channels=32, kernel_size=3))
layers_.append(nn.Conv1d(in_channels=32, out_channels=32, kernel_size=3))
... | the_stack_v2_python_sparse | texar/torch/core/layers_test.py | panaali/texar-pytorch | train | 1 |
892cbc07a1524f47caaf9eddeb1e1485bb79c915 | [
"data = form.cleaned_data\nself.success_url = reverse('course_result', kwargs={'course': int(data['course'].id)})\nreturn super().form_valid(form)",
"context = super().get_context_data(**kwargs)\ncontext['title_text'] = 'Choose Course Result To Display'\ncontext['detail_text'] = 'Please select the <strong>Course\... | <|body_start_0|>
data = form.cleaned_data
self.success_url = reverse('course_result', kwargs={'course': int(data['course'].id)})
return super().form_valid(form)
<|end_body_0|>
<|body_start_1|>
context = super().get_context_data(**kwargs)
context['title_text'] = 'Choose Course Re... | View for choosing which course result to display. Check that the user's account is still active. Redirects to course_result view on form valid. | ShowCourseResultView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShowCourseResultView:
"""View for choosing which course result to display. Check that the user's account is still active. Redirects to course_result view on form valid."""
def form_valid(self, form):
"""Compute the success URL and call super.form_valid()"""
<|body_0|>
de... | stack_v2_sparse_classes_10k_train_002022 | 29,759 | no_license | [
{
"docstring": "Compute the success URL and call super.form_valid()",
"name": "form_valid",
"signature": "def form_valid(self, form)"
},
{
"docstring": "Return the data used in the templates rendering.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
... | 2 | stack_v2_sparse_classes_30k_train_005645 | Implement the Python class `ShowCourseResultView` described below.
Class description:
View for choosing which course result to display. Check that the user's account is still active. Redirects to course_result view on form valid.
Method signatures and docstrings:
- def form_valid(self, form): Compute the success URL ... | Implement the Python class `ShowCourseResultView` described below.
Class description:
View for choosing which course result to display. Check that the user's account is still active. Redirects to course_result view on form valid.
Method signatures and docstrings:
- def form_valid(self, form): Compute the success URL ... | 06bc577d01d3dbf6c425e03dcb903977a38e377c | <|skeleton|>
class ShowCourseResultView:
"""View for choosing which course result to display. Check that the user's account is still active. Redirects to course_result view on form valid."""
def form_valid(self, form):
"""Compute the success URL and call super.form_valid()"""
<|body_0|>
de... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ShowCourseResultView:
"""View for choosing which course result to display. Check that the user's account is still active. Redirects to course_result view on form valid."""
def form_valid(self, form):
"""Compute the success URL and call super.form_valid()"""
data = form.cleaned_data
... | the_stack_v2_python_sparse | cbt/views.py | Festusali/CBTest | train | 6 |
d6fbedb83b39047f310b7935ea33ca436583fe7c | [
"self.driver.get(self.url_ + '/')\ntitle_present = EC.text_to_be_present_in_element((By.XPATH, '//*[@id=\"main-nav\"]/div/div[1]/a'), 'Data Commons')\nWebDriverWait(self.driver, self.TIMEOUT_SEC).until(title_present)\nhero_msg = self.driver.find_elements_by_class_name('lead')[0]\nself.assertTrue(hero_msg.text.start... | <|body_start_0|>
self.driver.get(self.url_ + '/')
title_present = EC.text_to_be_present_in_element((By.XPATH, '//*[@id="main-nav"]/div/div[1]/a'), 'Data Commons')
WebDriverWait(self.driver, self.TIMEOUT_SEC).until(title_present)
hero_msg = self.driver.find_elements_by_class_name('lead')[... | Tests for Homepage. | TestPlaceLanding | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPlaceLanding:
"""Tests for Homepage."""
def test_homepage_en(self):
"""Test homepage in EN."""
<|body_0|>
def test_homepage_it(self):
"""Test homepage in IT."""
<|body_1|>
def test_hero_all_langs(self):
"""Test hero message translation in... | stack_v2_sparse_classes_10k_train_002023 | 5,887 | permissive | [
{
"docstring": "Test homepage in EN.",
"name": "test_homepage_en",
"signature": "def test_homepage_en(self)"
},
{
"docstring": "Test homepage in IT.",
"name": "test_homepage_it",
"signature": "def test_homepage_it(self)"
},
{
"docstring": "Test hero message translation in *all* l... | 3 | stack_v2_sparse_classes_30k_train_001537 | Implement the Python class `TestPlaceLanding` described below.
Class description:
Tests for Homepage.
Method signatures and docstrings:
- def test_homepage_en(self): Test homepage in EN.
- def test_homepage_it(self): Test homepage in IT.
- def test_hero_all_langs(self): Test hero message translation in *all* language... | Implement the Python class `TestPlaceLanding` described below.
Class description:
Tests for Homepage.
Method signatures and docstrings:
- def test_homepage_en(self): Test homepage in EN.
- def test_homepage_it(self): Test homepage in IT.
- def test_hero_all_langs(self): Test hero message translation in *all* language... | 928625749a74dd9de473170b5683f62a4bbdbd15 | <|skeleton|>
class TestPlaceLanding:
"""Tests for Homepage."""
def test_homepage_en(self):
"""Test homepage in EN."""
<|body_0|>
def test_homepage_it(self):
"""Test homepage in IT."""
<|body_1|>
def test_hero_all_langs(self):
"""Test hero message translation in... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestPlaceLanding:
"""Tests for Homepage."""
def test_homepage_en(self):
"""Test homepage in EN."""
self.driver.get(self.url_ + '/')
title_present = EC.text_to_be_present_in_element((By.XPATH, '//*[@id="main-nav"]/div/div[1]/a'), 'Data Commons')
WebDriverWait(self.driver, s... | the_stack_v2_python_sparse | server/webdriver_tests/homepage_test.py | localsite/website | train | 0 |
b79266990d0c502ca390e30b53bdc5461a69c0cf | [
"self.config_entry = config_entry\nself.options = config_entry.options\nself.host = config_entry.data[CONF_HOST]\nself.key = config_entry.data[CONF_CLIENT_SECRET]",
"errors = {}\nif user_input is not None:\n options_input = {CONF_SOURCES: user_input[CONF_SOURCES]}\n return self.async_create_entry(title='', ... | <|body_start_0|>
self.config_entry = config_entry
self.options = config_entry.options
self.host = config_entry.data[CONF_HOST]
self.key = config_entry.data[CONF_CLIENT_SECRET]
<|end_body_0|>
<|body_start_1|>
errors = {}
if user_input is not None:
options_inpu... | Handle options. | OptionsFlowHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptionsFlowHandler:
"""Handle options."""
def __init__(self, config_entry: ConfigEntry) -> None:
"""Initialize options flow."""
<|body_0|>
async def async_step_init(self, user_input: dict[str, Any] | None=None) -> FlowResult:
"""Manage the options."""
<|b... | stack_v2_sparse_classes_10k_train_002024 | 7,262 | permissive | [
{
"docstring": "Initialize options flow.",
"name": "__init__",
"signature": "def __init__(self, config_entry: ConfigEntry) -> None"
},
{
"docstring": "Manage the options.",
"name": "async_step_init",
"signature": "async def async_step_init(self, user_input: dict[str, Any] | None=None) ->... | 2 | stack_v2_sparse_classes_30k_train_004832 | Implement the Python class `OptionsFlowHandler` described below.
Class description:
Handle options.
Method signatures and docstrings:
- def __init__(self, config_entry: ConfigEntry) -> None: Initialize options flow.
- async def async_step_init(self, user_input: dict[str, Any] | None=None) -> FlowResult: Manage the op... | Implement the Python class `OptionsFlowHandler` described below.
Class description:
Handle options.
Method signatures and docstrings:
- def __init__(self, config_entry: ConfigEntry) -> None: Initialize options flow.
- async def async_step_init(self, user_input: dict[str, Any] | None=None) -> FlowResult: Manage the op... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class OptionsFlowHandler:
"""Handle options."""
def __init__(self, config_entry: ConfigEntry) -> None:
"""Initialize options flow."""
<|body_0|>
async def async_step_init(self, user_input: dict[str, Any] | None=None) -> FlowResult:
"""Manage the options."""
<|b... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OptionsFlowHandler:
"""Handle options."""
def __init__(self, config_entry: ConfigEntry) -> None:
"""Initialize options flow."""
self.config_entry = config_entry
self.options = config_entry.options
self.host = config_entry.data[CONF_HOST]
self.key = config_entry.dat... | the_stack_v2_python_sparse | homeassistant/components/webostv/config_flow.py | home-assistant/core | train | 35,501 |
74bce0dbec2c1a92c40a962f3a099097be735c96 | [
"super().__init__()\nself.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)\nself.dropout = nn.Dropout(dropout)\nself.linear1 = nn.Linear(d_model, dim_feedforward)\nself.linear2 = nn.Linear(dim_feedforward, d_model)\nself.norm1 = nn.LayerNorm(d_model)\nself.norm2 = nn.LayerNorm(d_model)\nself.dropo... | <|body_start_0|>
super().__init__()
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
self.dropout = nn.Dropout(dropout)
self.linear1 = nn.Linear(d_model, dim_feedforward)
self.linear2 = nn.Linear(dim_feedforward, d_model)
self.norm1 = nn.LayerNorm(d... | TransformerEncoderLayer is made up of self-attn and feedforward. This standard encoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need. In Advances in Neu... | TransformerEncoderLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerEncoderLayer:
"""TransformerEncoderLayer is made up of self-attn and feedforward. This standard encoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhin. ... | stack_v2_sparse_classes_10k_train_002025 | 20,460 | permissive | [
{
"docstring": "Initialize a TransformerEncoderLayer. Parameters ---------- d_model : int The number of expected features in the input. n_head : int The number of heads in the multiheadattention models. dim_feedforward : int, optional The dimension of the feedforward network (default=2048). dropout : float, opt... | 2 | stack_v2_sparse_classes_30k_train_002299 | Implement the Python class `TransformerEncoderLayer` described below.
Class description:
TransformerEncoderLayer is made up of self-attn and feedforward. This standard encoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez... | Implement the Python class `TransformerEncoderLayer` described below.
Class description:
TransformerEncoderLayer is made up of self-attn and feedforward. This standard encoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez... | 0dc2f5b2b286694defe8abf450fe5be9ae12c097 | <|skeleton|>
class TransformerEncoderLayer:
"""TransformerEncoderLayer is made up of self-attn and feedforward. This standard encoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhin. ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TransformerEncoderLayer:
"""TransformerEncoderLayer is made up of self-attn and feedforward. This standard encoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhin. 2017. Attenti... | the_stack_v2_python_sparse | flambe/nn/transformer.py | cle-ros/flambe | train | 1 |
b59300fadfcbb5ea24be202f588d2ebdd165a0d1 | [
"super(SentimentRNN, self).__init__()\nself.output_size = output_size\nself.n_layers = n_layers\nself.hidden_dim = hidden_dim\nself.embedding = nn.Embedding(vocab_size, embedding_dim)\nself.lstm = nn.LSTM(embedding_dim, hidden_dim, n_layers, dropout=drop_prob, batch_first=True)\nself.dropout = nn.Dropout(0.3)\nself... | <|body_start_0|>
super(SentimentRNN, self).__init__()
self.output_size = output_size
self.n_layers = n_layers
self.hidden_dim = hidden_dim
self.embedding = nn.Embedding(vocab_size, embedding_dim)
self.lstm = nn.LSTM(embedding_dim, hidden_dim, n_layers, dropout=drop_prob, ... | The RNN models that will be used to perform Sentiment analysis. | SentimentRNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SentimentRNN:
"""The RNN models that will be used to perform Sentiment analysis."""
def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, drop_prob=0.5):
"""Initialize the models by setting up the layers."""
<|body_0|>
def forward(self, x, hidd... | stack_v2_sparse_classes_10k_train_002026 | 3,087 | no_license | [
{
"docstring": "Initialize the models by setting up the layers.",
"name": "__init__",
"signature": "def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, drop_prob=0.5)"
},
{
"docstring": "Perform a forward pass of our models on some input and hidden state.",
"name... | 3 | stack_v2_sparse_classes_30k_test_000170 | Implement the Python class `SentimentRNN` described below.
Class description:
The RNN models that will be used to perform Sentiment analysis.
Method signatures and docstrings:
- def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, drop_prob=0.5): Initialize the models by setting up the lay... | Implement the Python class `SentimentRNN` described below.
Class description:
The RNN models that will be used to perform Sentiment analysis.
Method signatures and docstrings:
- def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, drop_prob=0.5): Initialize the models by setting up the lay... | aa9d9a6e99abc5b2fbee8a724e02a65232d2eb60 | <|skeleton|>
class SentimentRNN:
"""The RNN models that will be used to perform Sentiment analysis."""
def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, drop_prob=0.5):
"""Initialize the models by setting up the layers."""
<|body_0|>
def forward(self, x, hidd... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SentimentRNN:
"""The RNN models that will be used to perform Sentiment analysis."""
def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, drop_prob=0.5):
"""Initialize the models by setting up the layers."""
super(SentimentRNN, self).__init__()
self.outp... | the_stack_v2_python_sparse | sentiment_analysis/model.py | ilyarudyak/tv_script_gen | train | 1 |
44ab080409a0baddac6e71cc84accb4bf5592c7f | [
"if root == None:\n return ''\nres = []\nqueue = deque()\nqueue.append(root)\nres.append(root.val)\nwhile queue:\n node = queue.popleft()\n if node == 'None':\n continue\n if node.left != None:\n queue.append(node.left)\n res.append(node.left.val)\n else:\n res.append('Non... | <|body_start_0|>
if root == None:
return ''
res = []
queue = deque()
queue.append(root)
res.append(root.val)
while queue:
node = queue.popleft()
if node == 'None':
continue
if node.left != None:
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_002027 | 4,106 | 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_001960 | 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:... | 56047a5058c6a20b356ab20e52eacb425ad45762 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if root == None:
return ''
res = []
queue = deque()
queue.append(root)
res.append(root.val)
while queue:
node = queue.popl... | the_stack_v2_python_sparse | Python/BinaryTree/297. Serialize and Deserialize Binary Tree.py | Leahxuliu/Data-Structure-And-Algorithm | train | 2 | |
8f7fe29ee878283624bc643573ac9990209f28f4 | [
"if not features.has('organizations:incidents', organization, actor=request.user):\n raise ResourceDoesNotExist\nprojects = self.get_projects(request, organization)\nalert_rules = AlertRule.objects.fetch_for_organization(organization, projects)\nif not features.has('organizations:performance-view', organization)... | <|body_start_0|>
if not features.has('organizations:incidents', organization, actor=request.user):
raise ResourceDoesNotExist
projects = self.get_projects(request, organization)
alert_rules = AlertRule.objects.fetch_for_organization(organization, projects)
if not features.has... | OrganizationAlertRuleIndexEndpoint | [
"Apache-2.0",
"BUSL-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrganizationAlertRuleIndexEndpoint:
def get(self, request: Request, organization) -> Response:
"""Fetches alert rules for an organization"""
<|body_0|>
def post(self, request: Request, organization) -> Response:
"""Create an alert rule"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_10k_train_002028 | 8,563 | permissive | [
{
"docstring": "Fetches alert rules for an organization",
"name": "get",
"signature": "def get(self, request: Request, organization) -> Response"
},
{
"docstring": "Create an alert rule",
"name": "post",
"signature": "def post(self, request: Request, organization) -> Response"
}
] | 2 | null | Implement the Python class `OrganizationAlertRuleIndexEndpoint` described below.
Class description:
Implement the OrganizationAlertRuleIndexEndpoint class.
Method signatures and docstrings:
- def get(self, request: Request, organization) -> Response: Fetches alert rules for an organization
- def post(self, request: R... | Implement the Python class `OrganizationAlertRuleIndexEndpoint` described below.
Class description:
Implement the OrganizationAlertRuleIndexEndpoint class.
Method signatures and docstrings:
- def get(self, request: Request, organization) -> Response: Fetches alert rules for an organization
- def post(self, request: R... | d9dd4f382f96b5c4576b64cbf015db651556c18b | <|skeleton|>
class OrganizationAlertRuleIndexEndpoint:
def get(self, request: Request, organization) -> Response:
"""Fetches alert rules for an organization"""
<|body_0|>
def post(self, request: Request, organization) -> Response:
"""Create an alert rule"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OrganizationAlertRuleIndexEndpoint:
def get(self, request: Request, organization) -> Response:
"""Fetches alert rules for an organization"""
if not features.has('organizations:incidents', organization, actor=request.user):
raise ResourceDoesNotExist
projects = self.get_proj... | the_stack_v2_python_sparse | src/sentry/incidents/endpoints/organization_alert_rule_index.py | nagyist/sentry | train | 0 | |
24975956c40bd648db2d4635df1a3329c7feff59 | [
"self.file = TFile(fnam)\nif self.file.IsZombie():\n raise ValueError(fnam + ' cannot be opened')\nself.hist = self.file.Get(histnam)\nif self.hist == None:\n raise ValueError('{h} cannot be found in {f}'.format(h=histnam, f=fnam))",
"eta = p4.eta()\npt = p4.pt()\nreturn pt * self.correction_factor(pt, eta)... | <|body_start_0|>
self.file = TFile(fnam)
if self.file.IsZombie():
raise ValueError(fnam + ' cannot be opened')
self.hist = self.file.Get(histnam)
if self.hist == None:
raise ValueError('{h} cannot be found in {f}'.format(h=histnam, f=fnam))
<|end_body_0|>
<|body_... | Generic energy corrector | EnergyCorrector | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnergyCorrector:
"""Generic energy corrector"""
def __init__(self, fnam, histnam='h_cor'):
"""fnam is a root file containing a 1D histogram giving the correction factor as a function of eta."""
<|body_0|>
def correct_p4(self, p4):
"""returns the corrected 4-momen... | stack_v2_sparse_classes_10k_train_002029 | 1,532 | permissive | [
{
"docstring": "fnam is a root file containing a 1D histogram giving the correction factor as a function of eta.",
"name": "__init__",
"signature": "def __init__(self, fnam, histnam='h_cor')"
},
{
"docstring": "returns the corrected 4-momentum. The 4 momentum is expected to behave as the one of ... | 3 | null | Implement the Python class `EnergyCorrector` described below.
Class description:
Generic energy corrector
Method signatures and docstrings:
- def __init__(self, fnam, histnam='h_cor'): fnam is a root file containing a 1D histogram giving the correction factor as a function of eta.
- def correct_p4(self, p4): returns ... | Implement the Python class `EnergyCorrector` described below.
Class description:
Generic energy corrector
Method signatures and docstrings:
- def __init__(self, fnam, histnam='h_cor'): fnam is a root file containing a 1D histogram giving the correction factor as a function of eta.
- def correct_p4(self, p4): returns ... | 19c178740257eb48367778593da55dcad08b7a4f | <|skeleton|>
class EnergyCorrector:
"""Generic energy corrector"""
def __init__(self, fnam, histnam='h_cor'):
"""fnam is a root file containing a 1D histogram giving the correction factor as a function of eta."""
<|body_0|>
def correct_p4(self, p4):
"""returns the corrected 4-momen... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EnergyCorrector:
"""Generic energy corrector"""
def __init__(self, fnam, histnam='h_cor'):
"""fnam is a root file containing a 1D histogram giving the correction factor as a function of eta."""
self.file = TFile(fnam)
if self.file.IsZombie():
raise ValueError(fnam + ' ... | the_stack_v2_python_sparse | PhysicsTools/Heppy/python/physicsutils/EnergyCorrector.py | cms-sw/cmssw | train | 1,006 |
e5f61a9891cdc8fb69ab5624893f5fad019af30d | [
"dic = {}\nfor i, v in enumerate(nums):\n val = target - v\n if val in dic:\n return [dic[val], i]\n else:\n dic[v] = i",
"dic = {}\nfor i, v in enumerate(nums):\n if v not in dic:\n dic[v] = [i]\n else:\n dic[v].append(i)\nfor i, v in enumerate(nums):\n val = target ... | <|body_start_0|>
dic = {}
for i, v in enumerate(nums):
val = target - v
if val in dic:
return [dic[val], i]
else:
dic[v] = i
<|end_body_0|>
<|body_start_1|>
dic = {}
for i, v in enumerate(nums):
if v not in ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum3(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
def twoSum2(self, nums, targe... | stack_v2_sparse_classes_10k_train_002030 | 2,021 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum",
"signature": "def twoSum(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum3",
"signature": "def twoSum3(self, nums, target)"
}... | 4 | stack_v2_sparse_classes_30k_train_003789 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum3(self, nums, target): :type nums: List[int] :type target: int :rtype: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum3(self, nums, target): :type nums: List[int] :type target: int :rtype: List[... | 3ded7bd0f046e8f87c9b9b9bce81e52ab1bdcdac | <|skeleton|>
class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum3(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
def twoSum2(self, nums, targe... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
dic = {}
for i, v in enumerate(nums):
val = target - v
if val in dic:
return [dic[val], i]
else:
dic[v] = i
... | the_stack_v2_python_sparse | leetcode/arrays/two_sum.py | JeanChrist/Algorithms | train | 0 | |
7cbd65d86ce2b9239d3a37c471f56785b075e5be | [
"if id:\n self.id = id\nelse:\n Base.__nb_objects += 1\n self.id = Base.__nb_objects",
"if len(list_dictionaries) is False or list_dictionaries is None:\n return '[]'\nelse:\n json_str = json.dumps(list_dictionaries)\n return json_str",
"if len(json_string) == 0 or json_string is None:\n re... | <|body_start_0|>
if id:
self.id = id
else:
Base.__nb_objects += 1
self.id = Base.__nb_objects
<|end_body_0|>
<|body_start_1|>
if len(list_dictionaries) is False or list_dictionaries is None:
return '[]'
else:
json_str = json.du... | base class for project all other shapes are built on this class return: 0 | Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base:
"""base class for project all other shapes are built on this class return: 0"""
def __init__(self, id=None):
"""count object"""
<|body_0|>
def to_json_string(list_dictionaries):
"""convert to json obj Return: dict"""
<|body_1|>
def from_json_st... | stack_v2_sparse_classes_10k_train_002031 | 2,646 | no_license | [
{
"docstring": "count object",
"name": "__init__",
"signature": "def __init__(self, id=None)"
},
{
"docstring": "convert to json obj Return: dict",
"name": "to_json_string",
"signature": "def to_json_string(list_dictionaries)"
},
{
"docstring": "creates dictionaries",
"name":... | 6 | stack_v2_sparse_classes_30k_train_001109 | Implement the Python class `Base` described below.
Class description:
base class for project all other shapes are built on this class return: 0
Method signatures and docstrings:
- def __init__(self, id=None): count object
- def to_json_string(list_dictionaries): convert to json obj Return: dict
- def from_json_string... | Implement the Python class `Base` described below.
Class description:
base class for project all other shapes are built on this class return: 0
Method signatures and docstrings:
- def __init__(self, id=None): count object
- def to_json_string(list_dictionaries): convert to json obj Return: dict
- def from_json_string... | f47fc1817245fa41e597c9b03707687c78bc80e6 | <|skeleton|>
class Base:
"""base class for project all other shapes are built on this class return: 0"""
def __init__(self, id=None):
"""count object"""
<|body_0|>
def to_json_string(list_dictionaries):
"""convert to json obj Return: dict"""
<|body_1|>
def from_json_st... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Base:
"""base class for project all other shapes are built on this class return: 0"""
def __init__(self, id=None):
"""count object"""
if id:
self.id = id
else:
Base.__nb_objects += 1
self.id = Base.__nb_objects
def to_json_string(list_dicti... | the_stack_v2_python_sparse | 0x0C-python-almost_a_circle/models/base.py | stefansilverio/holbertonschool-higher_level_programming | train | 1 |
20181cde79aed270068f202a65271e2e59b72b92 | [
"for menu in self:\n if menu.item_with_command(cmd):\n return menu\nreturn None",
"for menu in self:\n item = menu.item_with_command(cmd)\n if item:\n return item\nreturn None"
] | <|body_start_0|>
for menu in self:
if menu.item_with_command(cmd):
return menu
return None
<|end_body_0|>
<|body_start_1|>
for menu in self:
item = menu.item_with_command(cmd)
if item:
return item
return None
<|end_body... | A MenuList is a sequence of Menus with methods for finding menus and menu items by command. | MenuList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MenuList:
"""A MenuList is a sequence of Menus with methods for finding menus and menu items by command."""
def menu_with_command(self, cmd):
"""Returns the menu containing the given command, or None if there is no such menu in the list."""
<|body_0|>
def item_with_comma... | stack_v2_sparse_classes_10k_train_002032 | 660 | permissive | [
{
"docstring": "Returns the menu containing the given command, or None if there is no such menu in the list.",
"name": "menu_with_command",
"signature": "def menu_with_command(self, cmd)"
},
{
"docstring": "Returns the menu item having the given command, or None if there is no such item.",
"... | 2 | null | Implement the Python class `MenuList` described below.
Class description:
A MenuList is a sequence of Menus with methods for finding menus and menu items by command.
Method signatures and docstrings:
- def menu_with_command(self, cmd): Returns the menu containing the given command, or None if there is no such menu in... | Implement the Python class `MenuList` described below.
Class description:
A MenuList is a sequence of Menus with methods for finding menus and menu items by command.
Method signatures and docstrings:
- def menu_with_command(self, cmd): Returns the menu containing the given command, or None if there is no such menu in... | 58c6c38ccb8e66acdf98dea6b24bef1d9a03147c | <|skeleton|>
class MenuList:
"""A MenuList is a sequence of Menus with methods for finding menus and menu items by command."""
def menu_with_command(self, cmd):
"""Returns the menu containing the given command, or None if there is no such menu in the list."""
<|body_0|>
def item_with_comma... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MenuList:
"""A MenuList is a sequence of Menus with methods for finding menus and menu items by command."""
def menu_with_command(self, cmd):
"""Returns the menu containing the given command, or None if there is no such menu in the list."""
for menu in self:
if menu.item_with_... | the_stack_v2_python_sparse | GUI/Generic/MenuList.py | coldmax88/PyGUI | train | 0 |
aaa47a1e25dbdad3c170a595e5c34a346d9a0d80 | [
"input_data = {}\ninput_data['name'] = kwargs.get('name', None)\ninput_data['sort_by_date'] = kwargs.get('sort_by_date', None)\ninput_data['podcast_type'] = kwargs.get('podcast_type', None)\ninput_data['duration'] = kwargs.get('duration', None)\ninput_data['published'] = kwargs.get('published', None)\ninput_data['l... | <|body_start_0|>
input_data = {}
input_data['name'] = kwargs.get('name', None)
input_data['sort_by_date'] = kwargs.get('sort_by_date', None)
input_data['podcast_type'] = kwargs.get('podcast_type', None)
input_data['duration'] = kwargs.get('duration', None)
input_data['pub... | Validations for theclient information | PodcastValidations | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PodcastValidations:
"""Validations for theclient information"""
def validate_podcast_data(self, kwargs):
"""Runs all the individual client registration data validations in one function Args: kwargs (dict): request data Returns: input_data (dict): validated data"""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_002033 | 2,198 | permissive | [
{
"docstring": "Runs all the individual client registration data validations in one function Args: kwargs (dict): request data Returns: input_data (dict): validated data",
"name": "validate_podcast_data",
"signature": "def validate_podcast_data(self, kwargs)"
},
{
"docstring": "Runs all the corp... | 2 | stack_v2_sparse_classes_30k_train_006777 | Implement the Python class `PodcastValidations` described below.
Class description:
Validations for theclient information
Method signatures and docstrings:
- def validate_podcast_data(self, kwargs): Runs all the individual client registration data validations in one function Args: kwargs (dict): request data Returns:... | Implement the Python class `PodcastValidations` described below.
Class description:
Validations for theclient information
Method signatures and docstrings:
- def validate_podcast_data(self, kwargs): Runs all the individual client registration data validations in one function Args: kwargs (dict): request data Returns:... | 04ff9ebb5da482e5b2642a89654a5b5f0128eaaa | <|skeleton|>
class PodcastValidations:
"""Validations for theclient information"""
def validate_podcast_data(self, kwargs):
"""Runs all the individual client registration data validations in one function Args: kwargs (dict): request data Returns: input_data (dict): validated data"""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PodcastValidations:
"""Validations for theclient information"""
def validate_podcast_data(self, kwargs):
"""Runs all the individual client registration data validations in one function Args: kwargs (dict): request data Returns: input_data (dict): validated data"""
input_data = {}
... | the_stack_v2_python_sparse | app/api/podcast/validators/validate_input.py | lunyamwis/laylinks-bend | train | 0 |
c72e3503a4db7fc0bf5316211def72edd548268b | [
"UserModel = get_user_model()\nuser = None\nservice = extra_fields.pop('service', 'login')\nencoding = extra_fields.pop('encoding', 'utf-8')\nresetcreds = extra_fields.pop('resetcreds', True)\nlog.debug('request: %s, username: %s, service: %s, encoding: %s, resetcreds: %s, extra_fields: %s', request, username, serv... | <|body_start_0|>
UserModel = get_user_model()
user = None
service = extra_fields.pop('service', 'login')
encoding = extra_fields.pop('encoding', 'utf-8')
resetcreds = extra_fields.pop('resetcreds', True)
log.debug('request: %s, username: %s, service: %s, encoding: %s, res... | An implementation of a PAM backend authentication module. | PAMBackend | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PAMBackend:
"""An implementation of a PAM backend authentication module."""
def authenticate(self, request, username=None, password=None, **extra_fields):
"""Authenticate using PAM then get the account if it exists else create a new account. .. note:: The keyword arguments 'service',... | stack_v2_sparse_classes_10k_train_002034 | 3,567 | permissive | [
{
"docstring": "Authenticate using PAM then get the account if it exists else create a new account. .. note:: The keyword arguments 'service', 'encoding', and 'resetcreds' can also be passed and will be pulled off the 'extra_fields' kwargs. :param username: The users username. This is a manditory field. :type u... | 2 | stack_v2_sparse_classes_30k_train_005691 | Implement the Python class `PAMBackend` described below.
Class description:
An implementation of a PAM backend authentication module.
Method signatures and docstrings:
- def authenticate(self, request, username=None, password=None, **extra_fields): Authenticate using PAM then get the account if it exists else create ... | Implement the Python class `PAMBackend` described below.
Class description:
An implementation of a PAM backend authentication module.
Method signatures and docstrings:
- def authenticate(self, request, username=None, password=None, **extra_fields): Authenticate using PAM then get the account if it exists else create ... | 0839bb50dbaccdd3e41a067175507ee9bc79f754 | <|skeleton|>
class PAMBackend:
"""An implementation of a PAM backend authentication module."""
def authenticate(self, request, username=None, password=None, **extra_fields):
"""Authenticate using PAM then get the account if it exists else create a new account. .. note:: The keyword arguments 'service',... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PAMBackend:
"""An implementation of a PAM backend authentication module."""
def authenticate(self, request, username=None, password=None, **extra_fields):
"""Authenticate using PAM then get the account if it exists else create a new account. .. note:: The keyword arguments 'service', 'encoding', ... | the_stack_v2_python_sparse | django_pam/auth/backends.py | cnobile2012/django-pam | train | 14 |
a478ca2d7f14f8d34aef812294010aa3734eb9cc | [
"ctx = _request_ctx_stack.top\ncurrent_user = ctx.user\nuser = User.get_by_id(current_user.id)\npage = request.args.get('page', 1, type=int)\nreturn response_paginate_accounts(user, page)",
"ctx = _request_ctx_stack.top\ncurrent_user = ctx.user\nrequest_body = request.get_json()\nname = request_body.get('name')\n... | <|body_start_0|>
ctx = _request_ctx_stack.top
current_user = ctx.user
user = User.get_by_id(current_user.id)
page = request.args.get('page', 1, type=int)
return response_paginate_accounts(user, page)
<|end_body_0|>
<|body_start_1|>
ctx = _request_ctx_stack.top
cu... | Accounts | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Accounts:
def get(self):
"""@api {GET} /api/v1/accounts Get all accounts of an user @apiVersion 0.0.1 @apiName GetAllAccounts @apiGroup Accounts @apiDescription Get all accounts of an authenticated user (10 accounts per page) @apiHeader {String} Authorization Users auth token @apiHeader ... | stack_v2_sparse_classes_10k_train_002035 | 6,784 | no_license | [
{
"docstring": "@api {GET} /api/v1/accounts Get all accounts of an user @apiVersion 0.0.1 @apiName GetAllAccounts @apiGroup Accounts @apiDescription Get all accounts of an authenticated user (10 accounts per page) @apiHeader {String} Authorization Users auth token @apiHeader {String} Content-Type=\"application/... | 2 | stack_v2_sparse_classes_30k_train_006805 | Implement the Python class `Accounts` described below.
Class description:
Implement the Accounts class.
Method signatures and docstrings:
- def get(self): @api {GET} /api/v1/accounts Get all accounts of an user @apiVersion 0.0.1 @apiName GetAllAccounts @apiGroup Accounts @apiDescription Get all accounts of an authent... | Implement the Python class `Accounts` described below.
Class description:
Implement the Accounts class.
Method signatures and docstrings:
- def get(self): @api {GET} /api/v1/accounts Get all accounts of an user @apiVersion 0.0.1 @apiName GetAllAccounts @apiGroup Accounts @apiDescription Get all accounts of an authent... | 8640cde9e6c7a8ea7f581dee29ed7fa440a5034a | <|skeleton|>
class Accounts:
def get(self):
"""@api {GET} /api/v1/accounts Get all accounts of an user @apiVersion 0.0.1 @apiName GetAllAccounts @apiGroup Accounts @apiDescription Get all accounts of an authenticated user (10 accounts per page) @apiHeader {String} Authorization Users auth token @apiHeader ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Accounts:
def get(self):
"""@api {GET} /api/v1/accounts Get all accounts of an user @apiVersion 0.0.1 @apiName GetAllAccounts @apiGroup Accounts @apiDescription Get all accounts of an authenticated user (10 accounts per page) @apiHeader {String} Authorization Users auth token @apiHeader {String} Conte... | the_stack_v2_python_sparse | backend/app/api/v1/account/accounts.py | zinzinhust96/sea_7 | train | 0 | |
5159c412f7c30d9092558bdee9c06cbfcf490bf0 | [
"if os.path.exists(fname):\n self.file = open(fname, 'rb')\n self.magic_t, self.elsize, _, self.dim, _ = _read_header(self.file, False)\n self.gz = False\nelse:\n import gzip\n self.file = gzip.open(fname + '.gz', 'rb')\n self.magic_t, self.elsize, _, self.dim, _ = _read_header(self.file, False, T... | <|body_start_0|>
if os.path.exists(fname):
self.file = open(fname, 'rb')
self.magic_t, self.elsize, _, self.dim, _ = _read_header(self.file, False)
self.gz = False
else:
import gzip
self.file = gzip.open(fname + '.gz', 'rb')
self.ma... | FTFile | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FTFile:
def __init__(self, fname, scale=1, dtype=None):
"""Tests: >>> f = FTFile('/data/lisa/data/nist/by_class/digits/digits_test_labels.ft')"""
<|body_0|>
def skip(self, num):
"""Skips `num` items in the file. If `num` is negative, skips size-num. Tests: >>> f = FT... | stack_v2_sparse_classes_10k_train_002036 | 9,679 | permissive | [
{
"docstring": "Tests: >>> f = FTFile('/data/lisa/data/nist/by_class/digits/digits_test_labels.ft')",
"name": "__init__",
"signature": "def __init__(self, fname, scale=1, dtype=None)"
},
{
"docstring": "Skips `num` items in the file. If `num` is negative, skips size-num. Tests: >>> f = FTFile('/... | 3 | stack_v2_sparse_classes_30k_val_000247 | Implement the Python class `FTFile` described below.
Class description:
Implement the FTFile class.
Method signatures and docstrings:
- def __init__(self, fname, scale=1, dtype=None): Tests: >>> f = FTFile('/data/lisa/data/nist/by_class/digits/digits_test_labels.ft')
- def skip(self, num): Skips `num` items in the fi... | Implement the Python class `FTFile` described below.
Class description:
Implement the FTFile class.
Method signatures and docstrings:
- def __init__(self, fname, scale=1, dtype=None): Tests: >>> f = FTFile('/data/lisa/data/nist/by_class/digits/digits_test_labels.ft')
- def skip(self, num): Skips `num` items in the fi... | 7881458caaf2f5ab82b130ee50cb933cf12f6de7 | <|skeleton|>
class FTFile:
def __init__(self, fname, scale=1, dtype=None):
"""Tests: >>> f = FTFile('/data/lisa/data/nist/by_class/digits/digits_test_labels.ft')"""
<|body_0|>
def skip(self, num):
"""Skips `num` items in the file. If `num` is negative, skips size-num. Tests: >>> f = FT... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FTFile:
def __init__(self, fname, scale=1, dtype=None):
"""Tests: >>> f = FTFile('/data/lisa/data/nist/by_class/digits/digits_test_labels.ft')"""
if os.path.exists(fname):
self.file = open(fname, 'rb')
self.magic_t, self.elsize, _, self.dim, _ = _read_header(self.file, ... | the_stack_v2_python_sparse | datasets/ift6266/datasets/ftfile.py | sauravbiswasiupr/image_transformations | train | 0 | |
0cf6592c04a57755ddeb987922308f852cc5f643 | [
"if not nums:\n return 0\nf = 1\nd = 1\nfor i in range(1, len(nums)):\n if nums[i] > nums[i - 1]:\n f = d + 1\n elif nums[i] < nums[i - 1]:\n d = f + 1\nreturn max(f, d)",
"if len(nums) < 2:\n return len(nums)\ndp = [None for _ in range(len(nums))]\ndp[0] = [1, None]\nfor i in range(1, l... | <|body_start_0|>
if not nums:
return 0
f = 1
d = 1
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]:
f = d + 1
elif nums[i] < nums[i - 1]:
d = f + 1
return max(f, d)
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wiggleMaxLength(self, nums):
"""nearly the same as linear house rob :type nums: List[int] :rtype: int"""
<|body_0|>
def wiggleMaxLength2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_002037 | 1,231 | no_license | [
{
"docstring": "nearly the same as linear house rob :type nums: List[int] :rtype: int",
"name": "wiggleMaxLength",
"signature": "def wiggleMaxLength(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "wiggleMaxLength2",
"signature": "def wiggleMaxLength2(self, nu... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wiggleMaxLength(self, nums): nearly the same as linear house rob :type nums: List[int] :rtype: int
- def wiggleMaxLength2(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 wiggleMaxLength(self, nums): nearly the same as linear house rob :type nums: List[int] :rtype: int
- def wiggleMaxLength2(self, nums): :type nums: List[int] :rtype: int
<|sk... | e16702d2b3ec4e5054baad56f4320bc3b31676ad | <|skeleton|>
class Solution:
def wiggleMaxLength(self, nums):
"""nearly the same as linear house rob :type nums: List[int] :rtype: int"""
<|body_0|>
def wiggleMaxLength2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def wiggleMaxLength(self, nums):
"""nearly the same as linear house rob :type nums: List[int] :rtype: int"""
if not nums:
return 0
f = 1
d = 1
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]:
f = d + 1
... | the_stack_v2_python_sparse | leetcode/medium/wiggle_sequence.py | SuperMartinYang/learning_algorithm | train | 0 | |
45dc204e8719c43b7b8b46b64f0c8045d41b1b27 | [
"self.origin = asarray(origin)\nself.vectors = asarray(vectors)\nif not colors:\n colors = ('r', 'g', 'b')\nself.colors = colors",
"assert_axes_dimension(axes, 3)\no = self.origin\nxyz = self.vectors\naxes.plot([o[0, 0], o[0, 0] + xyz[0, 0]], [o[0, 1], o[0, 1] + xyz[0, 1]], [o[0, 2], o[0, 2] + xyz[0, 2]], '{0}... | <|body_start_0|>
self.origin = asarray(origin)
self.vectors = asarray(vectors)
if not colors:
colors = ('r', 'g', 'b')
self.colors = colors
<|end_body_0|>
<|body_start_1|>
assert_axes_dimension(axes, 3)
o = self.origin
xyz = self.vectors
axes.... | Definition of a 3D Axes object. Parameters ---------- origin : tuple or list X, Y and Z coordinates for the origin. vectors : list The X, Y and Z axes. Attributes ---------- origin : tuple or list X, Y and Z coordinates for the origin. vectors : list The X, Y and Z axes. | Axes3D | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Axes3D:
"""Definition of a 3D Axes object. Parameters ---------- origin : tuple or list X, Y and Z coordinates for the origin. vectors : list The X, Y and Z axes. Attributes ---------- origin : tuple or list X, Y and Z coordinates for the origin. vectors : list The X, Y and Z axes."""
def __... | stack_v2_sparse_classes_10k_train_002038 | 5,340 | permissive | [
{
"docstring": "Initializes the Axes3D object",
"name": "__init__",
"signature": "def __init__(self, origin, vectors, colors=None)"
},
{
"docstring": "Plots the axes object Parameters ---------- axes : object The matplotlib axes object.",
"name": "plot",
"signature": "def plot(self, axes... | 2 | null | Implement the Python class `Axes3D` described below.
Class description:
Definition of a 3D Axes object. Parameters ---------- origin : tuple or list X, Y and Z coordinates for the origin. vectors : list The X, Y and Z axes. Attributes ---------- origin : tuple or list X, Y and Z coordinates for the origin. vectors : l... | Implement the Python class `Axes3D` described below.
Class description:
Definition of a 3D Axes object. Parameters ---------- origin : tuple or list X, Y and Z coordinates for the origin. vectors : list The X, Y and Z axes. Attributes ---------- origin : tuple or list X, Y and Z coordinates for the origin. vectors : l... | 486e2e9332553240bcbd80e100d26bff58071709 | <|skeleton|>
class Axes3D:
"""Definition of a 3D Axes object. Parameters ---------- origin : tuple or list X, Y and Z coordinates for the origin. vectors : list The X, Y and Z axes. Attributes ---------- origin : tuple or list X, Y and Z coordinates for the origin. vectors : list The X, Y and Z axes."""
def __... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Axes3D:
"""Definition of a 3D Axes object. Parameters ---------- origin : tuple or list X, Y and Z coordinates for the origin. vectors : list The X, Y and Z axes. Attributes ---------- origin : tuple or list X, Y and Z coordinates for the origin. vectors : list The X, Y and Z axes."""
def __init__(self, ... | the_stack_v2_python_sparse | src/compas_plotters/core/helpers.py | compas-dev/compas | train | 286 |
21a802b48685982220130e6ed33d38d531a9b33e | [
"if not self.VTKObject.GetCellTypesArray():\n return None\nreturn vtkDataArrayToVTKArray(self.VTKObject.GetCellTypesArray(), self)",
"if not self.VTKObject.GetCellLocationsArray():\n return None\nreturn vtkDataArrayToVTKArray(self.VTKObject.GetCellLocationsArray(), self)",
"if not self.VTKObject.GetCells(... | <|body_start_0|>
if not self.VTKObject.GetCellTypesArray():
return None
return vtkDataArrayToVTKArray(self.VTKObject.GetCellTypesArray(), self)
<|end_body_0|>
<|body_start_1|>
if not self.VTKObject.GetCellLocationsArray():
return None
return vtkDataArrayToVTKArra... | This is a python friendly wrapper of a vtkUnstructuredGrid that defines a few useful properties. | UnstructuredGrid | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnstructuredGrid:
"""This is a python friendly wrapper of a vtkUnstructuredGrid that defines a few useful properties."""
def GetCellTypes(self):
"""Returns the cell types as a VTKArray instance."""
<|body_0|>
def GetCellLocations(self):
"""Returns the cell locati... | stack_v2_sparse_classes_10k_train_002039 | 47,641 | permissive | [
{
"docstring": "Returns the cell types as a VTKArray instance.",
"name": "GetCellTypes",
"signature": "def GetCellTypes(self)"
},
{
"docstring": "Returns the cell locations as a VTKArray instance.",
"name": "GetCellLocations",
"signature": "def GetCellLocations(self)"
},
{
"docst... | 4 | stack_v2_sparse_classes_30k_train_003440 | Implement the Python class `UnstructuredGrid` described below.
Class description:
This is a python friendly wrapper of a vtkUnstructuredGrid that defines a few useful properties.
Method signatures and docstrings:
- def GetCellTypes(self): Returns the cell types as a VTKArray instance.
- def GetCellLocations(self): Re... | Implement the Python class `UnstructuredGrid` described below.
Class description:
This is a python friendly wrapper of a vtkUnstructuredGrid that defines a few useful properties.
Method signatures and docstrings:
- def GetCellTypes(self): Returns the cell types as a VTKArray instance.
- def GetCellLocations(self): Re... | dd4138e17f1ed5dfe6ef1eab0ff6643fdc07e271 | <|skeleton|>
class UnstructuredGrid:
"""This is a python friendly wrapper of a vtkUnstructuredGrid that defines a few useful properties."""
def GetCellTypes(self):
"""Returns the cell types as a VTKArray instance."""
<|body_0|>
def GetCellLocations(self):
"""Returns the cell locati... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UnstructuredGrid:
"""This is a python friendly wrapper of a vtkUnstructuredGrid that defines a few useful properties."""
def GetCellTypes(self):
"""Returns the cell types as a VTKArray instance."""
if not self.VTKObject.GetCellTypesArray():
return None
return vtkDataAr... | the_stack_v2_python_sparse | Wrapping/Python/vtkmodules/numpy_interface/dataset_adapter.py | Kitware/VTK | train | 2,253 |
e8cf816e779fa625fa3f530a75311cfbdfcf19ad | [
"if not nums:\n return 0\nfor i in range(1, len(nums) - 1):\n if nums[i] < nums[i - 1] and nums[i] < nums[i + 1]:\n return nums[i]",
"if not nums:\n return None\ni, j = (0, len(nums) - 1)\nwhile i < j:\n m = i + int((j - i) / 2)\n if nums[m] > nums[j]:\n i = m + 1\n elif nums[m] < ... | <|body_start_0|>
if not nums:
return 0
for i in range(1, len(nums) - 1):
if nums[i] < nums[i - 1] and nums[i] < nums[i + 1]:
return nums[i]
<|end_body_0|>
<|body_start_1|>
if not nums:
return None
i, j = (0, len(nums) - 1)
whil... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def MinNumberInRotateArray(self, nums):
"""查找旋转数组中最小的元素 :param nums: :return: 时间复杂度分析:时间复杂度O(N)"""
<|body_0|>
def MinNumberInRotateArrayPlus(self, nums):
"""查找旋转数组中最小的元素 :param nums: :return: 时间复杂度分析:时间复杂度O(logN)"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_10k_train_002040 | 3,014 | no_license | [
{
"docstring": "查找旋转数组中最小的元素 :param nums: :return: 时间复杂度分析:时间复杂度O(N)",
"name": "MinNumberInRotateArray",
"signature": "def MinNumberInRotateArray(self, nums)"
},
{
"docstring": "查找旋转数组中最小的元素 :param nums: :return: 时间复杂度分析:时间复杂度O(logN)",
"name": "MinNumberInRotateArrayPlus",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_004994 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def MinNumberInRotateArray(self, nums): 查找旋转数组中最小的元素 :param nums: :return: 时间复杂度分析:时间复杂度O(N)
- def MinNumberInRotateArrayPlus(self, nums): 查找旋转数组中最小的元素 :param nums: :return: 时间复杂... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def MinNumberInRotateArray(self, nums): 查找旋转数组中最小的元素 :param nums: :return: 时间复杂度分析:时间复杂度O(N)
- def MinNumberInRotateArrayPlus(self, nums): 查找旋转数组中最小的元素 :param nums: :return: 时间复杂... | 32941ee052d0985a9569441d314378700ff4d225 | <|skeleton|>
class Solution:
def MinNumberInRotateArray(self, nums):
"""查找旋转数组中最小的元素 :param nums: :return: 时间复杂度分析:时间复杂度O(N)"""
<|body_0|>
def MinNumberInRotateArrayPlus(self, nums):
"""查找旋转数组中最小的元素 :param nums: :return: 时间复杂度分析:时间复杂度O(logN)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def MinNumberInRotateArray(self, nums):
"""查找旋转数组中最小的元素 :param nums: :return: 时间复杂度分析:时间复杂度O(N)"""
if not nums:
return 0
for i in range(1, len(nums) - 1):
if nums[i] < nums[i - 1] and nums[i] < nums[i + 1]:
return nums[i]
def MinNu... | the_stack_v2_python_sparse | cecilia-python/剑指offer/chapter-2/MinNumberInRotateArray.py | Cecilia520/algorithmic-learning-leetcode | train | 7 | |
e3f1e91a022165a526299378047d7249c65a6eaa | [
"username = request.GET.get('username', None)\nif username is not None:\n pm = get_object_or_404(PM, user__username=username)\n serializer = CMSerializer(pm)\n return JsonResponse({'pms': [serializer.data]}, safe=False)\nelse:\n pms = PM.objects.all()\n serializer = PMSerializer(pms, many=True)\n ... | <|body_start_0|>
username = request.GET.get('username', None)
if username is not None:
pm = get_object_or_404(PM, user__username=username)
serializer = CMSerializer(pm)
return JsonResponse({'pms': [serializer.data]}, safe=False)
else:
pms = PM.obje... | 专业负责人view | PMs | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PMs:
"""专业负责人view"""
def get(self, request):
"""查询专业负责人"""
<|body_0|>
def post(self, request):
"""增加专业负责人"""
<|body_1|>
def delete(self, request):
"""删除导员"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
username = request.GE... | stack_v2_sparse_classes_10k_train_002041 | 16,053 | permissive | [
{
"docstring": "查询专业负责人",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "增加专业负责人",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "删除导员",
"name": "delete",
"signature": "def delete(self, request)"
}
] | 3 | stack_v2_sparse_classes_30k_train_005259 | Implement the Python class `PMs` described below.
Class description:
专业负责人view
Method signatures and docstrings:
- def get(self, request): 查询专业负责人
- def post(self, request): 增加专业负责人
- def delete(self, request): 删除导员 | Implement the Python class `PMs` described below.
Class description:
专业负责人view
Method signatures and docstrings:
- def get(self, request): 查询专业负责人
- def post(self, request): 增加专业负责人
- def delete(self, request): 删除导员
<|skeleton|>
class PMs:
"""专业负责人view"""
def get(self, request):
"""查询专业负责人"""
... | 7aaa1be773718de1beb3ce0080edca7c4114b7ad | <|skeleton|>
class PMs:
"""专业负责人view"""
def get(self, request):
"""查询专业负责人"""
<|body_0|>
def post(self, request):
"""增加专业负责人"""
<|body_1|>
def delete(self, request):
"""删除导员"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PMs:
"""专业负责人view"""
def get(self, request):
"""查询专业负责人"""
username = request.GET.get('username', None)
if username is not None:
pm = get_object_or_404(PM, user__username=username)
serializer = CMSerializer(pm)
return JsonResponse({'pms': [seria... | the_stack_v2_python_sparse | user/views.py | MIXISAMA/MIS-backend | train | 0 |
2806af3588bd07bcc8e715c777b099fdff581a09 | [
"n_bin_rev = n_bin[::-1]\npower_of_2 = 0\ndecimal = 0\nfor i in n_bin_rev:\n decimal += int(i) * 2 ** power_of_2\n power_of_2 += 1\nreturn decimal",
"binary = ''\nwhile n_dec != 0:\n remainder = str(n_dec % 2)\n binary = binary + remainder\n n_dec = n_dec // 2\nreturn binary[::-1]",
"a_dec = self... | <|body_start_0|>
n_bin_rev = n_bin[::-1]
power_of_2 = 0
decimal = 0
for i in n_bin_rev:
decimal += int(i) * 2 ** power_of_2
power_of_2 += 1
return decimal
<|end_body_0|>
<|body_start_1|>
binary = ''
while n_dec != 0:
remainder ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def bin_to_dec(self, n_bin):
""":param n_bin: binary string :return: int decimal equivalent logic: say n_bin = 100, 1*2^2 + 0*2^1+ 0*2^0. Initially it is reversed bcoz we start conversion from right."""
<|body_0|>
def dec_to_bin(self, n_dec):
""":param n_de... | stack_v2_sparse_classes_10k_train_002042 | 1,647 | no_license | [
{
"docstring": ":param n_bin: binary string :return: int decimal equivalent logic: say n_bin = 100, 1*2^2 + 0*2^1+ 0*2^0. Initially it is reversed bcoz we start conversion from right.",
"name": "bin_to_dec",
"signature": "def bin_to_dec(self, n_bin)"
},
{
"docstring": ":param n_dec: string :retu... | 3 | stack_v2_sparse_classes_30k_train_007293 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def bin_to_dec(self, n_bin): :param n_bin: binary string :return: int decimal equivalent logic: say n_bin = 100, 1*2^2 + 0*2^1+ 0*2^0. Initially it is reversed bcoz we start conv... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def bin_to_dec(self, n_bin): :param n_bin: binary string :return: int decimal equivalent logic: say n_bin = 100, 1*2^2 + 0*2^1+ 0*2^0. Initially it is reversed bcoz we start conv... | c9c0d4dbeb583eaf8ec7899310bb4665ec5035d0 | <|skeleton|>
class Solution:
def bin_to_dec(self, n_bin):
""":param n_bin: binary string :return: int decimal equivalent logic: say n_bin = 100, 1*2^2 + 0*2^1+ 0*2^0. Initially it is reversed bcoz we start conversion from right."""
<|body_0|>
def dec_to_bin(self, n_dec):
""":param n_de... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def bin_to_dec(self, n_bin):
""":param n_bin: binary string :return: int decimal equivalent logic: say n_bin = 100, 1*2^2 + 0*2^1+ 0*2^0. Initially it is reversed bcoz we start conversion from right."""
n_bin_rev = n_bin[::-1]
power_of_2 = 0
decimal = 0
for i ... | the_stack_v2_python_sparse | Leetcode--Python-master/Directory1/BinarySum.py | sanaydevi/leetCodeSolutions | train | 0 | |
d84bd57e7fa0398b7d9e5527445e0f30c6951980 | [
"if item in self:\n return super(_LoadedConfigs, self).__getitem__(item)\naddon = item.replace('_config', '')\nif addon in ValidAddons.all:\n import_path = 'gungame51.scripts.%s.%s.%s' % (ValidAddons.get_addon_type(addon), addon, item)\nelif _base_configs.joinpath(item + '.py').isfile():\n import_path = 'g... | <|body_start_0|>
if item in self:
return super(_LoadedConfigs, self).__getitem__(item)
addon = item.replace('_config', '')
if addon in ValidAddons.all:
import_path = 'gungame51.scripts.%s.%s.%s' % (ValidAddons.get_addon_type(addon), addon, item)
elif _base_configs... | Class used to store loaded config files | _LoadedConfigs | [
"Artistic-1.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _LoadedConfigs:
"""Class used to store loaded config files"""
def __getitem__(self, item):
"""Verify that the given item is a config file instance and store it"""
<|body_0|>
def clear(self):
"""Unloads all configs within the dicionary"""
<|body_1|>
<|end... | stack_v2_sparse_classes_10k_train_002043 | 2,849 | permissive | [
{
"docstring": "Verify that the given item is a config file instance and store it",
"name": "__getitem__",
"signature": "def __getitem__(self, item)"
},
{
"docstring": "Unloads all configs within the dicionary",
"name": "clear",
"signature": "def clear(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005459 | Implement the Python class `_LoadedConfigs` described below.
Class description:
Class used to store loaded config files
Method signatures and docstrings:
- def __getitem__(self, item): Verify that the given item is a config file instance and store it
- def clear(self): Unloads all configs within the dicionary | Implement the Python class `_LoadedConfigs` described below.
Class description:
Class used to store loaded config files
Method signatures and docstrings:
- def __getitem__(self, item): Verify that the given item is a config file instance and store it
- def clear(self): Unloads all configs within the dicionary
<|skel... | ebf4624626266f552189a32612b8d09cd5b4c5a3 | <|skeleton|>
class _LoadedConfigs:
"""Class used to store loaded config files"""
def __getitem__(self, item):
"""Verify that the given item is a config file instance and store it"""
<|body_0|>
def clear(self):
"""Unloads all configs within the dicionary"""
<|body_1|>
<|end... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _LoadedConfigs:
"""Class used to store loaded config files"""
def __getitem__(self, item):
"""Verify that the given item is a config file instance and store it"""
if item in self:
return super(_LoadedConfigs, self).__getitem__(item)
addon = item.replace('_config', '')
... | the_stack_v2_python_sparse | cstrike/addons/eventscripts/gungame51/core/cfg/loaded.py | GunGame-Dev-Team/GunGame51 | train | 0 |
7f889974320321eef23830119ebf3bfde0256ec3 | [
"if parent and parent.is_audio_clip and parent.warping:\n self.set_range((0, len(parent.available_warp_modes) - 1))\n super(WarpProperty, self).set_parent(parent)\nelse:\n super(WarpProperty, self).set_parent(None)\nreturn",
"if self._parent.warping and current_value != new_value:\n modes = list(self.... | <|body_start_0|>
if parent and parent.is_audio_clip and parent.warping:
self.set_range((0, len(parent.available_warp_modes) - 1))
super(WarpProperty, self).set_parent(parent)
else:
super(WarpProperty, self).set_parent(None)
return
<|end_body_0|>
<|body_start_... | WarpProperty specializes PropertyControl to control a clip's warp mode. | WarpProperty | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WarpProperty:
"""WarpProperty specializes PropertyControl to control a clip's warp mode."""
def set_parent(self, parent):
"""Extends standard to only set parent if it's an audio clip and to set the property's range based on the available warp modes."""
<|body_0|>
def set... | stack_v2_sparse_classes_10k_train_002044 | 13,552 | no_license | [
{
"docstring": "Extends standard to only set parent if it's an audio clip and to set the property's range based on the available warp modes.",
"name": "set_parent",
"signature": "def set_parent(self, parent)"
},
{
"docstring": "Overrides standard to set the warp mode based on the available warp ... | 4 | stack_v2_sparse_classes_30k_train_001630 | Implement the Python class `WarpProperty` described below.
Class description:
WarpProperty specializes PropertyControl to control a clip's warp mode.
Method signatures and docstrings:
- def set_parent(self, parent): Extends standard to only set parent if it's an audio clip and to set the property's range based on the... | Implement the Python class `WarpProperty` described below.
Class description:
WarpProperty specializes PropertyControl to control a clip's warp mode.
Method signatures and docstrings:
- def set_parent(self, parent): Extends standard to only set parent if it's an audio clip and to set the property's range based on the... | e3ec6846470eed7da8a4d4f78562ed49dc00727b | <|skeleton|>
class WarpProperty:
"""WarpProperty specializes PropertyControl to control a clip's warp mode."""
def set_parent(self, parent):
"""Extends standard to only set parent if it's an audio clip and to set the property's range based on the available warp modes."""
<|body_0|>
def set... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WarpProperty:
"""WarpProperty specializes PropertyControl to control a clip's warp mode."""
def set_parent(self, parent):
"""Extends standard to only set parent if it's an audio clip and to set the property's range based on the available warp modes."""
if parent and parent.is_audio_clip a... | the_stack_v2_python_sparse | Live 10.1.18/_NKFW2/ClipPropertiesComponent.py | notelba/midi-remote-scripts | train | 0 |
8d429ae268f5979724de54ebe0075e38f857c830 | [
"nvars = 3\nsuper().__init__(init=(nvars, None, np.dtype('float64')))\nself._makeAttributeAndRegister('nvars', localVars=locals(), readOnly=True)\nself._makeAttributeAndRegister('sigma', 'rho', 'beta', 'newton_tol', 'newton_maxiter', localVars=locals(), readOnly=False)\nself.work_counters['newton'] = WorkCounter()\... | <|body_start_0|>
nvars = 3
super().__init__(init=(nvars, None, np.dtype('float64')))
self._makeAttributeAndRegister('nvars', localVars=locals(), readOnly=True)
self._makeAttributeAndRegister('sigma', 'rho', 'beta', 'newton_tol', 'newton_maxiter', localVars=locals(), readOnly=False)
... | Simple script to run a Lorenz attractor problem. The Lorenz attractor is a system of three ordinary differential equations (ODEs) that exhibits some chaotic behaviour. It is well known for the "Butterfly Effect", because the solution looks like a butterfly (solve to :math:`T_{end} = 100` or so to see this with these in... | LorenzAttractor | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LorenzAttractor:
"""Simple script to run a Lorenz attractor problem. The Lorenz attractor is a system of three ordinary differential equations (ODEs) that exhibits some chaotic behaviour. It is well known for the "Butterfly Effect", because the solution looks like a butterfly (solve to :math:`T_{... | stack_v2_sparse_classes_10k_train_002045 | 7,847 | permissive | [
{
"docstring": "Initialization routine",
"name": "__init__",
"signature": "def __init__(self, sigma=10.0, rho=28.0, beta=8.0 / 3.0, newton_tol=1e-09, newton_maxiter=99)"
},
{
"docstring": "Routine to evaluate the right-hand side of the problem. Parameters ---------- u : dtype_u Current values of... | 4 | null | Implement the Python class `LorenzAttractor` described below.
Class description:
Simple script to run a Lorenz attractor problem. The Lorenz attractor is a system of three ordinary differential equations (ODEs) that exhibits some chaotic behaviour. It is well known for the "Butterfly Effect", because the solution look... | Implement the Python class `LorenzAttractor` described below.
Class description:
Simple script to run a Lorenz attractor problem. The Lorenz attractor is a system of three ordinary differential equations (ODEs) that exhibits some chaotic behaviour. It is well known for the "Butterfly Effect", because the solution look... | 1a51834bedffd4472e344bed28f4d766614b1537 | <|skeleton|>
class LorenzAttractor:
"""Simple script to run a Lorenz attractor problem. The Lorenz attractor is a system of three ordinary differential equations (ODEs) that exhibits some chaotic behaviour. It is well known for the "Butterfly Effect", because the solution looks like a butterfly (solve to :math:`T_{... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LorenzAttractor:
"""Simple script to run a Lorenz attractor problem. The Lorenz attractor is a system of three ordinary differential equations (ODEs) that exhibits some chaotic behaviour. It is well known for the "Butterfly Effect", because the solution looks like a butterfly (solve to :math:`T_{end} = 100` o... | the_stack_v2_python_sparse | pySDC/implementations/problem_classes/Lorenz.py | Parallel-in-Time/pySDC | train | 30 |
183370fde921c6500c31865d9ff4823138b107f8 | [
"args = dict(is_add=True, locator_set_name=name, locator_num=0, locators=[])\ncmd = u'lisp_add_del_locator_set'\nerr_msg = f\"Failed to add locator set on host {node[u'host']}\"\nwith PapiSocketExecutor(node) as papi_exec:\n papi_exec.add(cmd, **args).get_reply(err_msg)",
"args = dict(is_add=False, locator_set... | <|body_start_0|>
args = dict(is_add=True, locator_set_name=name, locator_num=0, locators=[])
cmd = u'lisp_add_del_locator_set'
err_msg = f"Failed to add locator set on host {node[u'host']}"
with PapiSocketExecutor(node) as papi_exec:
papi_exec.add(cmd, **args).get_reply(err_m... | Class for Lisp Locator Set API. | LispLocatorSet | [
"GPL-1.0-or-later",
"CC-BY-4.0",
"Apache-2.0",
"LicenseRef-scancode-dco-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LispLocatorSet:
"""Class for Lisp Locator Set API."""
def vpp_add_lisp_locator_set(node, name):
"""Add lisp locator_set on VPP. :param node: VPP node. :param name: VPP locator name. :type node: dict :type name: str"""
<|body_0|>
def vpp_del_lisp_locator_set(node, name):
... | stack_v2_sparse_classes_10k_train_002046 | 14,690 | permissive | [
{
"docstring": "Add lisp locator_set on VPP. :param node: VPP node. :param name: VPP locator name. :type node: dict :type name: str",
"name": "vpp_add_lisp_locator_set",
"signature": "def vpp_add_lisp_locator_set(node, name)"
},
{
"docstring": "Del lisp locator_set on VPP. :param node: VPP node.... | 2 | stack_v2_sparse_classes_30k_train_001171 | Implement the Python class `LispLocatorSet` described below.
Class description:
Class for Lisp Locator Set API.
Method signatures and docstrings:
- def vpp_add_lisp_locator_set(node, name): Add lisp locator_set on VPP. :param node: VPP node. :param name: VPP locator name. :type node: dict :type name: str
- def vpp_de... | Implement the Python class `LispLocatorSet` described below.
Class description:
Class for Lisp Locator Set API.
Method signatures and docstrings:
- def vpp_add_lisp_locator_set(node, name): Add lisp locator_set on VPP. :param node: VPP node. :param name: VPP locator name. :type node: dict :type name: str
- def vpp_de... | 947057d7310cd1602119258c6b82fbb25fe1b79d | <|skeleton|>
class LispLocatorSet:
"""Class for Lisp Locator Set API."""
def vpp_add_lisp_locator_set(node, name):
"""Add lisp locator_set on VPP. :param node: VPP node. :param name: VPP locator name. :type node: dict :type name: str"""
<|body_0|>
def vpp_del_lisp_locator_set(node, name):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LispLocatorSet:
"""Class for Lisp Locator Set API."""
def vpp_add_lisp_locator_set(node, name):
"""Add lisp locator_set on VPP. :param node: VPP node. :param name: VPP locator name. :type node: dict :type name: str"""
args = dict(is_add=True, locator_set_name=name, locator_num=0, locators... | the_stack_v2_python_sparse | resources/libraries/python/LispSetup.py | FDio/csit | train | 28 |
68f32e911a2f0093db3d2f25e619f474f7e7c4e2 | [
"self.reqparser = reqparse.RequestParser()\nself.reqparser.add_argument('symbol', required=False, type=str, location=['form', 'json'])\nself.reqparser.add_argument('description', required=False, type=str, location=['form', 'json'])",
"if not get_jwt_claims()['admin']:\n return ({'message': 'Not Authorized.'}, ... | <|body_start_0|>
self.reqparser = reqparse.RequestParser()
self.reqparser.add_argument('symbol', required=False, type=str, location=['form', 'json'])
self.reqparser.add_argument('description', required=False, type=str, location=['form', 'json'])
<|end_body_0|>
<|body_start_1|>
if not ge... | Fetches a specified unit instance from the database by its symbol or description :post: :arg symbol: Symbol string of the unit eg 'kg' :arg description: The description of the unit :type symbol: str :type description: str | GetUnitOfMeasure | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetUnitOfMeasure:
"""Fetches a specified unit instance from the database by its symbol or description :post: :arg symbol: Symbol string of the unit eg 'kg' :arg description: The description of the unit :type symbol: str :type description: str"""
def __init__(self) -> None:
"""Instant... | stack_v2_sparse_classes_10k_train_002047 | 2,710 | permissive | [
{
"docstring": "Instantiates the endpoint to get a unit from the database table unit.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Fetches a specified unit instance from the database by its symbol or description :post: :arg symbol: Symbol string of the unit ... | 2 | stack_v2_sparse_classes_30k_train_006950 | Implement the Python class `GetUnitOfMeasure` described below.
Class description:
Fetches a specified unit instance from the database by its symbol or description :post: :arg symbol: Symbol string of the unit eg 'kg' :arg description: The description of the unit :type symbol: str :type description: str
Method signatu... | Implement the Python class `GetUnitOfMeasure` described below.
Class description:
Fetches a specified unit instance from the database by its symbol or description :post: :arg symbol: Symbol string of the unit eg 'kg' :arg description: The description of the unit :type symbol: str :type description: str
Method signatu... | 5d123691d1f25d0b85e20e4e8293266bf23c9f8a | <|skeleton|>
class GetUnitOfMeasure:
"""Fetches a specified unit instance from the database by its symbol or description :post: :arg symbol: Symbol string of the unit eg 'kg' :arg description: The description of the unit :type symbol: str :type description: str"""
def __init__(self) -> None:
"""Instant... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GetUnitOfMeasure:
"""Fetches a specified unit instance from the database by its symbol or description :post: :arg symbol: Symbol string of the unit eg 'kg' :arg description: The description of the unit :type symbol: str :type description: str"""
def __init__(self) -> None:
"""Instantiates the end... | the_stack_v2_python_sparse | Analytics/resources/units/get_unit.py | thanosbnt/SharingCitiesDashboard | train | 0 |
c838b97f2badd0127072e0460292c3f4a1c35d59 | [
"learning_rate = 0.001\nresolution = (128, 128)\nbatch_size = 2\nnum_slots = 3\nnum_iterations = 2\noptimizer = tf.keras.optimizers.Adam(learning_rate, epsilon=1e-08)\nmodel = model_utils.build_model(resolution, batch_size, num_slots, num_iterations, model_type='object_discovery')\ninput_shape = (batch_size, resolu... | <|body_start_0|>
learning_rate = 0.001
resolution = (128, 128)
batch_size = 2
num_slots = 3
num_iterations = 2
optimizer = tf.keras.optimizers.Adam(learning_rate, epsilon=1e-08)
model = model_utils.build_model(resolution, batch_size, num_slots, num_iterations, mod... | Test model construction and training. | ModelTests | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelTests:
"""Test model construction and training."""
def test_object_discovery_model(self):
"""Test object discovery model."""
<|body_0|>
def test_set_prediction_model(self):
"""Test set prediction model."""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_10k_train_002048 | 2,850 | permissive | [
{
"docstring": "Test object discovery model.",
"name": "test_object_discovery_model",
"signature": "def test_object_discovery_model(self)"
},
{
"docstring": "Test set prediction model.",
"name": "test_set_prediction_model",
"signature": "def test_set_prediction_model(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000678 | Implement the Python class `ModelTests` described below.
Class description:
Test model construction and training.
Method signatures and docstrings:
- def test_object_discovery_model(self): Test object discovery model.
- def test_set_prediction_model(self): Test set prediction model. | Implement the Python class `ModelTests` described below.
Class description:
Test model construction and training.
Method signatures and docstrings:
- def test_object_discovery_model(self): Test object discovery model.
- def test_set_prediction_model(self): Test set prediction model.
<|skeleton|>
class ModelTests:
... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class ModelTests:
"""Test model construction and training."""
def test_object_discovery_model(self):
"""Test object discovery model."""
<|body_0|>
def test_set_prediction_model(self):
"""Test set prediction model."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ModelTests:
"""Test model construction and training."""
def test_object_discovery_model(self):
"""Test object discovery model."""
learning_rate = 0.001
resolution = (128, 128)
batch_size = 2
num_slots = 3
num_iterations = 2
optimizer = tf.keras.opti... | the_stack_v2_python_sparse | slot_attention/unit_tests/test_lib.py | Jimmy-INL/google-research | train | 1 |
df5d2e0541397e5c8c6863ced056aa9a5711873f | [
"query = self.session.query(VOpenposition.timecreate, VOpenposition.timeupdate, VOpenposition.position, VOpenposition.login, VOpenposition.symbol, VOpenposition.action, VOpenposition.volume, VOpenposition.priceopen, VOpenposition.pricesl, VOpenposition.pricetp, VOpenposition.pricecurrent, VOpenposition.storage, VOp... | <|body_start_0|>
query = self.session.query(VOpenposition.timecreate, VOpenposition.timeupdate, VOpenposition.position, VOpenposition.login, VOpenposition.symbol, VOpenposition.action, VOpenposition.volume, VOpenposition.priceopen, VOpenposition.pricesl, VOpenposition.pricetp, VOpenposition.pricecurrent, VOpenp... | v_openposition视图操作 | VOpenpositionDao | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VOpenpositionDao:
"""v_openposition视图操作"""
def search_by_uid(self, uid, start, end, mtlogin, page=None):
"""已知用户id,根据时间段,查询飘单记录 :param uid: 用户id :param start: 开始时间 :param end: 结束时间 :return: 各项总和"""
<|body_0|>
def searchsum_by_uid(self, uid, start, end, mtlogin):
... | stack_v2_sparse_classes_10k_train_002049 | 26,694 | permissive | [
{
"docstring": "已知用户id,根据时间段,查询飘单记录 :param uid: 用户id :param start: 开始时间 :param end: 结束时间 :return: 各项总和",
"name": "search_by_uid",
"signature": "def search_by_uid(self, uid, start, end, mtlogin, page=None)"
},
{
"docstring": "已知用户id,根据时间段,查询总和 :param uid: 用户id :param start: 开始时间 :param end: 结束时间 ... | 2 | stack_v2_sparse_classes_30k_train_007224 | Implement the Python class `VOpenpositionDao` described below.
Class description:
v_openposition视图操作
Method signatures and docstrings:
- def search_by_uid(self, uid, start, end, mtlogin, page=None): 已知用户id,根据时间段,查询飘单记录 :param uid: 用户id :param start: 开始时间 :param end: 结束时间 :return: 各项总和
- def searchsum_by_uid(self, uid... | Implement the Python class `VOpenpositionDao` described below.
Class description:
v_openposition视图操作
Method signatures and docstrings:
- def search_by_uid(self, uid, start, end, mtlogin, page=None): 已知用户id,根据时间段,查询飘单记录 :param uid: 用户id :param start: 开始时间 :param end: 结束时间 :return: 各项总和
- def searchsum_by_uid(self, uid... | 1fadeecf31f1d25e258dc5d70c47a785f7b33961 | <|skeleton|>
class VOpenpositionDao:
"""v_openposition视图操作"""
def search_by_uid(self, uid, start, end, mtlogin, page=None):
"""已知用户id,根据时间段,查询飘单记录 :param uid: 用户id :param start: 开始时间 :param end: 结束时间 :return: 各项总和"""
<|body_0|>
def searchsum_by_uid(self, uid, start, end, mtlogin):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VOpenpositionDao:
"""v_openposition视图操作"""
def search_by_uid(self, uid, start, end, mtlogin, page=None):
"""已知用户id,根据时间段,查询飘单记录 :param uid: 用户id :param start: 开始时间 :param end: 结束时间 :return: 各项总和"""
query = self.session.query(VOpenposition.timecreate, VOpenposition.timeupdate, VOpenpositio... | the_stack_v2_python_sparse | xwcrm/model/views.py | MSUNorg/XWCRM | train | 0 |
268519c40c5ddca2f9bd17416f6b86f28316806a | [
"self.name = name\nself.env = None\nself.reward_fn = get_reward_fn(task_name=task_name, layout_id=layout_id, is_planning=is_planning)\nself.history = []",
"assert self.env.prev_obs_data is not None\nassert self.env.obs_data is not None\nreward, termination = self.reward_fn(self.env.prev_obs_data, self.env.obs_dat... | <|body_start_0|>
self.name = name
self.env = None
self.reward_fn = get_reward_fn(task_name=task_name, layout_id=layout_id, is_planning=is_planning)
self.history = []
<|end_body_0|>
<|body_start_1|>
assert self.env.prev_obs_data is not None
assert self.env.obs_data is not... | Reward function of the pushing tasks. | PushReward | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PushReward:
"""Reward function of the pushing tasks."""
def __init__(self, name, task_name, layout_id, is_planning=False):
"""Initialize."""
<|body_0|>
def get_reward(self):
"""Returns the reward value of the current step."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_10k_train_002050 | 13,137 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, name, task_name, layout_id, is_planning=False)"
},
{
"docstring": "Returns the reward value of the current step.",
"name": "get_reward",
"signature": "def get_reward(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000403 | Implement the Python class `PushReward` described below.
Class description:
Reward function of the pushing tasks.
Method signatures and docstrings:
- def __init__(self, name, task_name, layout_id, is_planning=False): Initialize.
- def get_reward(self): Returns the reward value of the current step. | Implement the Python class `PushReward` described below.
Class description:
Reward function of the pushing tasks.
Method signatures and docstrings:
- def __init__(self, name, task_name, layout_id, is_planning=False): Initialize.
- def get_reward(self): Returns the reward value of the current step.
<|skeleton|>
class... | c333ce7f1d7b156bedf28c3b09793f5487b6690a | <|skeleton|>
class PushReward:
"""Reward function of the pushing tasks."""
def __init__(self, name, task_name, layout_id, is_planning=False):
"""Initialize."""
<|body_0|>
def get_reward(self):
"""Returns the reward value of the current step."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PushReward:
"""Reward function of the pushing tasks."""
def __init__(self, name, task_name, layout_id, is_planning=False):
"""Initialize."""
self.name = name
self.env = None
self.reward_fn = get_reward_fn(task_name=task_name, layout_id=layout_id, is_planning=is_planning)
... | the_stack_v2_python_sparse | robovat/reward_fns/push_reward.py | UT-Austin-RPL/robovat | train | 7 |
eb5a3d1ef291a7fb31526610ba6d5a92dc0d3f84 | [
"self.is_training = is_training\nself.root = root\nself.shuffle = shuffle\nself.drop_last = drop_last\nself.num_instances = num_instances\nself.instance_id = instance_id\nResnetMediaPipe.instance_count += 1\npipe_name = '{}:{}'.format(self.__class__.__name__, ResnetMediaPipe.instance_count)\npipe_name = str(pipe_na... | <|body_start_0|>
self.is_training = is_training
self.root = root
self.shuffle = shuffle
self.drop_last = drop_last
self.num_instances = num_instances
self.instance_id = instance_id
ResnetMediaPipe.instance_count += 1
pipe_name = '{}:{}'.format(self.__class... | Class defining resnet media pipe. | ResnetMediaPipe | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResnetMediaPipe:
"""Class defining resnet media pipe."""
def __init__(self, is_training=False, root=None, batch_size=1, shuffle=False, drop_last=True, queue_depth=1, num_instances=1, instance_id=0, device=None, seed=None):
""":params is_training: True if ResnetMediaPipe handles train... | stack_v2_sparse_classes_10k_train_002051 | 7,309 | permissive | [
{
"docstring": ":params is_training: True if ResnetMediaPipe handles training data, False in case of evaluation. :params root: path from which to load the images. :params batch_size: mediapipe output batch size. :params shuffle: whether images have to be shuffled. :params drop_last: whether to drop the last inc... | 2 | stack_v2_sparse_classes_30k_train_006390 | Implement the Python class `ResnetMediaPipe` described below.
Class description:
Class defining resnet media pipe.
Method signatures and docstrings:
- def __init__(self, is_training=False, root=None, batch_size=1, shuffle=False, drop_last=True, queue_depth=1, num_instances=1, instance_id=0, device=None, seed=None): :... | Implement the Python class `ResnetMediaPipe` described below.
Class description:
Class defining resnet media pipe.
Method signatures and docstrings:
- def __init__(self, is_training=False, root=None, batch_size=1, shuffle=False, drop_last=True, queue_depth=1, num_instances=1, instance_id=0, device=None, seed=None): :... | 3ca77c4a5fb62c60372e8a2839b1fccc3c4e4212 | <|skeleton|>
class ResnetMediaPipe:
"""Class defining resnet media pipe."""
def __init__(self, is_training=False, root=None, batch_size=1, shuffle=False, drop_last=True, queue_depth=1, num_instances=1, instance_id=0, device=None, seed=None):
""":params is_training: True if ResnetMediaPipe handles train... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ResnetMediaPipe:
"""Class defining resnet media pipe."""
def __init__(self, is_training=False, root=None, batch_size=1, shuffle=False, drop_last=True, queue_depth=1, num_instances=1, instance_id=0, device=None, seed=None):
""":params is_training: True if ResnetMediaPipe handles training data, Fal... | the_stack_v2_python_sparse | PyTorch/computer_vision/classification/torchvision/resnet_media_pipe.py | HabanaAI/Model-References | train | 108 |
2ab61fae1a943af8224ac40fbedbbf8868cf272b | [
"i = 0\nwhile i ** 2 <= x:\n i += 1\nreturn i if i ** 2 == x else i - 1",
"left, right = (0, x)\nwhile left <= right:\n mid = left + (right - left) // 2\n if mid ** 2 < x:\n left = mid + 1\n elif mid ** 2 > x:\n right = mid - 1\n else:\n return mid\nreturn right",
"y = x\nwhi... | <|body_start_0|>
i = 0
while i ** 2 <= x:
i += 1
return i if i ** 2 == x else i - 1
<|end_body_0|>
<|body_start_1|>
left, right = (0, x)
while left <= right:
mid = left + (right - left) // 2
if mid ** 2 < x:
left = mid + 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mySqrt(self, x: int) -> int:
"""执行用时 :8272 ms, 在所有 Python3 提交中击败了5.01%的用户 内存消耗 :13.6 MB, 在所有 Python3 提交中击败了5.09%的用户 :param x: :return:"""
<|body_0|>
def mySqrt2(self, x: int) -> int:
"""执行用时 :44 ms, 在所有 Python3 提交中击败了66.27%的用户 内存消耗 :13.7 MB, 在所有 Python3... | stack_v2_sparse_classes_10k_train_002052 | 2,069 | no_license | [
{
"docstring": "执行用时 :8272 ms, 在所有 Python3 提交中击败了5.01%的用户 内存消耗 :13.6 MB, 在所有 Python3 提交中击败了5.09%的用户 :param x: :return:",
"name": "mySqrt",
"signature": "def mySqrt(self, x: int) -> int"
},
{
"docstring": "执行用时 :44 ms, 在所有 Python3 提交中击败了66.27%的用户 内存消耗 :13.7 MB, 在所有 Python3 提交中击败了5.20%的用户 思路:二分法 :... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mySqrt(self, x: int) -> int: 执行用时 :8272 ms, 在所有 Python3 提交中击败了5.01%的用户 内存消耗 :13.6 MB, 在所有 Python3 提交中击败了5.09%的用户 :param x: :return:
- def mySqrt2(self, x: int) -> int: 执行用时 :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mySqrt(self, x: int) -> int: 执行用时 :8272 ms, 在所有 Python3 提交中击败了5.01%的用户 内存消耗 :13.6 MB, 在所有 Python3 提交中击败了5.09%的用户 :param x: :return:
- def mySqrt2(self, x: int) -> int: 执行用时 :... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def mySqrt(self, x: int) -> int:
"""执行用时 :8272 ms, 在所有 Python3 提交中击败了5.01%的用户 内存消耗 :13.6 MB, 在所有 Python3 提交中击败了5.09%的用户 :param x: :return:"""
<|body_0|>
def mySqrt2(self, x: int) -> int:
"""执行用时 :44 ms, 在所有 Python3 提交中击败了66.27%的用户 内存消耗 :13.7 MB, 在所有 Python3... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def mySqrt(self, x: int) -> int:
"""执行用时 :8272 ms, 在所有 Python3 提交中击败了5.01%的用户 内存消耗 :13.6 MB, 在所有 Python3 提交中击败了5.09%的用户 :param x: :return:"""
i = 0
while i ** 2 <= x:
i += 1
return i if i ** 2 == x else i - 1
def mySqrt2(self, x: int) -> int:
... | the_stack_v2_python_sparse | LeetCode/数学/69. Sqrt(x).py | yiming1012/MyLeetCode | train | 2 | |
69a7db37f552a29e804b6bdf8cd3878c590c8602 | [
"_LOGGER.debug('Enable charging: %s', self.name)\nawait self.tesla_device.start_charge()\nself.async_write_ha_state()",
"_LOGGER.debug('Disable charging for: %s', self.name)\nawait self.tesla_device.stop_charge()\nself.async_write_ha_state()",
"if self.tesla_device.is_charging() is None:\n return None\nretur... | <|body_start_0|>
_LOGGER.debug('Enable charging: %s', self.name)
await self.tesla_device.start_charge()
self.async_write_ha_state()
<|end_body_0|>
<|body_start_1|>
_LOGGER.debug('Disable charging for: %s', self.name)
await self.tesla_device.stop_charge()
self.async_write... | Representation of a Tesla charger switch. | ChargerSwitch | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChargerSwitch:
"""Representation of a Tesla charger switch."""
async def async_turn_on(self, **kwargs):
"""Send the on command."""
<|body_0|>
async def async_turn_off(self, **kwargs):
"""Send the off command."""
<|body_1|>
def is_on(self):
""... | stack_v2_sparse_classes_10k_train_002053 | 4,636 | permissive | [
{
"docstring": "Send the on command.",
"name": "async_turn_on",
"signature": "async def async_turn_on(self, **kwargs)"
},
{
"docstring": "Send the off command.",
"name": "async_turn_off",
"signature": "async def async_turn_off(self, **kwargs)"
},
{
"docstring": "Get whether the s... | 3 | null | Implement the Python class `ChargerSwitch` described below.
Class description:
Representation of a Tesla charger switch.
Method signatures and docstrings:
- async def async_turn_on(self, **kwargs): Send the on command.
- async def async_turn_off(self, **kwargs): Send the off command.
- def is_on(self): Get whether th... | Implement the Python class `ChargerSwitch` described below.
Class description:
Representation of a Tesla charger switch.
Method signatures and docstrings:
- async def async_turn_on(self, **kwargs): Send the on command.
- async def async_turn_off(self, **kwargs): Send the off command.
- def is_on(self): Get whether th... | 2fee32fce03bc49e86cf2e7b741a15621a97cce5 | <|skeleton|>
class ChargerSwitch:
"""Representation of a Tesla charger switch."""
async def async_turn_on(self, **kwargs):
"""Send the on command."""
<|body_0|>
async def async_turn_off(self, **kwargs):
"""Send the off command."""
<|body_1|>
def is_on(self):
""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ChargerSwitch:
"""Representation of a Tesla charger switch."""
async def async_turn_on(self, **kwargs):
"""Send the on command."""
_LOGGER.debug('Enable charging: %s', self.name)
await self.tesla_device.start_charge()
self.async_write_ha_state()
async def async_turn_o... | the_stack_v2_python_sparse | homeassistant/components/tesla/switch.py | BenWoodford/home-assistant | train | 11 |
f3037a1d461ece66e5fae87be3335f615c2ece9d | [
"if table_size < 1:\n raise ValueError('table_size must be at least 1.')\nif repetitions < 3:\n raise ValueError('repetitions must be at least 3.')\nself._seed = seed\nself._salt = [str(seed + i) + _SEPARATOR for i in range(repetitions)]\nself._table_size = table_size\nself._repetitions = repetitions",
"all... | <|body_start_0|>
if table_size < 1:
raise ValueError('table_size must be at least 1.')
if repetitions < 3:
raise ValueError('repetitions must be at least 3.')
self._seed = seed
self._salt = [str(seed + i) + _SEPARATOR for i in range(repetitions)]
self._tab... | Hashes a string to a list of independently sampled indices. For a string, generates a set of indices such that each index is independently sampled uniformly at random. | RandomHyperEdgeHasher | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomHyperEdgeHasher:
"""Hashes a string to a list of independently sampled indices. For a string, generates a set of indices such that each index is independently sampled uniformly at random."""
def __init__(self, seed: int, table_size: int, repetitions: int):
"""Initializes `Rando... | stack_v2_sparse_classes_10k_train_002054 | 10,259 | permissive | [
{
"docstring": "Initializes `RandomHyperEdgeHasher`. Args: seed: An integer seed for hash functions. table_size: The hash table size of the IBLT. Must be a positive integer. repetitions: The number of repetitions in IBLT data structure. Must be an integer at least 3. Raises: ValueError: If arguments do not meet... | 3 | stack_v2_sparse_classes_30k_test_000404 | Implement the Python class `RandomHyperEdgeHasher` described below.
Class description:
Hashes a string to a list of independently sampled indices. For a string, generates a set of indices such that each index is independently sampled uniformly at random.
Method signatures and docstrings:
- def __init__(self, seed: in... | Implement the Python class `RandomHyperEdgeHasher` described below.
Class description:
Hashes a string to a list of independently sampled indices. For a string, generates a set of indices such that each index is independently sampled uniformly at random.
Method signatures and docstrings:
- def __init__(self, seed: in... | ad4bca66f4b483e09d8396e9948630813a343d27 | <|skeleton|>
class RandomHyperEdgeHasher:
"""Hashes a string to a list of independently sampled indices. For a string, generates a set of indices such that each index is independently sampled uniformly at random."""
def __init__(self, seed: int, table_size: int, repetitions: int):
"""Initializes `Rando... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RandomHyperEdgeHasher:
"""Hashes a string to a list of independently sampled indices. For a string, generates a set of indices such that each index is independently sampled uniformly at random."""
def __init__(self, seed: int, table_size: int, repetitions: int):
"""Initializes `RandomHyperEdgeHas... | the_stack_v2_python_sparse | tensorflow_federated/python/analytics/heavy_hitters/iblt/hyperedge_hashers.py | tensorflow/federated | train | 2,297 |
6789042fd28f7c65312f2d8dc337637d9dc2aa44 | [
"self.block_proc = cell_proc\nself.proc_block_np = proc_cell_np\nself.num_procs = len(proc_cell_np)\nself.c = kwargs.get('c', 0.3)\nif init:\n self.gen_clusters(**kwargs)",
"for cluster in self.clusters:\n cluster.cells[:] = []\nfor cell in self.block_proc:\n wdists = []\n for cluster in self.clusters... | <|body_start_0|>
self.block_proc = cell_proc
self.proc_block_np = proc_cell_np
self.num_procs = len(proc_cell_np)
self.c = kwargs.get('c', 0.3)
if init:
self.gen_clusters(**kwargs)
<|end_body_0|>
<|body_start_1|>
for cluster in self.clusters:
clus... | Partition of cells for parallel solvers | ParDecompose | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParDecompose:
"""Partition of cells for parallel solvers"""
def __init__(self, cell_proc, proc_cell_np, init=True, **kwargs):
"""constructor kwargs can be used to finetune the algorithm: c = (0.3) the ratio of euler distance contribution in calculating the distance of particle from c... | stack_v2_sparse_classes_10k_train_002055 | 12,256 | permissive | [
{
"docstring": "constructor kwargs can be used to finetune the algorithm: c = (0.3) the ratio of euler distance contribution in calculating the distance of particle from cluster center (the other component is scaled distance based on cluster size) t = (0.2) ratio of old component of center in the center calcula... | 6 | stack_v2_sparse_classes_30k_train_007166 | Implement the Python class `ParDecompose` described below.
Class description:
Partition of cells for parallel solvers
Method signatures and docstrings:
- def __init__(self, cell_proc, proc_cell_np, init=True, **kwargs): constructor kwargs can be used to finetune the algorithm: c = (0.3) the ratio of euler distance co... | Implement the Python class `ParDecompose` described below.
Class description:
Partition of cells for parallel solvers
Method signatures and docstrings:
- def __init__(self, cell_proc, proc_cell_np, init=True, **kwargs): constructor kwargs can be used to finetune the algorithm: c = (0.3) the ratio of euler distance co... | 5bb1fc46a9c84aefd42758356a9986689db05454 | <|skeleton|>
class ParDecompose:
"""Partition of cells for parallel solvers"""
def __init__(self, cell_proc, proc_cell_np, init=True, **kwargs):
"""constructor kwargs can be used to finetune the algorithm: c = (0.3) the ratio of euler distance contribution in calculating the distance of particle from c... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ParDecompose:
"""Partition of cells for parallel solvers"""
def __init__(self, cell_proc, proc_cell_np, init=True, **kwargs):
"""constructor kwargs can be used to finetune the algorithm: c = (0.3) the ratio of euler distance contribution in calculating the distance of particle from cluster center... | the_stack_v2_python_sparse | source/pysph/parallel/load_balancer_mkmeans.py | pankajp/pysph | train | 1 |
754d3a0a02fb2655478b3d9efbbd2f17777ca101 | [
"self.access_zone_name = access_zone_name\nself.nfs_mount_point = nfs_mount_point\nself.path = path\nself.protocols = protocols\nself.smb_mount_points = smb_mount_points",
"if dictionary is None:\n return None\naccess_zone_name = dictionary.get('accessZoneName')\nnfs_mount_point = cohesity_management_sdk.model... | <|body_start_0|>
self.access_zone_name = access_zone_name
self.nfs_mount_point = nfs_mount_point
self.path = path
self.protocols = protocols
self.smb_mount_points = smb_mount_points
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
ac... | Implementation of the 'IsilonMountPoint' model. Specifies information about a mount point in an Isilon OneFs Cluster. Attributes: access_zone_name (string): Specifies the name of access zone. nfs_mount_point (IsilonNfsMountPoint): Specifies information about an NFS export. This field is set if the file system supports ... | IsilonMountPoint | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IsilonMountPoint:
"""Implementation of the 'IsilonMountPoint' model. Specifies information about a mount point in an Isilon OneFs Cluster. Attributes: access_zone_name (string): Specifies the name of access zone. nfs_mount_point (IsilonNfsMountPoint): Specifies information about an NFS export. Th... | stack_v2_sparse_classes_10k_train_002056 | 3,464 | permissive | [
{
"docstring": "Constructor for the IsilonMountPoint class",
"name": "__init__",
"signature": "def __init__(self, access_zone_name=None, nfs_mount_point=None, path=None, protocols=None, smb_mount_points=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionar... | 2 | null | Implement the Python class `IsilonMountPoint` described below.
Class description:
Implementation of the 'IsilonMountPoint' model. Specifies information about a mount point in an Isilon OneFs Cluster. Attributes: access_zone_name (string): Specifies the name of access zone. nfs_mount_point (IsilonNfsMountPoint): Specif... | Implement the Python class `IsilonMountPoint` described below.
Class description:
Implementation of the 'IsilonMountPoint' model. Specifies information about a mount point in an Isilon OneFs Cluster. Attributes: access_zone_name (string): Specifies the name of access zone. nfs_mount_point (IsilonNfsMountPoint): Specif... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class IsilonMountPoint:
"""Implementation of the 'IsilonMountPoint' model. Specifies information about a mount point in an Isilon OneFs Cluster. Attributes: access_zone_name (string): Specifies the name of access zone. nfs_mount_point (IsilonNfsMountPoint): Specifies information about an NFS export. Th... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class IsilonMountPoint:
"""Implementation of the 'IsilonMountPoint' model. Specifies information about a mount point in an Isilon OneFs Cluster. Attributes: access_zone_name (string): Specifies the name of access zone. nfs_mount_point (IsilonNfsMountPoint): Specifies information about an NFS export. This field is s... | the_stack_v2_python_sparse | cohesity_management_sdk/models/isilon_mount_point.py | cohesity/management-sdk-python | train | 24 |
401f469d870af734a199eb7395b4c9fd190a5245 | [
"logger.info(f'Trainer arguments: {pl_trainer_args}')\nif pl_trainer_args['resume_from_checkpoint'] is not None and (not pl_trainer_args['resume_from_checkpoint'].endswith('.ckpt')):\n pl_trainer_args['resume_from_checkpoint'] = None\npl_trainer_args['callbacks'] = {'model_checkpoint_callback': {'save_top_k': pl... | <|body_start_0|>
logger.info(f'Trainer arguments: {pl_trainer_args}')
if pl_trainer_args['resume_from_checkpoint'] is not None and (not pl_trainer_args['resume_from_checkpoint'].endswith('.ckpt')):
pl_trainer_args['resume_from_checkpoint'] = None
pl_trainer_args['callbacks'] = {'mode... | gflownet training pipelines. | GFlowNetTrainingPipeline | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GFlowNetTrainingPipeline:
"""gflownet training pipelines."""
def train(self, pl_trainer_args: Dict[str, Any], model_args: Dict[str, Union[float, str, int]], dataset_args: Dict[str, Union[float, str, int]], dataset: GFlowNetDataset, environment: GraphBuildingEnv, context: GraphBuildingEnvCont... | stack_v2_sparse_classes_10k_train_002057 | 16,893 | permissive | [
{
"docstring": "Generic training function for PyTorch Lightning-based training. Args: pl_trainer_args: pytorch lightning trainer arguments passed to the configuration. model_args: model arguments passed to the configuration. dataset_args: dataset arguments passed to the configuration. dataset: dataset to be use... | 2 | stack_v2_sparse_classes_30k_train_003550 | Implement the Python class `GFlowNetTrainingPipeline` described below.
Class description:
gflownet training pipelines.
Method signatures and docstrings:
- def train(self, pl_trainer_args: Dict[str, Any], model_args: Dict[str, Union[float, str, int]], dataset_args: Dict[str, Union[float, str, int]], dataset: GFlowNetD... | Implement the Python class `GFlowNetTrainingPipeline` described below.
Class description:
gflownet training pipelines.
Method signatures and docstrings:
- def train(self, pl_trainer_args: Dict[str, Any], model_args: Dict[str, Union[float, str, int]], dataset_args: Dict[str, Union[float, str, int]], dataset: GFlowNetD... | 0b69b7d5b261f2f9af3984793c1295b9b80cd01a | <|skeleton|>
class GFlowNetTrainingPipeline:
"""gflownet training pipelines."""
def train(self, pl_trainer_args: Dict[str, Any], model_args: Dict[str, Union[float, str, int]], dataset_args: Dict[str, Union[float, str, int]], dataset: GFlowNetDataset, environment: GraphBuildingEnv, context: GraphBuildingEnvCont... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GFlowNetTrainingPipeline:
"""gflownet training pipelines."""
def train(self, pl_trainer_args: Dict[str, Any], model_args: Dict[str, Union[float, str, int]], dataset_args: Dict[str, Union[float, str, int]], dataset: GFlowNetDataset, environment: GraphBuildingEnv, context: GraphBuildingEnvContext, task: GF... | the_stack_v2_python_sparse | src/gt4sd/training_pipelines/pytorch_lightning/gflownet/core.py | GT4SD/gt4sd-core | train | 239 |
e027a9183c2c149dd94aeeaa48900e5a483960bd | [
"super().__init__()\nself._img_size = config.get('img_size')\nself._input_channel = config.get('input_channel')\nself._filter_sizes = config.get('filter_size')\nself._kernel_size = config.get('kernel_size')\nself._padding = padding\nself._stride = stride\nself._dilation = dilation\nself._encoder_maxpool_count = con... | <|body_start_0|>
super().__init__()
self._img_size = config.get('img_size')
self._input_channel = config.get('input_channel')
self._filter_sizes = config.get('filter_size')
self._kernel_size = config.get('kernel_size')
self._padding = padding
self._stride = stride... | Stochastic_Conv_Encoder | Stochastic_Conv_Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stochastic_Conv_Encoder:
"""Stochastic_Conv_Encoder"""
def __init__(self, config, padding=0, stride=2, dilation=1):
"""NP"""
<|body_0|>
def forward(self, inputs):
"""Args: input : imamges (num_tasks, num_points (way * shot), img_size, img_size) Return: output :""... | stack_v2_sparse_classes_10k_train_002058 | 18,202 | no_license | [
{
"docstring": "NP",
"name": "__init__",
"signature": "def __init__(self, config, padding=0, stride=2, dilation=1)"
},
{
"docstring": "Args: input : imamges (num_tasks, num_points (way * shot), img_size, img_size) Return: output :",
"name": "forward",
"signature": "def forward(self, inpu... | 2 | stack_v2_sparse_classes_30k_train_002519 | Implement the Python class `Stochastic_Conv_Encoder` described below.
Class description:
Stochastic_Conv_Encoder
Method signatures and docstrings:
- def __init__(self, config, padding=0, stride=2, dilation=1): NP
- def forward(self, inputs): Args: input : imamges (num_tasks, num_points (way * shot), img_size, img_siz... | Implement the Python class `Stochastic_Conv_Encoder` described below.
Class description:
Stochastic_Conv_Encoder
Method signatures and docstrings:
- def __init__(self, config, padding=0, stride=2, dilation=1): NP
- def forward(self, inputs): Args: input : imamges (num_tasks, num_points (way * shot), img_size, img_siz... | c7e1bfb49ebaec6937ed7b186689227f95a43e0f | <|skeleton|>
class Stochastic_Conv_Encoder:
"""Stochastic_Conv_Encoder"""
def __init__(self, config, padding=0, stride=2, dilation=1):
"""NP"""
<|body_0|>
def forward(self, inputs):
"""Args: input : imamges (num_tasks, num_points (way * shot), img_size, img_size) Return: output :""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Stochastic_Conv_Encoder:
"""Stochastic_Conv_Encoder"""
def __init__(self, config, padding=0, stride=2, dilation=1):
"""NP"""
super().__init__()
self._img_size = config.get('img_size')
self._input_channel = config.get('input_channel')
self._filter_sizes = config.get... | the_stack_v2_python_sparse | model/MAML/Part/encoder.py | MingyuKim87/MLwM | train | 0 |
c6d230cdcfaef450de89da720c929356634afd61 | [
"if not nums:\n self.root = None\n return\n\ndef make_tree(start, end):\n root = Node()\n if start == end:\n root.val = nums[start]\n return root\n left = make_tree(start, (start + end) // 2)\n right = make_tree((start + end) // 2 + 1, end)\n root.val = left.val + right.val\n r... | <|body_start_0|>
if not nums:
self.root = None
return
def make_tree(start, end):
root = Node()
if start == end:
root.val = nums[start]
return root
left = make_tree(start, (start + end) // 2)
right = ... | 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_10k_train_002059 | 2,123 | 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 | stack_v2_sparse_classes_30k_test_000083 | 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:... | 4416d0c711b8978f12de960c29d00a9d9792b9e0 | <|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_10k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
if not nums:
self.root = None
return
def make_tree(start, end):
root = Node()
if start == end:
root.val = nums[start]
return root
... | the_stack_v2_python_sparse | 301-400/307. Range Sum Query - Mutable.py | Ys-Zhou/leetcode-medi-p3 | train | 0 | |
468aa25f469ef2be7f2730cf01c783b25cbe4e4e | [
"self.disk_file_name = disk_file_name\nself.length_bytes = length_bytes\nself.number = number\nself.offset_bytes = offset_bytes",
"if dictionary is None:\n return None\ndisk_file_name = dictionary.get('diskFileName')\nlength_bytes = dictionary.get('lengthBytes')\nnumber = dictionary.get('number')\noffset_bytes... | <|body_start_0|>
self.disk_file_name = disk_file_name
self.length_bytes = length_bytes
self.number = number
self.offset_bytes = offset_bytes
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
disk_file_name = dictionary.get('diskFileName')
... | Implementation of the 'FilePartitionBlock' model. Defines a leaf node of a device tree. This refers to a logical partition in a virtual disk file. Attributes: disk_file_name (string): Specifies the disk file name where the logical partition is. length_bytes (long|int): Specifies the length of the block in bytes. number... | FilePartitionBlock | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilePartitionBlock:
"""Implementation of the 'FilePartitionBlock' model. Defines a leaf node of a device tree. This refers to a logical partition in a virtual disk file. Attributes: disk_file_name (string): Specifies the disk file name where the logical partition is. length_bytes (long|int): Spec... | stack_v2_sparse_classes_10k_train_002060 | 2,389 | permissive | [
{
"docstring": "Constructor for the FilePartitionBlock class",
"name": "__init__",
"signature": "def __init__(self, disk_file_name=None, length_bytes=None, number=None, offset_bytes=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dic... | 2 | null | Implement the Python class `FilePartitionBlock` described below.
Class description:
Implementation of the 'FilePartitionBlock' model. Defines a leaf node of a device tree. This refers to a logical partition in a virtual disk file. Attributes: disk_file_name (string): Specifies the disk file name where the logical part... | Implement the Python class `FilePartitionBlock` described below.
Class description:
Implementation of the 'FilePartitionBlock' model. Defines a leaf node of a device tree. This refers to a logical partition in a virtual disk file. Attributes: disk_file_name (string): Specifies the disk file name where the logical part... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class FilePartitionBlock:
"""Implementation of the 'FilePartitionBlock' model. Defines a leaf node of a device tree. This refers to a logical partition in a virtual disk file. Attributes: disk_file_name (string): Specifies the disk file name where the logical partition is. length_bytes (long|int): Spec... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FilePartitionBlock:
"""Implementation of the 'FilePartitionBlock' model. Defines a leaf node of a device tree. This refers to a logical partition in a virtual disk file. Attributes: disk_file_name (string): Specifies the disk file name where the logical partition is. length_bytes (long|int): Specifies the len... | the_stack_v2_python_sparse | cohesity_management_sdk/models/file_partition_block.py | cohesity/management-sdk-python | train | 24 |
e96945fababa77d483574550ab01855da9d66d98 | [
"permission = AdministerOrganizationPermission(orgname)\nif permission.can():\n organization = model.organization.get_organization(orgname)\n if not organization.stripe_id:\n raise NotFound()\n return {'fields': get_invoice_fields(organization)[0]}\nabort(403)",
"permission = AdministerOrganizatio... | <|body_start_0|>
permission = AdministerOrganizationPermission(orgname)
if permission.can():
organization = model.organization.get_organization(orgname)
if not organization.stripe_id:
raise NotFound()
return {'fields': get_invoice_fields(organization)[... | Resource for listing and creating an organization's custom invoice fields. | OrganizationInvoiceFieldList | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrganizationInvoiceFieldList:
"""Resource for listing and creating an organization's custom invoice fields."""
def get(self, orgname):
"""List the invoice fields for the organization."""
<|body_0|>
def post(self, orgname):
"""Creates a new invoice field."""
... | stack_v2_sparse_classes_10k_train_002061 | 33,890 | permissive | [
{
"docstring": "List the invoice fields for the organization.",
"name": "get",
"signature": "def get(self, orgname)"
},
{
"docstring": "Creates a new invoice field.",
"name": "post",
"signature": "def post(self, orgname)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001839 | Implement the Python class `OrganizationInvoiceFieldList` described below.
Class description:
Resource for listing and creating an organization's custom invoice fields.
Method signatures and docstrings:
- def get(self, orgname): List the invoice fields for the organization.
- def post(self, orgname): Creates a new in... | Implement the Python class `OrganizationInvoiceFieldList` described below.
Class description:
Resource for listing and creating an organization's custom invoice fields.
Method signatures and docstrings:
- def get(self, orgname): List the invoice fields for the organization.
- def post(self, orgname): Creates a new in... | e400a0c22c5f89dd35d571654b13d262b1f6e3b3 | <|skeleton|>
class OrganizationInvoiceFieldList:
"""Resource for listing and creating an organization's custom invoice fields."""
def get(self, orgname):
"""List the invoice fields for the organization."""
<|body_0|>
def post(self, orgname):
"""Creates a new invoice field."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OrganizationInvoiceFieldList:
"""Resource for listing and creating an organization's custom invoice fields."""
def get(self, orgname):
"""List the invoice fields for the organization."""
permission = AdministerOrganizationPermission(orgname)
if permission.can():
organi... | the_stack_v2_python_sparse | endpoints/api/billing.py | quay/quay | train | 2,363 |
025a2da059013785fecfcaf19bfbd8e042158938 | [
"ret = None\nl = []\nmapper = StudentJSONMapper()\nfor student in students:\n l.append(mapper.map_to_json(student))\nreturn json.dumps(l, indent=4, sort_keys=True)",
"l = []\nmapper = StudentJSONMapper()\nfor student in students:\n l.append(mapper.map_to_json(student))\nwith open(filename, 'w') as fh:\n ... | <|body_start_0|>
ret = None
l = []
mapper = StudentJSONMapper()
for student in students:
l.append(mapper.map_to_json(student))
return json.dumps(l, indent=4, sort_keys=True)
<|end_body_0|>
<|body_start_1|>
l = []
mapper = StudentJSONMapper()
f... | This class is used for exporting students to JSON files, and importing students from JSON files. | StudentJSONSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StudentJSONSerializer:
"""This class is used for exporting students to JSON files, and importing students from JSON files."""
def exportAsJSON(self, students):
"""Generates JSON data from students :param students: list of model.Student.Student-s :return: JSON data"""
<|body_0... | stack_v2_sparse_classes_10k_train_002062 | 1,650 | no_license | [
{
"docstring": "Generates JSON data from students :param students: list of model.Student.Student-s :return: JSON data",
"name": "exportAsJSON",
"signature": "def exportAsJSON(self, students)"
},
{
"docstring": "Exports students to the JSON file with the given filename. :param students: list of m... | 3 | stack_v2_sparse_classes_30k_train_004346 | Implement the Python class `StudentJSONSerializer` described below.
Class description:
This class is used for exporting students to JSON files, and importing students from JSON files.
Method signatures and docstrings:
- def exportAsJSON(self, students): Generates JSON data from students :param students: list of model... | Implement the Python class `StudentJSONSerializer` described below.
Class description:
This class is used for exporting students to JSON files, and importing students from JSON files.
Method signatures and docstrings:
- def exportAsJSON(self, students): Generates JSON data from students :param students: list of model... | a30389aa4542a23011a955ac61bf5b853c3e7854 | <|skeleton|>
class StudentJSONSerializer:
"""This class is used for exporting students to JSON files, and importing students from JSON files."""
def exportAsJSON(self, students):
"""Generates JSON data from students :param students: list of model.Student.Student-s :return: JSON data"""
<|body_0... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StudentJSONSerializer:
"""This class is used for exporting students to JSON files, and importing students from JSON files."""
def exportAsJSON(self, students):
"""Generates JSON data from students :param students: list of model.Student.Student-s :return: JSON data"""
ret = None
l ... | the_stack_v2_python_sparse | serializer/StudentJSONSerializer.py | edutilos6666/PythonSciStudentProject | train | 0 |
22fcc0cd69accb362d71f418cc4e41c05f9ee297 | [
"author_list = list(set(map(lambda article: article.author, Article.objects.all())))\nfor author in author_list:\n yield (author.id, author.nickname or author.username)",
"author_id = self.value()\nif author_id:\n return queryset.filter(author__id=author_id)\nelse:\n return queryset"
] | <|body_start_0|>
author_list = list(set(map(lambda article: article.author, Article.objects.all())))
for author in author_list:
yield (author.id, author.nickname or author.username)
<|end_body_0|>
<|body_start_1|>
author_id = self.value()
if author_id:
return que... | 自定义查询的过滤器-根据文章作者过滤文章 | ArticleAuthorListFilter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArticleAuthorListFilter:
"""自定义查询的过滤器-根据文章作者过滤文章"""
def lookups(self, request, model_admin):
"""Must be overridden to return a list of tuples (value, verbose value)"""
<|body_0|>
def queryset(self, request, queryset):
"""Return the filtered queryset."""
<... | stack_v2_sparse_classes_10k_train_002063 | 10,733 | permissive | [
{
"docstring": "Must be overridden to return a list of tuples (value, verbose value)",
"name": "lookups",
"signature": "def lookups(self, request, model_admin)"
},
{
"docstring": "Return the filtered queryset.",
"name": "queryset",
"signature": "def queryset(self, request, queryset)"
}... | 2 | stack_v2_sparse_classes_30k_train_003041 | Implement the Python class `ArticleAuthorListFilter` described below.
Class description:
自定义查询的过滤器-根据文章作者过滤文章
Method signatures and docstrings:
- def lookups(self, request, model_admin): Must be overridden to return a list of tuples (value, verbose value)
- def queryset(self, request, queryset): Return the filtered q... | Implement the Python class `ArticleAuthorListFilter` described below.
Class description:
自定义查询的过滤器-根据文章作者过滤文章
Method signatures and docstrings:
- def lookups(self, request, model_admin): Must be overridden to return a list of tuples (value, verbose value)
- def queryset(self, request, queryset): Return the filtered q... | 0fcf3709fabeee49874343b3a4ab80582698c466 | <|skeleton|>
class ArticleAuthorListFilter:
"""自定义查询的过滤器-根据文章作者过滤文章"""
def lookups(self, request, model_admin):
"""Must be overridden to return a list of tuples (value, verbose value)"""
<|body_0|>
def queryset(self, request, queryset):
"""Return the filtered queryset."""
<... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ArticleAuthorListFilter:
"""自定义查询的过滤器-根据文章作者过滤文章"""
def lookups(self, request, model_admin):
"""Must be overridden to return a list of tuples (value, verbose value)"""
author_list = list(set(map(lambda article: article.author, Article.objects.all())))
for author in author_list:
... | the_stack_v2_python_sparse | blog/admin.py | enjoy-binbin/Django-blog | train | 113 |
daf7ce02d1a3d3a275d7e2a771f708388619e0df | [
"self.log.info('login from GitHub')\ncode = context.get('code')\nif not code:\n return None\naccess_token = self.get_token(code)\nself.log.info('Successfully get access token from github using code %s' % code)\nuser_info = self.get_user_info(access_token)\nemail_list = self.get_emails(access_token)\nself.log.inf... | <|body_start_0|>
self.log.info('login from GitHub')
code = context.get('code')
if not code:
return None
access_token = self.get_token(code)
self.log.info('Successfully get access token from github using code %s' % code)
user_info = self.get_user_info(access_to... | Sign in with github docs: https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow .. notes:: | GithubLogin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GithubLogin:
"""Sign in with github docs: https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow .. notes::"""
def login(self, context):
"""github Login :type context: Context :param context: :rtype: dict :return: token and instance of user... | stack_v2_sparse_classes_10k_train_002064 | 17,886 | permissive | [
{
"docstring": "github Login :type context: Context :param context: :rtype: dict :return: token and instance of user",
"name": "login",
"signature": "def login(self, context)"
},
{
"docstring": "Get github access token :type code: str :param code: :rtype: str :return: access token",
"name": ... | 4 | stack_v2_sparse_classes_30k_train_004253 | Implement the Python class `GithubLogin` described below.
Class description:
Sign in with github docs: https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow .. notes::
Method signatures and docstrings:
- def login(self, context): github Login :type context: Context :param ... | Implement the Python class `GithubLogin` described below.
Class description:
Sign in with github docs: https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow .. notes::
Method signatures and docstrings:
- def login(self, context): github Login :type context: Context :param ... | 945c4fd2755f5b0dea11e54eb649eeb37ec93d01 | <|skeleton|>
class GithubLogin:
"""Sign in with github docs: https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow .. notes::"""
def login(self, context):
"""github Login :type context: Context :param context: :rtype: dict :return: token and instance of user... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GithubLogin:
"""Sign in with github docs: https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow .. notes::"""
def login(self, context):
"""github Login :type context: Context :param context: :rtype: dict :return: token and instance of user"""
s... | the_stack_v2_python_sparse | open-hackathon-server/src/hackathon/user/oauth_login.py | kaiyuanshe/open-hackathon | train | 46 |
65210560a0a1e25f94576bc2336c13b7e5bee31a | [
"self.parent = parent\nself.power = power\nself.isPhysical = isPhysical\nself.pierce = pierce",
"damage = super(PierceDodge2XDelegate, self).coreDamage(user, target)\nif target.dodge == self.pierce:\n return 2 * damage\nelse:\n return damage"
] | <|body_start_0|>
self.parent = parent
self.power = power
self.isPhysical = isPhysical
self.pierce = pierce
<|end_body_0|>
<|body_start_1|>
damage = super(PierceDodge2XDelegate, self).coreDamage(user, target)
if target.dodge == self.pierce:
return 2 * damage
... | Represents an attack whose damage is doubled when used against an opponent dodging in a certain manner | PierceDodge2XDelegate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PierceDodge2XDelegate:
"""Represents an attack whose damage is doubled when used against an opponent dodging in a certain manner"""
def __init__(self, parent, power, isPhysical, pierce):
"""Build the Damage Delegate with the dodge it pierces"""
<|body_0|>
def coreDamage(... | stack_v2_sparse_classes_10k_train_002065 | 842 | no_license | [
{
"docstring": "Build the Damage Delegate with the dodge it pierces",
"name": "__init__",
"signature": "def __init__(self, parent, power, isPhysical, pierce)"
},
{
"docstring": "Doubles the damage when the opponent is dodging in the manner that is pierced",
"name": "coreDamage",
"signatu... | 2 | null | Implement the Python class `PierceDodge2XDelegate` described below.
Class description:
Represents an attack whose damage is doubled when used against an opponent dodging in a certain manner
Method signatures and docstrings:
- def __init__(self, parent, power, isPhysical, pierce): Build the Damage Delegate with the do... | Implement the Python class `PierceDodge2XDelegate` described below.
Class description:
Represents an attack whose damage is doubled when used against an opponent dodging in a certain manner
Method signatures and docstrings:
- def __init__(self, parent, power, isPhysical, pierce): Build the Damage Delegate with the do... | 3931eee5fd04e18bb1738a0b27a4c6979dc4db01 | <|skeleton|>
class PierceDodge2XDelegate:
"""Represents an attack whose damage is doubled when used against an opponent dodging in a certain manner"""
def __init__(self, parent, power, isPhysical, pierce):
"""Build the Damage Delegate with the dodge it pierces"""
<|body_0|>
def coreDamage(... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PierceDodge2XDelegate:
"""Represents an attack whose damage is doubled when used against an opponent dodging in a certain manner"""
def __init__(self, parent, power, isPhysical, pierce):
"""Build the Damage Delegate with the dodge it pierces"""
self.parent = parent
self.power = po... | the_stack_v2_python_sparse | src/Battle/Attack/DamageDelegates/piercedodge_2Xdelegate.py | sgtnourry/Pokemon-Project | train | 0 |
7a699bb81e9b9652baf9a288f1bd2fcfd2a70fe7 | [
"LOGGER.info('Importing CDK...')\nfrom aws_cdk.core import App\nfrom pcluster.templates.cdk_artifacts_manager import CDKArtifactsManager\nfrom pcluster.templates.cluster_stack import ClusterCdkStack\nLOGGER.info('CDK import completed successfully')\nLOGGER.info('Starting CDK template generation...')\nwith tempfile.... | <|body_start_0|>
LOGGER.info('Importing CDK...')
from aws_cdk.core import App
from pcluster.templates.cdk_artifacts_manager import CDKArtifactsManager
from pcluster.templates.cluster_stack import ClusterCdkStack
LOGGER.info('CDK import completed successfully')
LOGGER.info... | Create the template, starting from the given resources. | CDKTemplateBuilder | [
"Python-2.0",
"GPL-1.0-or-later",
"MPL-2.0",
"MIT",
"LicenseRef-scancode-python-cwi",
"BSD-3-Clause",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"MIT-0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CDKTemplateBuilder:
"""Create the template, starting from the given resources."""
def build_cluster_template(cluster_config: BaseClusterConfig, bucket: S3Bucket, stack_name: str, log_group_name: str=None):
"""Build template for the given cluster and return as output in Yaml format.""... | stack_v2_sparse_classes_10k_train_002066 | 3,232 | permissive | [
{
"docstring": "Build template for the given cluster and return as output in Yaml format.",
"name": "build_cluster_template",
"signature": "def build_cluster_template(cluster_config: BaseClusterConfig, bucket: S3Bucket, stack_name: str, log_group_name: str=None)"
},
{
"docstring": "Build templat... | 2 | stack_v2_sparse_classes_30k_train_002831 | Implement the Python class `CDKTemplateBuilder` described below.
Class description:
Create the template, starting from the given resources.
Method signatures and docstrings:
- def build_cluster_template(cluster_config: BaseClusterConfig, bucket: S3Bucket, stack_name: str, log_group_name: str=None): Build template for... | Implement the Python class `CDKTemplateBuilder` described below.
Class description:
Create the template, starting from the given resources.
Method signatures and docstrings:
- def build_cluster_template(cluster_config: BaseClusterConfig, bucket: S3Bucket, stack_name: str, log_group_name: str=None): Build template for... | a213978a09ea7fc80855bf55c539861ea95259f9 | <|skeleton|>
class CDKTemplateBuilder:
"""Create the template, starting from the given resources."""
def build_cluster_template(cluster_config: BaseClusterConfig, bucket: S3Bucket, stack_name: str, log_group_name: str=None):
"""Build template for the given cluster and return as output in Yaml format.""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CDKTemplateBuilder:
"""Create the template, starting from the given resources."""
def build_cluster_template(cluster_config: BaseClusterConfig, bucket: S3Bucket, stack_name: str, log_group_name: str=None):
"""Build template for the given cluster and return as output in Yaml format."""
LOG... | the_stack_v2_python_sparse | cli/src/pcluster/templates/cdk_builder.py | aws/aws-parallelcluster | train | 520 |
ebe0d2a359bd04434f81a606ddb1f32b57802455 | [
"cred_json = config.get('credentials')\ncreds = Credentials(token=cred_json.get('access_token'), refresh_token=cred_json.get('refresh_token'), token_uri=cred_json.get('token_uri'), client_id=cred_json.get('client_id'), client_secret=cred_json.get('client_secret'))\nreturn creds",
"try:\n dbm_service = build('d... | <|body_start_0|>
cred_json = config.get('credentials')
creds = Credentials(token=cred_json.get('access_token'), refresh_token=cred_json.get('refresh_token'), token_uri=cred_json.get('token_uri'), client_id=cred_json.get('client_id'), client_secret=cred_json.get('client_secret'))
return creds
<|e... | SourceDV360 | [
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"Elastic-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SourceDV360:
def get_credentials(self, config: json) -> Credentials:
"""Get the credentials from the config file and returns them as a Credentials object"""
<|body_0|>
def check_connection(self, logger: AirbyteLogger, config: Mapping[str, Any]) -> Tuple[bool, any]:
"... | stack_v2_sparse_classes_10k_train_002067 | 6,990 | permissive | [
{
"docstring": "Get the credentials from the config file and returns them as a Credentials object",
"name": "get_credentials",
"signature": "def get_credentials(self, config: json) -> Credentials"
},
{
"docstring": "Tests if the input configuration can be used to successfully connect to the inte... | 4 | null | Implement the Python class `SourceDV360` described below.
Class description:
Implement the SourceDV360 class.
Method signatures and docstrings:
- def get_credentials(self, config: json) -> Credentials: Get the credentials from the config file and returns them as a Credentials object
- def check_connection(self, logge... | Implement the Python class `SourceDV360` described below.
Class description:
Implement the SourceDV360 class.
Method signatures and docstrings:
- def get_credentials(self, config: json) -> Credentials: Get the credentials from the config file and returns them as a Credentials object
- def check_connection(self, logge... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class SourceDV360:
def get_credentials(self, config: json) -> Credentials:
"""Get the credentials from the config file and returns them as a Credentials object"""
<|body_0|>
def check_connection(self, logger: AirbyteLogger, config: Mapping[str, Any]) -> Tuple[bool, any]:
"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SourceDV360:
def get_credentials(self, config: json) -> Credentials:
"""Get the credentials from the config file and returns them as a Credentials object"""
cred_json = config.get('credentials')
creds = Credentials(token=cred_json.get('access_token'), refresh_token=cred_json.get('refre... | the_stack_v2_python_sparse | dts/airbyte/airbyte-integrations/connectors/source-dv-360/source_dv_360/source.py | alldatacenter/alldata | train | 774 | |
30f24c40e4429291c0d9e381ce82308c89c7e9ec | [
"obj = None\nif self.is_view:\n try:\n obj = self.workflow.views.get(pk=self.kwargs.get('pk'))\n except ObjectDoesNotExist:\n raise http.Http404(_('No view found matching the query.'))\nreturn obj",
"obj = self.get_object()\nformula = None\nif obj:\n formula = obj.formula\n col_names = [... | <|body_start_0|>
obj = None
if self.is_view:
try:
obj = self.workflow.views.get(pk=self.kwargs.get('pk'))
except ObjectDoesNotExist:
raise http.Http404(_('No view found matching the query.'))
return obj
<|end_body_0|>
<|body_start_1|>
... | TableCSVDownloadView | [
"LGPL-2.0-or-later",
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"LGPL-2.1-only",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TableCSVDownloadView:
def get_object(self, queryset=None):
"""Get view from the workflow (if stats for view) or nothing."""
<|body_0|>
def get(self, request, *args, **kwargs):
"""Return the download response for the table/view"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_10k_train_002068 | 1,461 | permissive | [
{
"docstring": "Get view from the workflow (if stats for view) or nothing.",
"name": "get_object",
"signature": "def get_object(self, queryset=None)"
},
{
"docstring": "Return the download response for the table/view",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"... | 2 | null | Implement the Python class `TableCSVDownloadView` described below.
Class description:
Implement the TableCSVDownloadView class.
Method signatures and docstrings:
- def get_object(self, queryset=None): Get view from the workflow (if stats for view) or nothing.
- def get(self, request, *args, **kwargs): Return the down... | Implement the Python class `TableCSVDownloadView` described below.
Class description:
Implement the TableCSVDownloadView class.
Method signatures and docstrings:
- def get_object(self, queryset=None): Get view from the workflow (if stats for view) or nothing.
- def get(self, request, *args, **kwargs): Return the down... | c432745dfff932cbe7397100422d49df78f0a882 | <|skeleton|>
class TableCSVDownloadView:
def get_object(self, queryset=None):
"""Get view from the workflow (if stats for view) or nothing."""
<|body_0|>
def get(self, request, *args, **kwargs):
"""Return the download response for the table/view"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TableCSVDownloadView:
def get_object(self, queryset=None):
"""Get view from the workflow (if stats for view) or nothing."""
obj = None
if self.is_view:
try:
obj = self.workflow.views.get(pk=self.kwargs.get('pk'))
except ObjectDoesNotExist:
... | the_stack_v2_python_sparse | ontask/table/views/csvdownload.py | abelardopardo/ontask_b | train | 43 | |
a3fbdbbd0a271444bc64277451b26f429a8aa77b | [
"if not isinstance(args[0], PolarDiagram):\n super().plot(*args, **kwargs)\n return\npd = args[0]\nlabels, slices, info = pd.get_slices(ws, n_steps, full_info=True)\n_configure_axes(self, labels, colors, show_legend, legend_kw, **kwargs)\n_plot(self, slices, info, False, use_convex_hull, **kwargs)",
"if not... | <|body_start_0|>
if not isinstance(args[0], PolarDiagram):
super().plot(*args, **kwargs)
return
pd = args[0]
labels, slices, info = pd.get_slices(ws, n_steps, full_info=True)
_configure_axes(self, labels, colors, show_legend, legend_kw, **kwargs)
_plot(sel... | Projection to plot given data in a rectilinear plot. | HROFlat | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HROFlat:
"""Projection to plot given data in a rectilinear plot."""
def plot(self, *args, ws=None, n_steps=None, colors=('green', 'red'), show_legend=False, legend_kw=None, use_convex_hull=False, **kwargs):
"""Plots the given data in a rectilinear plot. Otherwise, it works identical ... | stack_v2_sparse_classes_10k_train_002069 | 23,221 | permissive | [
{
"docstring": "Plots the given data in a rectilinear plot. Otherwise, it works identical to `HROPolar.plot`. See also ---------- `HROPolar.plot`",
"name": "plot",
"signature": "def plot(self, *args, ws=None, n_steps=None, colors=('green', 'red'), show_legend=False, legend_kw=None, use_convex_hull=False... | 2 | stack_v2_sparse_classes_30k_train_001852 | Implement the Python class `HROFlat` described below.
Class description:
Projection to plot given data in a rectilinear plot.
Method signatures and docstrings:
- def plot(self, *args, ws=None, n_steps=None, colors=('green', 'red'), show_legend=False, legend_kw=None, use_convex_hull=False, **kwargs): Plots the given d... | Implement the Python class `HROFlat` described below.
Class description:
Projection to plot given data in a rectilinear plot.
Method signatures and docstrings:
- def plot(self, *args, ws=None, n_steps=None, colors=('green', 'red'), show_legend=False, legend_kw=None, use_convex_hull=False, **kwargs): Plots the given d... | 921536e2db7a9635c539a8dc2a97d1411e58c2a1 | <|skeleton|>
class HROFlat:
"""Projection to plot given data in a rectilinear plot."""
def plot(self, *args, ws=None, n_steps=None, colors=('green', 'red'), show_legend=False, legend_kw=None, use_convex_hull=False, **kwargs):
"""Plots the given data in a rectilinear plot. Otherwise, it works identical ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HROFlat:
"""Projection to plot given data in a rectilinear plot."""
def plot(self, *args, ws=None, n_steps=None, colors=('green', 'red'), show_legend=False, legend_kw=None, use_convex_hull=False, **kwargs):
"""Plots the given data in a rectilinear plot. Otherwise, it works identical to `HROPolar.... | the_stack_v2_python_sparse | hrosailing/plotting/projections.py | hrosailing/hrosailing | train | 17 |
6491a8498e4b72cf6ff9c754788ab538dc74c2f7 | [
"self.is_mail_enabled = is_mail_enabled\nself.is_security_enabled = is_security_enabled\nself.member_count = member_count\nself.visibility = visibility",
"if dictionary is None:\n return None\nis_mail_enabled = dictionary.get('isMailEnabled')\nis_security_enabled = dictionary.get('isSecurityEnabled')\nmember_c... | <|body_start_0|>
self.is_mail_enabled = is_mail_enabled
self.is_security_enabled = is_security_enabled
self.member_count = member_count
self.visibility = visibility
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
is_mail_enabled = dictionar... | Implementation of the 'Office365GroupInfo' model. Specifies information about a M365 Group. Attributes: is_mail_enabled (bool): Specifies whether the Group is mail enabled. Mail enabled groups are used within Microsoft to distribute messages. is_security_enabled (bool): Specifies whether the Group is security enabled. ... | Office365GroupInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Office365GroupInfo:
"""Implementation of the 'Office365GroupInfo' model. Specifies information about a M365 Group. Attributes: is_mail_enabled (bool): Specifies whether the Group is mail enabled. Mail enabled groups are used within Microsoft to distribute messages. is_security_enabled (bool): Spe... | stack_v2_sparse_classes_10k_train_002070 | 2,486 | permissive | [
{
"docstring": "Constructor for the Office365GroupInfo class",
"name": "__init__",
"signature": "def __init__(self, is_mail_enabled=None, is_security_enabled=None, member_count=None, visibility=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictio... | 2 | stack_v2_sparse_classes_30k_train_006654 | Implement the Python class `Office365GroupInfo` described below.
Class description:
Implementation of the 'Office365GroupInfo' model. Specifies information about a M365 Group. Attributes: is_mail_enabled (bool): Specifies whether the Group is mail enabled. Mail enabled groups are used within Microsoft to distribute me... | Implement the Python class `Office365GroupInfo` described below.
Class description:
Implementation of the 'Office365GroupInfo' model. Specifies information about a M365 Group. Attributes: is_mail_enabled (bool): Specifies whether the Group is mail enabled. Mail enabled groups are used within Microsoft to distribute me... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class Office365GroupInfo:
"""Implementation of the 'Office365GroupInfo' model. Specifies information about a M365 Group. Attributes: is_mail_enabled (bool): Specifies whether the Group is mail enabled. Mail enabled groups are used within Microsoft to distribute messages. is_security_enabled (bool): Spe... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Office365GroupInfo:
"""Implementation of the 'Office365GroupInfo' model. Specifies information about a M365 Group. Attributes: is_mail_enabled (bool): Specifies whether the Group is mail enabled. Mail enabled groups are used within Microsoft to distribute messages. is_security_enabled (bool): Specifies whethe... | the_stack_v2_python_sparse | cohesity_management_sdk/models/office_365_group_info.py | cohesity/management-sdk-python | train | 24 |
58de6955ee9c4d906e62ea1f588f5c63e79e8355 | [
"super(TwoLayerNet, self).__init__()\nself.linear1 = torch.nn.Linear(D_in, H)\nself.linear2 = torch.nn.Linear(H, D_out)",
"h_relu = self.linear1(x).clamp(min=0)\ny_pred = self.linear2(h_relu).clamp(min=0)\nreturn y_pred"
] | <|body_start_0|>
super(TwoLayerNet, self).__init__()
self.linear1 = torch.nn.Linear(D_in, H)
self.linear2 = torch.nn.Linear(H, D_out)
<|end_body_0|>
<|body_start_1|>
h_relu = self.linear1(x).clamp(min=0)
y_pred = self.linear2(h_relu).clamp(min=0)
return y_pred
<|end_body... | TwoLayerNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwoLayerNet:
def __init__(self, D_in, H, D_out):
"""In the constructor we instantiate two nn.Linear modules and assign them as member variables."""
<|body_0|>
def forward(self, x):
"""In the forward function we accept a Tensor of input data and we must return a Tenso... | stack_v2_sparse_classes_10k_train_002071 | 1,096 | no_license | [
{
"docstring": "In the constructor we instantiate two nn.Linear modules and assign them as member variables.",
"name": "__init__",
"signature": "def __init__(self, D_in, H, D_out)"
},
{
"docstring": "In the forward function we accept a Tensor of input data and we must return a Tensor of output d... | 2 | stack_v2_sparse_classes_30k_train_002394 | Implement the Python class `TwoLayerNet` described below.
Class description:
Implement the TwoLayerNet class.
Method signatures and docstrings:
- def __init__(self, D_in, H, D_out): In the constructor we instantiate two nn.Linear modules and assign them as member variables.
- def forward(self, x): In the forward func... | Implement the Python class `TwoLayerNet` described below.
Class description:
Implement the TwoLayerNet class.
Method signatures and docstrings:
- def __init__(self, D_in, H, D_out): In the constructor we instantiate two nn.Linear modules and assign them as member variables.
- def forward(self, x): In the forward func... | e1b46706c09c1989513794fb9a456ebbdbae4986 | <|skeleton|>
class TwoLayerNet:
def __init__(self, D_in, H, D_out):
"""In the constructor we instantiate two nn.Linear modules and assign them as member variables."""
<|body_0|>
def forward(self, x):
"""In the forward function we accept a Tensor of input data and we must return a Tenso... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TwoLayerNet:
def __init__(self, D_in, H, D_out):
"""In the constructor we instantiate two nn.Linear modules and assign them as member variables."""
super(TwoLayerNet, self).__init__()
self.linear1 = torch.nn.Linear(D_in, H)
self.linear2 = torch.nn.Linear(H, D_out)
def forw... | the_stack_v2_python_sparse | twolayernetog.py | weekend37/BG_Competition | train | 2 | |
54ebebd9743d02d1010166895bb95a2b63a8a954 | [
"self.safe_update(**kwargs)\nif butler is not None:\n self.log.warn('Ignoring butler in extract()')\ndtables = stack_summary_table(data, self, tablename='outliers', keep_cols=['nbad_total', 'nbad_rows', 'nbad_cols', 'slot', 'amp'])\nreturn dtables",
"self.safe_update(**kwargs)\nconfig_table = get_run_config_ta... | <|body_start_0|>
self.safe_update(**kwargs)
if butler is not None:
self.log.warn('Ignoring butler in extract()')
dtables = stack_summary_table(data, self, tablename='outliers', keep_cols=['nbad_total', 'nbad_rows', 'nbad_cols', 'slot', 'amp'])
return dtables
<|end_body_0|>
<... | Summarize the results for the superbias outlier analysis | SuperdarkOutlierSummaryTask | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuperdarkOutlierSummaryTask:
"""Summarize the results for the superbias outlier analysis"""
def extract(self, butler, data, **kwargs):
"""Make a summry table of the bias FFT data Parameters ---------- butler : `Butler` The data butler data : `dict` Dictionary (or other structure) con... | stack_v2_sparse_classes_10k_train_002072 | 14,784 | permissive | [
{
"docstring": "Make a summry table of the bias FFT data Parameters ---------- butler : `Butler` The data butler data : `dict` Dictionary (or other structure) contain the input data kwargs Used to override default configuration Returns ------- dtables : `TableDict` The resulting data",
"name": "extract",
... | 2 | stack_v2_sparse_classes_30k_train_001710 | Implement the Python class `SuperdarkOutlierSummaryTask` described below.
Class description:
Summarize the results for the superbias outlier analysis
Method signatures and docstrings:
- def extract(self, butler, data, **kwargs): Make a summry table of the bias FFT data Parameters ---------- butler : `Butler` The data... | Implement the Python class `SuperdarkOutlierSummaryTask` described below.
Class description:
Summarize the results for the superbias outlier analysis
Method signatures and docstrings:
- def extract(self, butler, data, **kwargs): Make a summry table of the bias FFT data Parameters ---------- butler : `Butler` The data... | 28418284fdaf2b2fb0afbeccd4324f7ad3e676c8 | <|skeleton|>
class SuperdarkOutlierSummaryTask:
"""Summarize the results for the superbias outlier analysis"""
def extract(self, butler, data, **kwargs):
"""Make a summry table of the bias FFT data Parameters ---------- butler : `Butler` The data butler data : `dict` Dictionary (or other structure) con... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SuperdarkOutlierSummaryTask:
"""Summarize the results for the superbias outlier analysis"""
def extract(self, butler, data, **kwargs):
"""Make a summry table of the bias FFT data Parameters ---------- butler : `Butler` The data butler data : `dict` Dictionary (or other structure) contain the inpu... | the_stack_v2_python_sparse | python/lsst/eo_utils/dark/superdark.py | lsst-camera-dh/EO-utilities | train | 2 |
4d4e5337c55330fd7332f95f996fd795cdb63d52 | [
"if not prices:\n return 0\nn = len(prices)\ndp = [[0] * 2 for _ in range(n)]\ndp[0][0] = 0\ndp[0][1] = -prices[0]\nfor i in range(1, n):\n dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i])\n dp[i][1] = max(dp[i - 1][1], -prices[i])\nreturn dp[n - 1][0]",
"if not prices:\n return 0\nn = len(price... | <|body_start_0|>
if not prices:
return 0
n = len(prices)
dp = [[0] * 2 for _ in range(n)]
dp[0][0] = 0
dp[0][1] = -prices[0]
for i in range(1, n):
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i])
dp[i][1] = max(dp[i - 1][1], -pric... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
... | stack_v2_sparse_classes_10k_train_002073 | 1,963 | no_license | [
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
},
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
},
{
"docstring": ":type prices: List[int... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit(self, prices): :type prices: L... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit(self, prices): :type prices: L... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
if not prices:
return 0
n = len(prices)
dp = [[0] * 2 for _ in range(n)]
dp[0][0] = 0
dp[0][1] = -prices[0]
for i in range(1, n):
dp[i][0] = max(dp[i... | the_stack_v2_python_sparse | 0121_Best_Time_to_Buy_and_Sell_Stock.py | bingli8802/leetcode | train | 0 | |
4e39c062fb33e2f8a77f52961eef1c3eb7c4fd7a | [
"from atom import Atom\nself._center = Atom('atomic')\nself._center.position = center\nself._radius = radius",
"distance_from_surface = abs(self._radius - distance(atom, self._center))\nif distance_from_surface <= cutoff_distance:\n return True\nelse:\n return False",
"distance_from_center = distance(atom... | <|body_start_0|>
from atom import Atom
self._center = Atom('atomic')
self._center.position = center
self._radius = radius
<|end_body_0|>
<|body_start_1|>
distance_from_surface = abs(self._radius - distance(atom, self._center))
if distance_from_surface <= cutoff_distance:... | Write Later | Sphere | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sphere:
"""Write Later"""
def __init__(self, center, radius):
"""Write Later"""
<|body_0|>
def nearest_neighbor(self, atom, cutoff_distance):
"""Write Later"""
<|body_1|>
def in_shape(self, atom):
"""Write Later"""
<|body_2|>
def... | stack_v2_sparse_classes_10k_train_002074 | 8,615 | no_license | [
{
"docstring": "Write Later",
"name": "__init__",
"signature": "def __init__(self, center, radius)"
},
{
"docstring": "Write Later",
"name": "nearest_neighbor",
"signature": "def nearest_neighbor(self, atom, cutoff_distance)"
},
{
"docstring": "Write Later",
"name": "in_shape... | 4 | stack_v2_sparse_classes_30k_train_000276 | Implement the Python class `Sphere` described below.
Class description:
Write Later
Method signatures and docstrings:
- def __init__(self, center, radius): Write Later
- def nearest_neighbor(self, atom, cutoff_distance): Write Later
- def in_shape(self, atom): Write Later
- def random_position_on_surface(self, cutoff... | Implement the Python class `Sphere` described below.
Class description:
Write Later
Method signatures and docstrings:
- def __init__(self, center, radius): Write Later
- def nearest_neighbor(self, atom, cutoff_distance): Write Later
- def in_shape(self, atom): Write Later
- def random_position_on_surface(self, cutoff... | 602c292f30398fd7f80accce6b436af3799b00c9 | <|skeleton|>
class Sphere:
"""Write Later"""
def __init__(self, center, radius):
"""Write Later"""
<|body_0|>
def nearest_neighbor(self, atom, cutoff_distance):
"""Write Later"""
<|body_1|>
def in_shape(self, atom):
"""Write Later"""
<|body_2|>
def... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Sphere:
"""Write Later"""
def __init__(self, center, radius):
"""Write Later"""
from atom import Atom
self._center = Atom('atomic')
self._center.position = center
self._radius = radius
def nearest_neighbor(self, atom, cutoff_distance):
"""Write Later""... | the_stack_v2_python_sparse | space.py | drzeus99/lmpsdata2 | train | 0 |
ece465c4868815509ae5749ddab7226c9444c522 | [
"n = 0\nt = head\nwhile t:\n n += 1\n t = t.next\nmid = n // 2\nphead = head\nfor _ in range(mid):\n phead = phead.next\np = phead\nq = phead.next\nphead.next = None\nwhile q:\n r = q.next\n q.next = p\n p = q\n q = r\nfor _ in range(mid):\n if head.val != p.val:\n return False\n h... | <|body_start_0|>
n = 0
t = head
while t:
n += 1
t = t.next
mid = n // 2
phead = head
for _ in range(mid):
phead = phead.next
p = phead
q = phead.next
phead.next = None
while q:
r = q.next
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome(self, head):
"""时间复杂度:O(n) 空间复杂度:O(1) :param head: :return:"""
<|body_0|>
def isPalindrome_3(self, head):
"""利用辅助空间 :type head: ListNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = 0
t = head
... | stack_v2_sparse_classes_10k_train_002075 | 1,798 | no_license | [
{
"docstring": "时间复杂度:O(n) 空间复杂度:O(1) :param head: :return:",
"name": "isPalindrome",
"signature": "def isPalindrome(self, head)"
},
{
"docstring": "利用辅助空间 :type head: ListNode :rtype: bool",
"name": "isPalindrome_3",
"signature": "def isPalindrome_3(self, head)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, head): 时间复杂度:O(n) 空间复杂度:O(1) :param head: :return:
- def isPalindrome_3(self, head): 利用辅助空间 :type head: ListNode :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, head): 时间复杂度:O(n) 空间复杂度:O(1) :param head: :return:
- def isPalindrome_3(self, head): 利用辅助空间 :type head: ListNode :rtype: bool
<|skeleton|>
class Solution:... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def isPalindrome(self, head):
"""时间复杂度:O(n) 空间复杂度:O(1) :param head: :return:"""
<|body_0|>
def isPalindrome_3(self, head):
"""利用辅助空间 :type head: ListNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isPalindrome(self, head):
"""时间复杂度:O(n) 空间复杂度:O(1) :param head: :return:"""
n = 0
t = head
while t:
n += 1
t = t.next
mid = n // 2
phead = head
for _ in range(mid):
phead = phead.next
p = phead
... | the_stack_v2_python_sparse | 234_回文链表.py | lovehhf/LeetCode | train | 0 | |
ef473b65772d1e5a6fdc756a8353b6bb9e6c6d71 | [
"super(DisneyBlock, self).__init__()\nself.f1z = torch.nn.Linear(zD, outD, bias=True)\nself.f1o = torch.nn.Linear(oD, outD, bias=True)\nself.f2 = torch.nn.Linear(outD, outD, bias=True)\nself.activation = torch.nn.ReLU()",
"out = self.f1o(o).add_(self.f1z(z))\nout = self.activation(out)\nout = self.f2(out)\nout = ... | <|body_start_0|>
super(DisneyBlock, self).__init__()
self.f1z = torch.nn.Linear(zD, outD, bias=True)
self.f1o = torch.nn.Linear(oD, outD, bias=True)
self.f2 = torch.nn.Linear(outD, outD, bias=True)
self.activation = torch.nn.ReLU()
<|end_body_0|>
<|body_start_1|>
out = s... | DisneyBlock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DisneyBlock:
def __init__(self, oD, zD, outD):
""":param oD: Dimension of output of the previous block :param zD: Dimension of one layer of hierarchical descriptor :param outD: Dimension of ouput of current block"""
<|body_0|>
def forward(self, o, z):
""":param o: ou... | stack_v2_sparse_classes_10k_train_002076 | 949 | permissive | [
{
"docstring": ":param oD: Dimension of output of the previous block :param zD: Dimension of one layer of hierarchical descriptor :param outD: Dimension of ouput of current block",
"name": "__init__",
"signature": "def __init__(self, oD, zD, outD)"
},
{
"docstring": ":param o: output of the prev... | 2 | stack_v2_sparse_classes_30k_train_000501 | Implement the Python class `DisneyBlock` described below.
Class description:
Implement the DisneyBlock class.
Method signatures and docstrings:
- def __init__(self, oD, zD, outD): :param oD: Dimension of output of the previous block :param zD: Dimension of one layer of hierarchical descriptor :param outD: Dimension o... | Implement the Python class `DisneyBlock` described below.
Class description:
Implement the DisneyBlock class.
Method signatures and docstrings:
- def __init__(self, oD, zD, outD): :param oD: Dimension of output of the previous block :param zD: Dimension of one layer of hierarchical descriptor :param outD: Dimension o... | eeb490b5e6afd7f05049c8aca90a5c2e6f253726 | <|skeleton|>
class DisneyBlock:
def __init__(self, oD, zD, outD):
""":param oD: Dimension of output of the previous block :param zD: Dimension of one layer of hierarchical descriptor :param outD: Dimension of ouput of current block"""
<|body_0|>
def forward(self, o, z):
""":param o: ou... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DisneyBlock:
def __init__(self, oD, zD, outD):
""":param oD: Dimension of output of the previous block :param zD: Dimension of one layer of hierarchical descriptor :param outD: Dimension of ouput of current block"""
super(DisneyBlock, self).__init__()
self.f1z = torch.nn.Linear(zD, out... | the_stack_v2_python_sparse | DeepestScatter_Train/Disney/DisneyBlock.py | marsermd/DeepestScatter | train | 15 | |
d4d6e81a1e4182c269cdaac531e29d97b4ce5c53 | [
"mask_changed = False\nzero_positions = get_zero_positions_in_binary_mask(input_mask_list[0])\nif zero_positions:\n original_out_mask = output_mask_list[0]\n output_mask_list[0] = input_mask_list[0]\n if output_mask_list[0] != original_out_mask:\n mask_changed = True\n logger.debug('Direct Co... | <|body_start_0|>
mask_changed = False
zero_positions = get_zero_positions_in_binary_mask(input_mask_list[0])
if zero_positions:
original_out_mask = output_mask_list[0]
output_mask_list[0] = input_mask_list[0]
if output_mask_list[0] != original_out_mask:
... | Models DIRECT internal connectivity for an Op. | DirectInternalConnectivity | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DirectInternalConnectivity:
"""Models DIRECT internal connectivity for an Op."""
def forward_propagate_the_masks(self, input_mask_list: List[List[int]], output_mask_list: List[List[int]]) -> bool:
"""Based on the internal connectivity and input mask(s), updates the output mask(s). :p... | stack_v2_sparse_classes_10k_train_002077 | 39,659 | permissive | [
{
"docstring": "Based on the internal connectivity and input mask(s), updates the output mask(s). :param input_mask_list: The input mask(s) to be propagated :param output_mask_list: The output mask(s) to be updated based on the Op's Internal Connectivity",
"name": "forward_propagate_the_masks",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_000008 | Implement the Python class `DirectInternalConnectivity` described below.
Class description:
Models DIRECT internal connectivity for an Op.
Method signatures and docstrings:
- def forward_propagate_the_masks(self, input_mask_list: List[List[int]], output_mask_list: List[List[int]]) -> bool: Based on the internal conne... | Implement the Python class `DirectInternalConnectivity` described below.
Class description:
Models DIRECT internal connectivity for an Op.
Method signatures and docstrings:
- def forward_propagate_the_masks(self, input_mask_list: List[List[int]], output_mask_list: List[List[int]]) -> bool: Based on the internal conne... | 5a406e657082b6a4f6e4bf48f0e46e085cb1e351 | <|skeleton|>
class DirectInternalConnectivity:
"""Models DIRECT internal connectivity for an Op."""
def forward_propagate_the_masks(self, input_mask_list: List[List[int]], output_mask_list: List[List[int]]) -> bool:
"""Based on the internal connectivity and input mask(s), updates the output mask(s). :p... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DirectInternalConnectivity:
"""Models DIRECT internal connectivity for an Op."""
def forward_propagate_the_masks(self, input_mask_list: List[List[int]], output_mask_list: List[List[int]]) -> bool:
"""Based on the internal connectivity and input mask(s), updates the output mask(s). :param input_ma... | the_stack_v2_python_sparse | TrainingExtensions/common/src/python/aimet_common/winnow/mask.py | quic/aimet | train | 1,676 |
f7b0d716b3202ae85f8593e8e999a52f1a143b04 | [
"timestamp = self._GetRowValue(query_hash, row, value_name)\nif timestamp is None:\n return None\nreturn dfdatetime_cocoa_time.CocoaTime(timestamp=timestamp)",
"query_hash = hash(query)\nevent_data = IOSDatausageEventData()\nevent_data.bundle_identifier = self._GetRowValue(query_hash, row, 'ZBUNDLENAME')\neven... | <|body_start_0|>
timestamp = self._GetRowValue(query_hash, row, value_name)
if timestamp is None:
return None
return dfdatetime_cocoa_time.CocoaTime(timestamp=timestamp)
<|end_body_0|>
<|body_start_1|>
query_hash = hash(query)
event_data = IOSDatausageEventData()
... | SQLite parser plugin for iOS DataUsage database. | IOSDatausagePlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IOSDatausagePlugin:
"""SQLite parser plugin for iOS DataUsage database."""
def _GetTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row. ro... | stack_v2_sparse_classes_10k_train_002078 | 4,379 | permissive | [
{
"docstring": "Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row. row (sqlite3.Row): row. value_name (str): name of the value. Returns: dfdatetime.CocoaTime: date and time value or None if not available.",
"name... | 2 | null | Implement the Python class `IOSDatausagePlugin` described below.
Class description:
SQLite parser plugin for iOS DataUsage database.
Method signatures and docstrings:
- def _GetTimeRowValue(self, query_hash, row, value_name): Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, tha... | Implement the Python class `IOSDatausagePlugin` described below.
Class description:
SQLite parser plugin for iOS DataUsage database.
Method signatures and docstrings:
- def _GetTimeRowValue(self, query_hash, row, value_name): Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, tha... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class IOSDatausagePlugin:
"""SQLite parser plugin for iOS DataUsage database."""
def _GetTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row. ro... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class IOSDatausagePlugin:
"""SQLite parser plugin for iOS DataUsage database."""
def _GetTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row. row (sqlite3.Ro... | the_stack_v2_python_sparse | plaso/parsers/sqlite_plugins/ios_datausage.py | log2timeline/plaso | train | 1,506 |
0e1c35cd8ab0cbcf2cacc0aae5f3a3d1ecdb0faa | [
"self.page = page\nself.per_page_count = per_page\nself.page_count = page_count\nself.page_url = page_url\npage_show_count = current_page_count\navg_page_count = page_show_count // 2\nself.start_page_show = page - avg_page_count\nself.end_page_show = page + avg_page_count\nif self.start_page_show <= 0:\n self.st... | <|body_start_0|>
self.page = page
self.per_page_count = per_page
self.page_count = page_count
self.page_url = page_url
page_show_count = current_page_count
avg_page_count = page_show_count // 2
self.start_page_show = page - avg_page_count
self.end_page_sho... | Page | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Page:
def __init__(self, page, page_count, page_url, per_page=10, current_page_count=10):
"""初始化分页的所有参数 :param page: :param page_count: :param page_url: :param per_page: :param current_page_count:"""
<|body_0|>
def get_page_show(self):
"""根据初始化的参数拼接page分页 :return:"""... | stack_v2_sparse_classes_10k_train_002079 | 4,235 | no_license | [
{
"docstring": "初始化分页的所有参数 :param page: :param page_count: :param page_url: :param per_page: :param current_page_count:",
"name": "__init__",
"signature": "def __init__(self, page, page_count, page_url, per_page=10, current_page_count=10)"
},
{
"docstring": "根据初始化的参数拼接page分页 :return:",
"name... | 2 | null | Implement the Python class `Page` described below.
Class description:
Implement the Page class.
Method signatures and docstrings:
- def __init__(self, page, page_count, page_url, per_page=10, current_page_count=10): 初始化分页的所有参数 :param page: :param page_count: :param page_url: :param per_page: :param current_page_count... | Implement the Python class `Page` described below.
Class description:
Implement the Page class.
Method signatures and docstrings:
- def __init__(self, page, page_count, page_url, per_page=10, current_page_count=10): 初始化分页的所有参数 :param page: :param page_count: :param page_url: :param per_page: :param current_page_count... | 5a1a6dd59cdd903563389fa7c73a283e8657d731 | <|skeleton|>
class Page:
def __init__(self, page, page_count, page_url, per_page=10, current_page_count=10):
"""初始化分页的所有参数 :param page: :param page_count: :param page_url: :param per_page: :param current_page_count:"""
<|body_0|>
def get_page_show(self):
"""根据初始化的参数拼接page分页 :return:"""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Page:
def __init__(self, page, page_count, page_url, per_page=10, current_page_count=10):
"""初始化分页的所有参数 :param page: :param page_count: :param page_url: :param per_page: :param current_page_count:"""
self.page = page
self.per_page_count = per_page
self.page_count = page_count
... | the_stack_v2_python_sparse | python/Django/20190625/test01/utils/page.py | wjl626nice/1902 | train | 4 | |
1e12abe768d49dc83d9be7a54e613fd872dbd4dd | [
"idx: Dict[int, Dict[str, Union[int, List[int]]]] = {}\nfor i, v in enumerate(numbers):\n if v not in idx:\n idx[v] = {'count': 1, 'index': [i]}\n else:\n idx[v]['count'] += 1\n idx[v]['index'].append(i)\nindex1, index2 = (0, 0)\nfor k in idx.keys():\n dif = target - k\n if dif in i... | <|body_start_0|>
idx: Dict[int, Dict[str, Union[int, List[int]]]] = {}
for i, v in enumerate(numbers):
if v not in idx:
idx[v] = {'count': 1, 'index': [i]}
else:
idx[v]['count'] += 1
idx[v]['index'].append(i)
index1, index2 ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
"""哈希表。"""
<|body_0|>
def twoSum2(self, numbers: List[int], target: int) -> List[int]:
"""二分查找。"""
<|body_1|>
def twoSum3(self, numbers: List[int], target: int) -> List[int]:
... | stack_v2_sparse_classes_10k_train_002080 | 4,429 | no_license | [
{
"docstring": "哈希表。",
"name": "twoSum",
"signature": "def twoSum(self, numbers: List[int], target: int) -> List[int]"
},
{
"docstring": "二分查找。",
"name": "twoSum2",
"signature": "def twoSum2(self, numbers: List[int], target: int) -> List[int]"
},
{
"docstring": "双指针。",
"name"... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, numbers: List[int], target: int) -> List[int]: 哈希表。
- def twoSum2(self, numbers: List[int], target: int) -> List[int]: 二分查找。
- def twoSum3(self, numbers: List[in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, numbers: List[int], target: int) -> List[int]: 哈希表。
- def twoSum2(self, numbers: List[int], target: int) -> List[int]: 二分查找。
- def twoSum3(self, numbers: List[in... | 6932d69353b94ec824dd0ddc86a92453f6673232 | <|skeleton|>
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
"""哈希表。"""
<|body_0|>
def twoSum2(self, numbers: List[int], target: int) -> List[int]:
"""二分查找。"""
<|body_1|>
def twoSum3(self, numbers: List[int], target: int) -> List[int]:
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
"""哈希表。"""
idx: Dict[int, Dict[str, Union[int, List[int]]]] = {}
for i, v in enumerate(numbers):
if v not in idx:
idx[v] = {'count': 1, 'index': [i]}
else:
... | the_stack_v2_python_sparse | 0167_two-sum-ii-input-array-is-sorted.py | Nigirimeshi/leetcode | train | 0 | |
4426b5e70ae0d8dc5d3c3366c1d3be8d8770d09e | [
"logging.Formatter.__init__(self, fmt, datefmt)\nself.technicolor = technicolor\nself._isatty = sys.stderr.isatty()",
"if record.levelno == logging.INFO:\n msg = logging.Formatter.format(self, record)\n return msg\nif self.technicolor and self._isatty:\n colour = self.LEVEL_COLOURS[record.levelno]\n b... | <|body_start_0|>
logging.Formatter.__init__(self, fmt, datefmt)
self.technicolor = technicolor
self._isatty = sys.stderr.isatty()
<|end_body_0|>
<|body_start_1|>
if record.levelno == logging.INFO:
msg = logging.Formatter.format(self, record)
return msg
if... | Intelligent and pretty log formatting. Colourise output to a TTY and prepend logging level name to levels other than INFO. | TechnicolorFormatter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TechnicolorFormatter:
"""Intelligent and pretty log formatting. Colourise output to a TTY and prepend logging level name to levels other than INFO."""
def __init__(self, fmt=None, datefmt=None, technicolor=True):
"""Create new Formatter. Args: fmt (str): A `logging.Formatter` format ... | stack_v2_sparse_classes_10k_train_002081 | 9,687 | permissive | [
{
"docstring": "Create new Formatter. Args: fmt (str): A `logging.Formatter` format string. datefmt (str): `strftime` format string. technicolor (bool): Colourise TTY output?",
"name": "__init__",
"signature": "def __init__(self, fmt=None, datefmt=None, technicolor=True)"
},
{
"docstring": "Form... | 3 | null | Implement the Python class `TechnicolorFormatter` described below.
Class description:
Intelligent and pretty log formatting. Colourise output to a TTY and prepend logging level name to levels other than INFO.
Method signatures and docstrings:
- def __init__(self, fmt=None, datefmt=None, technicolor=True): Create new ... | Implement the Python class `TechnicolorFormatter` described below.
Class description:
Intelligent and pretty log formatting. Colourise output to a TTY and prepend logging level name to levels other than INFO.
Method signatures and docstrings:
- def __init__(self, fmt=None, datefmt=None, technicolor=True): Create new ... | 665d39a2bd82543d5196555f0801ef8fd4a3ee48 | <|skeleton|>
class TechnicolorFormatter:
"""Intelligent and pretty log formatting. Colourise output to a TTY and prepend logging level name to levels other than INFO."""
def __init__(self, fmt=None, datefmt=None, technicolor=True):
"""Create new Formatter. Args: fmt (str): A `logging.Formatter` format ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TechnicolorFormatter:
"""Intelligent and pretty log formatting. Colourise output to a TTY and prepend logging level name to levels other than INFO."""
def __init__(self, fmt=None, datefmt=None, technicolor=True):
"""Create new Formatter. Args: fmt (str): A `logging.Formatter` format string. datef... | the_stack_v2_python_sparse | all-gists/b16f018119ef3fe951af/snippet.py | gistable/gistable | train | 76 |
918bff455975ffdd513038de15195eaf39667f01 | [
"self._list = []\nself._value = {}\nself._length = capacity",
"ans = self._value.get(key)\nif ans is not None:\n self.set(key, ans)\n return ans\nreturn -1",
"if not self._value.get(key):\n if len(self._list) == self._length:\n del self._value[self._list[0]]\n self._list[0:1] = []\nelse:\... | <|body_start_0|>
self._list = []
self._value = {}
self._length = capacity
<|end_body_0|>
<|body_start_1|>
ans = self._value.get(key)
if ans is not None:
self.set(key, ans)
return ans
return -1
<|end_body_1|>
<|body_start_2|>
if not self._... | 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_10k_train_002082 | 869 | 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 | stack_v2_sparse_classes_30k_train_001249 | 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... | bd6b18f134336513bbc3112be6e33c79374a7cb1 | <|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_10k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self._list = []
self._value = {}
self._length = capacity
def get(self, key):
""":rtype: int"""
ans = self._value.get(key)
if ans is not None:
self.set(key, ans)
... | the_stack_v2_python_sparse | python/146. LRU Cache.py | AlisonZXQ/leetcode | train | 1 | |
2393814dd49e482eca8fe96263f8bd409df4b7c4 | [
"visited = {}\nwhile head is not None:\n if head in visited:\n return True\n visited[head] = 1\n head = head.next\nreturn False",
"faster = slow = head\nwhile faster != None and faster.next != None:\n faster = faster.next.next\n slow = slow.next\n if faster == slow:\n return True\n... | <|body_start_0|>
visited = {}
while head is not None:
if head in visited:
return True
visited[head] = 1
head = head.next
return False
<|end_body_0|>
<|body_start_1|>
faster = slow = head
while faster != None and faster.next != ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def naive_hasCycle(self, head):
""":type head: ListNode :rtype: bool O(n) space complexity"""
<|body_0|>
def hasCycle(self, head):
""":type head: ListNode :rtype: bool proof: https://stackoverflow.com/questions/3952805/proof-of-detecting-the-start-of-cycle-... | stack_v2_sparse_classes_10k_train_002083 | 837 | no_license | [
{
"docstring": ":type head: ListNode :rtype: bool O(n) space complexity",
"name": "naive_hasCycle",
"signature": "def naive_hasCycle(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: bool proof: https://stackoverflow.com/questions/3952805/proof-of-detecting-the-start-of-cycle-in-linke... | 2 | stack_v2_sparse_classes_30k_train_004327 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def naive_hasCycle(self, head): :type head: ListNode :rtype: bool O(n) space complexity
- def hasCycle(self, head): :type head: ListNode :rtype: bool proof: https://stackoverflow... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def naive_hasCycle(self, head): :type head: ListNode :rtype: bool O(n) space complexity
- def hasCycle(self, head): :type head: ListNode :rtype: bool proof: https://stackoverflow... | 9746205998338fb4d7fd51300a21149c4181fc8f | <|skeleton|>
class Solution:
def naive_hasCycle(self, head):
""":type head: ListNode :rtype: bool O(n) space complexity"""
<|body_0|>
def hasCycle(self, head):
""":type head: ListNode :rtype: bool proof: https://stackoverflow.com/questions/3952805/proof-of-detecting-the-start-of-cycle-... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def naive_hasCycle(self, head):
""":type head: ListNode :rtype: bool O(n) space complexity"""
visited = {}
while head is not None:
if head in visited:
return True
visited[head] = 1
head = head.next
return False
... | the_stack_v2_python_sparse | leetcode/linkedList/4_linked_list_cycle.py | RuizhenMai/academic-blog | train | 0 | |
61fe90763c060ddfb2ad7768456acf1dc3c813d4 | [
"self.environment = environment\nself.relative_snapshot_directory = relative_snapshot_directory\nself.root_path = root_path\nself.source_snapshot_create_time_usecs = source_snapshot_create_time_usecs\nself.source_snapshot_name = source_snapshot_name\nself.view_name = view_name",
"if dictionary is None:\n retur... | <|body_start_0|>
self.environment = environment
self.relative_snapshot_directory = relative_snapshot_directory
self.root_path = root_path
self.source_snapshot_create_time_usecs = source_snapshot_create_time_usecs
self.source_snapshot_name = source_snapshot_name
self.view_... | Implementation of the 'SnapshotInfo' model. Specifies details about the snapshot task created to backup or copy one source object like a VM. Attributes: environment (EnvironmentSnapshotInfoEnum): Specifies the environment type (such as kVMware or kSQL) that contains the source to backup. Supported environment types suc... | SnapshotInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnapshotInfo:
"""Implementation of the 'SnapshotInfo' model. Specifies details about the snapshot task created to backup or copy one source object like a VM. Attributes: environment (EnvironmentSnapshotInfoEnum): Specifies the environment type (such as kVMware or kSQL) that contains the source to... | stack_v2_sparse_classes_10k_train_002084 | 7,355 | permissive | [
{
"docstring": "Constructor for the SnapshotInfo class",
"name": "__init__",
"signature": "def __init__(self, environment=None, relative_snapshot_directory=None, root_path=None, source_snapshot_create_time_usecs=None, source_snapshot_name=None, view_name=None)"
},
{
"docstring": "Creates an inst... | 2 | stack_v2_sparse_classes_30k_train_002234 | Implement the Python class `SnapshotInfo` described below.
Class description:
Implementation of the 'SnapshotInfo' model. Specifies details about the snapshot task created to backup or copy one source object like a VM. Attributes: environment (EnvironmentSnapshotInfoEnum): Specifies the environment type (such as kVMwa... | Implement the Python class `SnapshotInfo` described below.
Class description:
Implementation of the 'SnapshotInfo' model. Specifies details about the snapshot task created to backup or copy one source object like a VM. Attributes: environment (EnvironmentSnapshotInfoEnum): Specifies the environment type (such as kVMwa... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class SnapshotInfo:
"""Implementation of the 'SnapshotInfo' model. Specifies details about the snapshot task created to backup or copy one source object like a VM. Attributes: environment (EnvironmentSnapshotInfoEnum): Specifies the environment type (such as kVMware or kSQL) that contains the source to... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SnapshotInfo:
"""Implementation of the 'SnapshotInfo' model. Specifies details about the snapshot task created to backup or copy one source object like a VM. Attributes: environment (EnvironmentSnapshotInfoEnum): Specifies the environment type (such as kVMware or kSQL) that contains the source to backup. Supp... | the_stack_v2_python_sparse | cohesity_management_sdk/models/snapshot_info.py | cohesity/management-sdk-python | train | 24 |
5727df3b9618a01f9121dce7e723fa2c6a5dad10 | [
"super(Encoder, self).__init__()\nself.layers = clones(layer, N)\nself.norm = LayerNorm(layer.size)",
"for layer in self.layers:\n x = layer(x, mask)\nreturn self.norm(x)"
] | <|body_start_0|>
super(Encoder, self).__init__()
self.layers = clones(layer, N)
self.norm = LayerNorm(layer.size)
<|end_body_0|>
<|body_start_1|>
for layer in self.layers:
x = layer(x, mask)
return self.norm(x)
<|end_body_1|>
| Encoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
def __init__(self, layer, N):
"""Implementation of the encoder as a stack of :param N: :param layer: instances"""
<|body_0|>
def forward(self, x, mask):
"""Pass the input (and mask) through each layer in turn and return the normalized values of the output"""... | stack_v2_sparse_classes_10k_train_002085 | 1,986 | permissive | [
{
"docstring": "Implementation of the encoder as a stack of :param N: :param layer: instances",
"name": "__init__",
"signature": "def __init__(self, layer, N)"
},
{
"docstring": "Pass the input (and mask) through each layer in turn and return the normalized values of the output",
"name": "fo... | 2 | stack_v2_sparse_classes_30k_train_000582 | Implement the Python class `Encoder` described below.
Class description:
Implement the Encoder class.
Method signatures and docstrings:
- def __init__(self, layer, N): Implementation of the encoder as a stack of :param N: :param layer: instances
- def forward(self, x, mask): Pass the input (and mask) through each lay... | Implement the Python class `Encoder` described below.
Class description:
Implement the Encoder class.
Method signatures and docstrings:
- def __init__(self, layer, N): Implementation of the encoder as a stack of :param N: :param layer: instances
- def forward(self, x, mask): Pass the input (and mask) through each lay... | 0f61fac7a8decccd30c622b2080961ed7fec733f | <|skeleton|>
class Encoder:
def __init__(self, layer, N):
"""Implementation of the encoder as a stack of :param N: :param layer: instances"""
<|body_0|>
def forward(self, x, mask):
"""Pass the input (and mask) through each layer in turn and return the normalized values of the output"""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Encoder:
def __init__(self, layer, N):
"""Implementation of the encoder as a stack of :param N: :param layer: instances"""
super(Encoder, self).__init__()
self.layers = clones(layer, N)
self.norm = LayerNorm(layer.size)
def forward(self, x, mask):
"""Pass the input... | the_stack_v2_python_sparse | src/translate/learning/modules/transformer/encoder.py | py4/SFUTranslate | train | 0 | |
595ec60b2bb03b434ba50714ec0217bade080bba | [
"try:\n comment_id = ObjectId(comment_id)\n comment = Comment.objects.get(pk=comment_id)\nexcept InvalidId as e:\n return ErrorResponse(e.message)\nexcept:\n return ErrorResponse(\"Comment doesn't exists\")\nif config.DEBUG:\n print('comment id : {0}'.format(comment_id))\nresults = dict()\nresults['c... | <|body_start_0|>
try:
comment_id = ObjectId(comment_id)
comment = Comment.objects.get(pk=comment_id)
except InvalidId as e:
return ErrorResponse(e.message)
except:
return ErrorResponse("Comment doesn't exists")
if config.DEBUG:
... | CommentResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentResource:
def get(self, comment_id):
"""GET handler for the request /comments/{id} Return all details for the comment {id}"""
<|body_0|>
def delete(self, comment_id):
"""DELETE handler for the request /comments/{id} Delete the comment {id}"""
<|body_1|... | stack_v2_sparse_classes_10k_train_002086 | 4,940 | no_license | [
{
"docstring": "GET handler for the request /comments/{id} Return all details for the comment {id}",
"name": "get",
"signature": "def get(self, comment_id)"
},
{
"docstring": "DELETE handler for the request /comments/{id} Delete the comment {id}",
"name": "delete",
"signature": "def dele... | 2 | stack_v2_sparse_classes_30k_train_000585 | Implement the Python class `CommentResource` described below.
Class description:
Implement the CommentResource class.
Method signatures and docstrings:
- def get(self, comment_id): GET handler for the request /comments/{id} Return all details for the comment {id}
- def delete(self, comment_id): DELETE handler for the... | Implement the Python class `CommentResource` described below.
Class description:
Implement the CommentResource class.
Method signatures and docstrings:
- def get(self, comment_id): GET handler for the request /comments/{id} Return all details for the comment {id}
- def delete(self, comment_id): DELETE handler for the... | eff4a90312885495ccb3ecec5c78a94fc058feca | <|skeleton|>
class CommentResource:
def get(self, comment_id):
"""GET handler for the request /comments/{id} Return all details for the comment {id}"""
<|body_0|>
def delete(self, comment_id):
"""DELETE handler for the request /comments/{id} Delete the comment {id}"""
<|body_1|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CommentResource:
def get(self, comment_id):
"""GET handler for the request /comments/{id} Return all details for the comment {id}"""
try:
comment_id = ObjectId(comment_id)
comment = Comment.objects.get(pk=comment_id)
except InvalidId as e:
return Err... | the_stack_v2_python_sparse | wingo/resources/comments.py | dridk/wingo-server | train | 0 | |
6fa8ce9d1f166ef13328d0e5f538dff545cef425 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ImportedWindowsAutopilotDeviceIdentityUpload()",
"from .entity import Entity\nfrom .imported_windows_autopilot_device_identity import ImportedWindowsAutopilotDeviceIdentity\nfrom .imported_windows_autopilot_device_identity_upload_statu... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ImportedWindowsAutopilotDeviceIdentityUpload()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .imported_windows_autopilot_device_identity import ImportedWindowsAutopilot... | Import windows autopilot devices using upload. | ImportedWindowsAutopilotDeviceIdentityUpload | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImportedWindowsAutopilotDeviceIdentityUpload:
"""Import windows autopilot devices using upload."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ImportedWindowsAutopilotDeviceIdentityUpload:
"""Creates a new instance of the appropriate class based on di... | stack_v2_sparse_classes_10k_train_002087 | 3,621 | 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: ImportedWindowsAutopilotDeviceIdentityUpload",
"name": "create_from_discriminator_value",
"signature": "def ... | 3 | stack_v2_sparse_classes_30k_train_003896 | Implement the Python class `ImportedWindowsAutopilotDeviceIdentityUpload` described below.
Class description:
Import windows autopilot devices using upload.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ImportedWindowsAutopilotDeviceIdentityUpload: Cr... | Implement the Python class `ImportedWindowsAutopilotDeviceIdentityUpload` described below.
Class description:
Import windows autopilot devices using upload.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ImportedWindowsAutopilotDeviceIdentityUpload: Cr... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ImportedWindowsAutopilotDeviceIdentityUpload:
"""Import windows autopilot devices using upload."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ImportedWindowsAutopilotDeviceIdentityUpload:
"""Creates a new instance of the appropriate class based on di... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ImportedWindowsAutopilotDeviceIdentityUpload:
"""Import windows autopilot devices using upload."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ImportedWindowsAutopilotDeviceIdentityUpload:
"""Creates a new instance of the appropriate class based on discriminator v... | the_stack_v2_python_sparse | msgraph/generated/models/imported_windows_autopilot_device_identity_upload.py | microsoftgraph/msgraph-sdk-python | train | 135 |
14ec8d9c4938ca7ecb0fcbb709c3492f4d317fe9 | [
"self.VER = version\nself.DIR = dirname\nself.TR_PATH = os.path.join(raw_data_path, self.VER, self.DIR, 'tracklets', 'data')\nself.INS_PATH = os.path.join(raw_data_path, self.VER, self.DIR, 'INS', 'data')",
"load_path = [os.path.join(self.TR_PATH, dataset) for dataset in os.listdir(self.TR_PATH)]\nload_path.sort(... | <|body_start_0|>
self.VER = version
self.DIR = dirname
self.TR_PATH = os.path.join(raw_data_path, self.VER, self.DIR, 'tracklets', 'data')
self.INS_PATH = os.path.join(raw_data_path, self.VER, self.DIR, 'INS', 'data')
<|end_body_0|>
<|body_start_1|>
load_path = [os.path.join(sel... | Implementation of making datasets. | load_datasets | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class load_datasets:
"""Implementation of making datasets."""
def __init__(self, version, dirname):
"""Args: version: version of raw data ex) 'v1', 'v2' dirname: directory name of tracklets ex) '2017Y03M08D11H11m07s'"""
<|body_0|>
def load_tracklets(self):
"""load trac... | stack_v2_sparse_classes_10k_train_002088 | 1,560 | no_license | [
{
"docstring": "Args: version: version of raw data ex) 'v1', 'v2' dirname: directory name of tracklets ex) '2017Y03M08D11H11m07s'",
"name": "__init__",
"signature": "def __init__(self, version, dirname)"
},
{
"docstring": "load tracklets data.",
"name": "load_tracklets",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_train_004426 | Implement the Python class `load_datasets` described below.
Class description:
Implementation of making datasets.
Method signatures and docstrings:
- def __init__(self, version, dirname): Args: version: version of raw data ex) 'v1', 'v2' dirname: directory name of tracklets ex) '2017Y03M08D11H11m07s'
- def load_track... | Implement the Python class `load_datasets` described below.
Class description:
Implementation of making datasets.
Method signatures and docstrings:
- def __init__(self, version, dirname): Args: version: version of raw data ex) 'v1', 'v2' dirname: directory name of tracklets ex) '2017Y03M08D11H11m07s'
- def load_track... | 2fde7c45771047a2136f9e5842c2a78097fef13a | <|skeleton|>
class load_datasets:
"""Implementation of making datasets."""
def __init__(self, version, dirname):
"""Args: version: version of raw data ex) 'v1', 'v2' dirname: directory name of tracklets ex) '2017Y03M08D11H11m07s'"""
<|body_0|>
def load_tracklets(self):
"""load trac... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class load_datasets:
"""Implementation of making datasets."""
def __init__(self, version, dirname):
"""Args: version: version of raw data ex) 'v1', 'v2' dirname: directory name of tracklets ex) '2017Y03M08D11H11m07s'"""
self.VER = version
self.DIR = dirname
self.TR_PATH = os.pat... | the_stack_v2_python_sparse | data_preprocessing/load_datasets.py | spa-hanyang/neural-trajectory-prediction | train | 2 |
89f507bc0e205ae3fc33ab4b8d80c3be9424c360 | [
"print('Loading weights to MidasNet: ', path)\nsuper(MidasNet, self).__init__()\nuse_pretrained = False if path else True\nself.pretrained, self.scratch = _make_encoder(backbone, features, use_pretrained)\nself.scratch.refinenet4 = FeatureFusionBlock(features)\nself.scratch.refinenet3 = FeatureFusionBlock(features)... | <|body_start_0|>
print('Loading weights to MidasNet: ', path)
super(MidasNet, self).__init__()
use_pretrained = False if path else True
self.pretrained, self.scratch = _make_encoder(backbone, features, use_pretrained)
self.scratch.refinenet4 = FeatureFusionBlock(features)
... | Network for monocular depth estimation. | MidasNet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MidasNet:
"""Network for monocular depth estimation."""
def __init__(self, path=None, features=256, backbone='resnet50', non_negative=True):
"""Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. back... | stack_v2_sparse_classes_10k_train_002089 | 13,019 | permissive | [
{
"docstring": "Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. backbone (str, optional): Backbone network for encoder. Defaults to resnet50",
"name": "__init__",
"signature": "def __init__(self, path=None, features=... | 2 | null | Implement the Python class `MidasNet` described below.
Class description:
Network for monocular depth estimation.
Method signatures and docstrings:
- def __init__(self, path=None, features=256, backbone='resnet50', non_negative=True): Init. Args: path (str, optional): Path to saved model. Defaults to None. features (... | Implement the Python class `MidasNet` described below.
Class description:
Network for monocular depth estimation.
Method signatures and docstrings:
- def __init__(self, path=None, features=256, backbone='resnet50', non_negative=True): Init. Args: path (str, optional): Path to saved model. Defaults to None. features (... | a00c3619bf4042e446e1919087f0b09fe9fa3a65 | <|skeleton|>
class MidasNet:
"""Network for monocular depth estimation."""
def __init__(self, path=None, features=256, backbone='resnet50', non_negative=True):
"""Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. back... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MidasNet:
"""Network for monocular depth estimation."""
def __init__(self, path=None, features=256, backbone='resnet50', non_negative=True):
"""Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. backbone (str, op... | the_stack_v2_python_sparse | nasws/cnn/search_space/monodepth/models/midas_net.py | kcyu2014/nas-landmarkreg | train | 10 |
5fe5ef359fc4a781858d7704b6f540e129da78f2 | [
"super().__init__()\nself.analysis = analysis\nself.model = model\nself.perturbation_model = perturbation_model\npaths = search.paths\nself.search = search.copy_with_paths(DirectoryPaths(name=paths.name + '[base]', path_prefix=paths.path_prefix))\nself.perturbed_search = search.copy_with_paths(DirectoryPaths(name=p... | <|body_start_0|>
super().__init__()
self.analysis = analysis
self.model = model
self.perturbation_model = perturbation_model
paths = search.paths
self.search = search.copy_with_paths(DirectoryPaths(name=paths.name + '[base]', path_prefix=paths.path_prefix))
self.p... | Job | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Job:
def __init__(self, analysis: Analysis, model: AbstractPriorModel, perturbation_model: AbstractPriorModel, search: NonLinearSearch):
"""Job to run non-linear searches comparing how well a model and a model with a perturbation fit the image. Parameters ---------- model A base model th... | stack_v2_sparse_classes_10k_train_002090 | 10,356 | permissive | [
{
"docstring": "Job to run non-linear searches comparing how well a model and a model with a perturbation fit the image. Parameters ---------- model A base model that fits the image without a perturbation perturbation_model A model of the perturbation which has been added to the underlying image analysis A clas... | 2 | stack_v2_sparse_classes_30k_train_004358 | Implement the Python class `Job` described below.
Class description:
Implement the Job class.
Method signatures and docstrings:
- def __init__(self, analysis: Analysis, model: AbstractPriorModel, perturbation_model: AbstractPriorModel, search: NonLinearSearch): Job to run non-linear searches comparing how well a mode... | Implement the Python class `Job` described below.
Class description:
Implement the Job class.
Method signatures and docstrings:
- def __init__(self, analysis: Analysis, model: AbstractPriorModel, perturbation_model: AbstractPriorModel, search: NonLinearSearch): Job to run non-linear searches comparing how well a mode... | 324007a6bbda32baf94f09918e0aef04fda0c7d0 | <|skeleton|>
class Job:
def __init__(self, analysis: Analysis, model: AbstractPriorModel, perturbation_model: AbstractPriorModel, search: NonLinearSearch):
"""Job to run non-linear searches comparing how well a model and a model with a perturbation fit the image. Parameters ---------- model A base model th... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Job:
def __init__(self, analysis: Analysis, model: AbstractPriorModel, perturbation_model: AbstractPriorModel, search: NonLinearSearch):
"""Job to run non-linear searches comparing how well a model and a model with a perturbation fit the image. Parameters ---------- model A base model that fits the im... | the_stack_v2_python_sparse | autofit/non_linear/grid/sensitivity.py | philastrophist/PyAutoFit | train | 0 | |
4960b6d39ce43bf55a7339568139f68976c613b3 | [
"if AccountTeam.objects.filter(account=self.auth.get_account()).exists():\n raise TeamInfoExcept.already_in_team()\nlogic = TeamLogic(self.auth, tid)\nparams = ParamsParser(request.JSON)\npassword = params.str('password', desc='入队密码', default='', require=False)\nif not logic.team.public and password != logic.tea... | <|body_start_0|>
if AccountTeam.objects.filter(account=self.auth.get_account()).exists():
raise TeamInfoExcept.already_in_team()
logic = TeamLogic(self.auth, tid)
params = ParamsParser(request.JSON)
password = params.str('password', desc='入队密码', default='', require=False)
... | TeamManageView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeamManageView:
def post(self, request, tid):
"""加入队伍 :param request: :param tid: :return:"""
<|body_0|>
def get(self, request, tid):
"""获取队伍成员列表 :param request: :param tid: :return:"""
<|body_1|>
def put(self, request, tid):
"""修改成员角色 :param req... | stack_v2_sparse_classes_10k_train_002091 | 3,997 | no_license | [
{
"docstring": "加入队伍 :param request: :param tid: :return:",
"name": "post",
"signature": "def post(self, request, tid)"
},
{
"docstring": "获取队伍成员列表 :param request: :param tid: :return:",
"name": "get",
"signature": "def get(self, request, tid)"
},
{
"docstring": "修改成员角色 :param re... | 3 | stack_v2_sparse_classes_30k_train_006796 | Implement the Python class `TeamManageView` described below.
Class description:
Implement the TeamManageView class.
Method signatures and docstrings:
- def post(self, request, tid): 加入队伍 :param request: :param tid: :return:
- def get(self, request, tid): 获取队伍成员列表 :param request: :param tid: :return:
- def put(self, r... | Implement the Python class `TeamManageView` described below.
Class description:
Implement the TeamManageView class.
Method signatures and docstrings:
- def post(self, request, tid): 加入队伍 :param request: :param tid: :return:
- def get(self, request, tid): 获取队伍成员列表 :param request: :param tid: :return:
- def put(self, r... | 7467cd66e1fc91f0b3a264f8fc9b93f22f09fe7b | <|skeleton|>
class TeamManageView:
def post(self, request, tid):
"""加入队伍 :param request: :param tid: :return:"""
<|body_0|>
def get(self, request, tid):
"""获取队伍成员列表 :param request: :param tid: :return:"""
<|body_1|>
def put(self, request, tid):
"""修改成员角色 :param req... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TeamManageView:
def post(self, request, tid):
"""加入队伍 :param request: :param tid: :return:"""
if AccountTeam.objects.filter(account=self.auth.get_account()).exists():
raise TeamInfoExcept.already_in_team()
logic = TeamLogic(self.auth, tid)
params = ParamsParser(requ... | the_stack_v2_python_sparse | FireHydrant/server/team/views/manage.py | shoogoome/FireHydrant | train | 4 | |
52de90c9239df0a5c356aa3a10c15529dbf13a8f | [
"self.address = address\nself.is_alert_auditing_enabled = is_alert_auditing_enabled\nself.is_cluster_auditing_enabled = is_cluster_auditing_enabled\nself.is_data_protection_enabled = is_data_protection_enabled\nself.is_filer_auditing_enabled = is_filer_auditing_enabled\nself.is_ssh_log_enabled = is_ssh_log_enabled\... | <|body_start_0|>
self.address = address
self.is_alert_auditing_enabled = is_alert_auditing_enabled
self.is_cluster_auditing_enabled = is_cluster_auditing_enabled
self.is_data_protection_enabled = is_data_protection_enabled
self.is_filer_auditing_enabled = is_filer_auditing_enable... | Implementation of the 'OldSyslogServer' model. Specifies the syslog servers configuration to upload Cluster audit logs and filer audit logs. Attributes: address (string, required): Specifies the IP address or hostname of the syslog server. is_alert_auditing_enabled (bool): Specifies if cohesity alert should be sent to ... | OldSyslogServer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OldSyslogServer:
"""Implementation of the 'OldSyslogServer' model. Specifies the syslog servers configuration to upload Cluster audit logs and filer audit logs. Attributes: address (string, required): Specifies the IP address or hostname of the syslog server. is_alert_auditing_enabled (bool): Spe... | stack_v2_sparse_classes_10k_train_002092 | 5,035 | permissive | [
{
"docstring": "Constructor for the OldSyslogServer class",
"name": "__init__",
"signature": "def __init__(self, address=None, is_alert_auditing_enabled=None, is_cluster_auditing_enabled=None, is_data_protection_enabled=None, is_filer_auditing_enabled=None, is_ssh_log_enabled=None, name=None, port=None,... | 2 | null | Implement the Python class `OldSyslogServer` described below.
Class description:
Implementation of the 'OldSyslogServer' model. Specifies the syslog servers configuration to upload Cluster audit logs and filer audit logs. Attributes: address (string, required): Specifies the IP address or hostname of the syslog server... | Implement the Python class `OldSyslogServer` described below.
Class description:
Implementation of the 'OldSyslogServer' model. Specifies the syslog servers configuration to upload Cluster audit logs and filer audit logs. Attributes: address (string, required): Specifies the IP address or hostname of the syslog server... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class OldSyslogServer:
"""Implementation of the 'OldSyslogServer' model. Specifies the syslog servers configuration to upload Cluster audit logs and filer audit logs. Attributes: address (string, required): Specifies the IP address or hostname of the syslog server. is_alert_auditing_enabled (bool): Spe... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OldSyslogServer:
"""Implementation of the 'OldSyslogServer' model. Specifies the syslog servers configuration to upload Cluster audit logs and filer audit logs. Attributes: address (string, required): Specifies the IP address or hostname of the syslog server. is_alert_auditing_enabled (bool): Specifies if coh... | the_stack_v2_python_sparse | cohesity_management_sdk/models/old_syslog_server.py | cohesity/management-sdk-python | train | 24 |
b75166d9eb907de085925242fdeab40c0b0a4a8a | [
"super().__init__()\nself.feat_channels = feat_channels\nself.gate_channels = gate_channels\nself.int_channels = int_channels\nself.gate_conv = nn.Conv2d(gate_channels, int_channels, kernel_size=1, bias=False)\nself.gate_bn = nn.BatchNorm2d(int_channels)\nself.feat_conv = nn.Conv2d(feat_channels, int_channels, kern... | <|body_start_0|>
super().__init__()
self.feat_channels = feat_channels
self.gate_channels = gate_channels
self.int_channels = int_channels
self.gate_conv = nn.Conv2d(gate_channels, int_channels, kernel_size=1, bias=False)
self.gate_bn = nn.BatchNorm2d(int_channels)
... | Attention gate for (skip) connections. Produces the attention coefficient :math:`alpha`. See "Attention U-Net:Learning Where to Look for the Pancreas" https://arxiv.org/pdf/1804.03999.pdf | AttentionGate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttentionGate:
"""Attention gate for (skip) connections. Produces the attention coefficient :math:`alpha`. See "Attention U-Net:Learning Where to Look for the Pancreas" https://arxiv.org/pdf/1804.03999.pdf"""
def __init__(self, gate_channels, feat_channels, int_channels):
"""Paramete... | stack_v2_sparse_classes_10k_train_002093 | 9,610 | no_license | [
{
"docstring": "Parameters ---------- gate_channels : int No. of feature-maps in gate vector. feat_channels : int No. of feature-maps in lower-level feature vector (e.g. skip connection). int_channels : int No. of intermediate channels for the attention module.",
"name": "__init__",
"signature": "def __... | 2 | stack_v2_sparse_classes_30k_train_001521 | Implement the Python class `AttentionGate` described below.
Class description:
Attention gate for (skip) connections. Produces the attention coefficient :math:`alpha`. See "Attention U-Net:Learning Where to Look for the Pancreas" https://arxiv.org/pdf/1804.03999.pdf
Method signatures and docstrings:
- def __init__(se... | Implement the Python class `AttentionGate` described below.
Class description:
Attention gate for (skip) connections. Produces the attention coefficient :math:`alpha`. See "Attention U-Net:Learning Where to Look for the Pancreas" https://arxiv.org/pdf/1804.03999.pdf
Method signatures and docstrings:
- def __init__(se... | 6fe259cd15ca31b4a238f700d3993b48e44a73fe | <|skeleton|>
class AttentionGate:
"""Attention gate for (skip) connections. Produces the attention coefficient :math:`alpha`. See "Attention U-Net:Learning Where to Look for the Pancreas" https://arxiv.org/pdf/1804.03999.pdf"""
def __init__(self, gate_channels, feat_channels, int_channels):
"""Paramete... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AttentionGate:
"""Attention gate for (skip) connections. Produces the attention coefficient :math:`alpha`. See "Attention U-Net:Learning Where to Look for the Pancreas" https://arxiv.org/pdf/1804.03999.pdf"""
def __init__(self, gate_channels, feat_channels, int_channels):
"""Parameters ----------... | the_stack_v2_python_sparse | nets/unet.py | medical-projects/dlmi-project | train | 0 |
d33f5928e4414fbed5d4a09ae32baa2c6f413c19 | [
"super(Variational, self).__init__()\nself.hidden_size = hidden_size\nself.latent_size = latent_size\nself.use_identity = use_identity\nif self.use_identity:\n self.hidden_to_mu = nn.Identity()\n self.hidden_to_tanh = nn.Linear(self.hidden_size, self.latent_size)\n self.act_tanh = nn.Tanh()\n self.than_... | <|body_start_0|>
super(Variational, self).__init__()
self.hidden_size = hidden_size
self.latent_size = latent_size
self.use_identity = use_identity
if self.use_identity:
self.hidden_to_mu = nn.Identity()
self.hidden_to_tanh = nn.Linear(self.hidden_size, se... | Variation Layer of Variational AutoEncoder | Variational | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Variational:
"""Variation Layer of Variational AutoEncoder"""
def __init__(self, hidden_size: int, latent_size: int, use_identity: bool=False):
"""Variational Args: hidden_size (int): number of features per time step (output from encoder) latent_size (int): what size the latent vecto... | stack_v2_sparse_classes_10k_train_002094 | 14,969 | permissive | [
{
"docstring": "Variational Args: hidden_size (int): number of features per time step (output from encoder) latent_size (int): what size the latent vector should be use_identity (bool, optional): if identity should be used. Defaults to False.",
"name": "__init__",
"signature": "def __init__(self, hidden... | 2 | stack_v2_sparse_classes_30k_train_000482 | Implement the Python class `Variational` described below.
Class description:
Variation Layer of Variational AutoEncoder
Method signatures and docstrings:
- def __init__(self, hidden_size: int, latent_size: int, use_identity: bool=False): Variational Args: hidden_size (int): number of features per time step (output fr... | Implement the Python class `Variational` described below.
Class description:
Variation Layer of Variational AutoEncoder
Method signatures and docstrings:
- def __init__(self, hidden_size: int, latent_size: int, use_identity: bool=False): Variational Args: hidden_size (int): number of features per time step (output fr... | 5b4a61b5dd0bc259ffe68223877949ef4ebfa5e3 | <|skeleton|>
class Variational:
"""Variation Layer of Variational AutoEncoder"""
def __init__(self, hidden_size: int, latent_size: int, use_identity: bool=False):
"""Variational Args: hidden_size (int): number of features per time step (output from encoder) latent_size (int): what size the latent vecto... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Variational:
"""Variation Layer of Variational AutoEncoder"""
def __init__(self, hidden_size: int, latent_size: int, use_identity: bool=False):
"""Variational Args: hidden_size (int): number of features per time step (output from encoder) latent_size (int): what size the latent vector should be u... | the_stack_v2_python_sparse | src/models/anomalia/layers.py | maurony/ts-vrae | train | 1 |
95876cbb93bd6adb05e056aedbb3140bdd03aac5 | [
"self.radius = radius\nself.x = x_center\nself.y = y_center",
"while True:\n x = random.uniform(-1.0, 1.0)\n y = random.uniform(-1.0, 1.0)\n if x ** 2 + y ** 2 <= 1:\n break\nx = self.x + x * self.radius\ny = self.y + y * self.radius\nreturn [x, y]"
] | <|body_start_0|>
self.radius = radius
self.x = x_center
self.y = y_center
<|end_body_0|>
<|body_start_1|>
while True:
x = random.uniform(-1.0, 1.0)
y = random.uniform(-1.0, 1.0)
if x ** 2 + y ** 2 <= 1:
break
x = self.x + x * s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float"""
<|body_0|>
def randPoint(self):
""":rtype: List[float]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.radius = radi... | stack_v2_sparse_classes_10k_train_002095 | 2,121 | no_license | [
{
"docstring": ":type radius: float :type x_center: float :type y_center: float",
"name": "__init__",
"signature": "def __init__(self, radius, x_center, y_center)"
},
{
"docstring": ":rtype: List[float]",
"name": "randPoint",
"signature": "def randPoint(self)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, radius, x_center, y_center): :type radius: float :type x_center: float :type y_center: float
- def randPoint(self): :rtype: List[float] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, radius, x_center, y_center): :type radius: float :type x_center: float :type y_center: float
- def randPoint(self): :rtype: List[float]
<|skeleton|>
class Sol... | a5cb862f0c5a3cfd21468141800568c2dedded0a | <|skeleton|>
class Solution:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float"""
<|body_0|>
def randPoint(self):
""":rtype: List[float]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float"""
self.radius = radius
self.x = x_center
self.y = y_center
def randPoint(self):
""":rtype: List[float]"""
while True:
x... | the_stack_v2_python_sparse | python/leetcode/sampling/478_generate_point_circle.py | Levintsky/topcoder | train | 0 | |
d0842a76fef5e5a66e10ccec6f48daffaf1c5a92 | [
"params = request.query_params.dict()\nvariety = params.get('variety')\nsidebars = Sidebar.objects.filter(variety=variety).order_by('-priority', 'id')\ndata = [{'sidebar_id': sidebar.id, 'sidebar_name': sidebar.name} for sidebar in sidebars]\nreturn BackstageHTTPResponse(BackstageHTTPResponse.API_HTTP_CODE_NORMAL, ... | <|body_start_0|>
params = request.query_params.dict()
variety = params.get('variety')
sidebars = Sidebar.objects.filter(variety=variety).order_by('-priority', 'id')
data = [{'sidebar_id': sidebar.id, 'sidebar_name': sidebar.name} for sidebar in sidebars]
return BackstageHTTPRespo... | ChartSidebarView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChartSidebarView:
def get(self, request):
"""获取品种侧边栏 --- parameters: - name: variety description: 品种 paramType: query required: True"""
<|body_0|>
def post(self, request):
"""新增侧边栏 --- parameters: - name: variety description: 品种 paramType: form required: True - name:... | stack_v2_sparse_classes_10k_train_002096 | 16,279 | no_license | [
{
"docstring": "获取品种侧边栏 --- parameters: - name: variety description: 品种 paramType: query required: True",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "新增侧边栏 --- parameters: - name: variety description: 品种 paramType: form required: True - name: sidebar_name description:... | 4 | null | Implement the Python class `ChartSidebarView` described below.
Class description:
Implement the ChartSidebarView class.
Method signatures and docstrings:
- def get(self, request): 获取品种侧边栏 --- parameters: - name: variety description: 品种 paramType: query required: True
- def post(self, request): 新增侧边栏 --- parameters: -... | Implement the Python class `ChartSidebarView` described below.
Class description:
Implement the ChartSidebarView class.
Method signatures and docstrings:
- def get(self, request): 获取品种侧边栏 --- parameters: - name: variety description: 品种 paramType: query required: True
- def post(self, request): 新增侧边栏 --- parameters: -... | c50def8cde58fd4663032b860eb058302cbac6da | <|skeleton|>
class ChartSidebarView:
def get(self, request):
"""获取品种侧边栏 --- parameters: - name: variety description: 品种 paramType: query required: True"""
<|body_0|>
def post(self, request):
"""新增侧边栏 --- parameters: - name: variety description: 品种 paramType: form required: True - name:... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ChartSidebarView:
def get(self, request):
"""获取品种侧边栏 --- parameters: - name: variety description: 品种 paramType: query required: True"""
params = request.query_params.dict()
variety = params.get('variety')
sidebars = Sidebar.objects.filter(variety=variety).order_by('-priority', ... | the_stack_v2_python_sparse | src/api/chart/views.py | fan1018wen/Alpha | train | 0 | |
5a2e57b60a6b5d2016d3e5711de1276e0fc493eb | [
"if not self._dapver or parse(self._dapver) < self.__min_dapall_version__:\n raise MarvinError('DAPall is not available for versions before MPL-6.')\nif hasattr(self, '_dapall') and self._dapall is not None:\n return self._dapall\nif self.data_origin == 'file':\n try:\n dapall_data = self._get_dapal... | <|body_start_0|>
if not self._dapver or parse(self._dapver) < self.__min_dapall_version__:
raise MarvinError('DAPall is not available for versions before MPL-6.')
if hasattr(self, '_dapall') and self._dapall is not None:
return self._dapall
if self.data_origin == 'file':
... | A mixin that provides access to DAPall paremeters. Must be used in combination with `.MarvinToolsClass` and initialised before `~.DAPallMixIn.dapall` can be called. `DAPallMixIn` uses the `.MarvinToolsClass.data_origin` of the object to determine how to obtain the DAPall information. However, if the object contains a `... | DAPallMixIn | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DAPallMixIn:
"""A mixin that provides access to DAPall paremeters. Must be used in combination with `.MarvinToolsClass` and initialised before `~.DAPallMixIn.dapall` can be called. `DAPallMixIn` uses the `.MarvinToolsClass.data_origin` of the object to determine how to obtain the DAPall informati... | stack_v2_sparse_classes_10k_train_002097 | 4,554 | permissive | [
{
"docstring": "Returns the contents of the DAPall data for this target.",
"name": "dapall",
"signature": "def dapall(self)"
},
{
"docstring": "Uses DAPAll file to retrieve information.",
"name": "_get_dapall_from_file",
"signature": "def _get_dapall_from_file(self)"
},
{
"docstr... | 4 | stack_v2_sparse_classes_30k_train_005735 | Implement the Python class `DAPallMixIn` described below.
Class description:
A mixin that provides access to DAPall paremeters. Must be used in combination with `.MarvinToolsClass` and initialised before `~.DAPallMixIn.dapall` can be called. `DAPallMixIn` uses the `.MarvinToolsClass.data_origin` of the object to deter... | Implement the Python class `DAPallMixIn` described below.
Class description:
A mixin that provides access to DAPall paremeters. Must be used in combination with `.MarvinToolsClass` and initialised before `~.DAPallMixIn.dapall` can be called. `DAPallMixIn` uses the `.MarvinToolsClass.data_origin` of the object to deter... | db4c536a65fb2f16fee05a4f34996a7fd35f0527 | <|skeleton|>
class DAPallMixIn:
"""A mixin that provides access to DAPall paremeters. Must be used in combination with `.MarvinToolsClass` and initialised before `~.DAPallMixIn.dapall` can be called. `DAPallMixIn` uses the `.MarvinToolsClass.data_origin` of the object to determine how to obtain the DAPall informati... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DAPallMixIn:
"""A mixin that provides access to DAPall paremeters. Must be used in combination with `.MarvinToolsClass` and initialised before `~.DAPallMixIn.dapall` can be called. `DAPallMixIn` uses the `.MarvinToolsClass.data_origin` of the object to determine how to obtain the DAPall information. However, ... | the_stack_v2_python_sparse | python/marvin/tools/mixins/dapall.py | sdss/marvin | train | 56 |
0b39cc5d0b2c60e4d840a9c69fd40dc32372be15 | [
"res.append(partial)\nn = len(nums)\nif start >= n:\n return\nfor i in range(start, n):\n self._subsets(nums, i + 1, partial + [nums[i]], res)",
"res = []\npartial = []\nself._subsets(nums, 0, partial, res)\nreturn res"
] | <|body_start_0|>
res.append(partial)
n = len(nums)
if start >= n:
return
for i in range(start, n):
self._subsets(nums, i + 1, partial + [nums[i]], res)
<|end_body_0|>
<|body_start_1|>
res = []
partial = []
self._subsets(nums, 0, partial, r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _subsets(self, nums, start, partial, res):
""":type nums: List[int] :type start: int :type partial: List[int] :type res: List[List[int]]"""
<|body_0|>
def subsets(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end... | stack_v2_sparse_classes_10k_train_002098 | 1,073 | no_license | [
{
"docstring": ":type nums: List[int] :type start: int :type partial: List[int] :type res: List[List[int]]",
"name": "_subsets",
"signature": "def _subsets(self, nums, start, partial, res)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "subsets",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_004309 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _subsets(self, nums, start, partial, res): :type nums: List[int] :type start: int :type partial: List[int] :type res: List[List[int]]
- def subsets(self, nums): :type nums: L... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _subsets(self, nums, start, partial, res): :type nums: List[int] :type start: int :type partial: List[int] :type res: List[List[int]]
- def subsets(self, nums): :type nums: L... | cd3900a7d91d1d94d308bc7a65533b8262781ee9 | <|skeleton|>
class Solution:
def _subsets(self, nums, start, partial, res):
""":type nums: List[int] :type start: int :type partial: List[int] :type res: List[List[int]]"""
<|body_0|>
def subsets(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def _subsets(self, nums, start, partial, res):
""":type nums: List[int] :type start: int :type partial: List[int] :type res: List[List[int]]"""
res.append(partial)
n = len(nums)
if start >= n:
return
for i in range(start, n):
self._subs... | the_stack_v2_python_sparse | lc0078_Subsets/lc0078.py | cgi0911/LeetCodePractice | train | 0 | |
8798367333a1c41e46786ff3a41e7bfe38dbcdd9 | [
"num = 1\nself.container = []\ntemp = 0\nfor w_ in w:\n temp += w_\n self.container.append(temp)\nself.maxint = temp",
"rand = random.randint(1, self.maxint)\nindex = bisect.bisect_left(self.container, rand)\nreturn index"
] | <|body_start_0|>
num = 1
self.container = []
temp = 0
for w_ in w:
temp += w_
self.container.append(temp)
self.maxint = temp
<|end_body_0|>
<|body_start_1|>
rand = random.randint(1, self.maxint)
index = bisect.bisect_left(self.container, r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
num = 1
self.container = []
temp = 0
for w_ in w:
temp += w_... | stack_v2_sparse_classes_10k_train_002099 | 616 | no_license | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, w)"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000495 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int
<|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|... | d2e0fb4a55003d5c230fb8b2e13ac8b224b47a75 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, w):
""":type w: List[int]"""
num = 1
self.container = []
temp = 0
for w_ in w:
temp += w_
self.container.append(temp)
self.maxint = temp
def pickIndex(self):
""":rtype: int"""
rand = rando... | the_stack_v2_python_sparse | 528-pickIndex.py | sunshinewxz/leetcode | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.