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 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c83ce6e735fd9910d932ed0ca33158d81740a57e | [
"response_data = {}\nbase_uri = generate_base_uri(request)\nresponse_data['uri'] = base_uri\ntry:\n existing_group = Group.objects.get(id=group_id)\n existing_relationship = CourseGroupRelationship.objects.get(course_id=course_id, group=existing_group)\nexcept ObjectDoesNotExist:\n existing_group = None\n ... | <|body_start_0|>
response_data = {}
base_uri = generate_base_uri(request)
response_data['uri'] = base_uri
try:
existing_group = Group.objects.get(id=group_id)
existing_relationship = CourseGroupRelationship.objects.get(course_id=course_id, group=existing_group)
... | ### The GroupsCoursesDetail view allows clients to interact with a specific Group-Course relationship - URI: ```/api/groups/{group_id}/courses/{course_id}``` - GET: Returns a JSON representation of the specified Group-Course relationship - DELETE: Removes an existing Group-Course relationship ### Use Cases/Notes: * Use... | GroupsCoursesDetail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupsCoursesDetail:
"""### The GroupsCoursesDetail view allows clients to interact with a specific Group-Course relationship - URI: ```/api/groups/{group_id}/courses/{course_id}``` - GET: Returns a JSON representation of the specified Group-Course relationship - DELETE: Removes an existing Group... | stack_v2_sparse_classes_75kplus_train_066300 | 30,237 | no_license | [
{
"docstring": "GET /api/groups/{group_id}/courses/{course_id}",
"name": "get",
"signature": "def get(self, request, group_id, course_id)"
},
{
"docstring": "DELETE /api/groups/{group_id}/courses/{course_id}",
"name": "delete",
"signature": "def delete(self, request, group_id, course_id)... | 2 | stack_v2_sparse_classes_30k_train_023771 | Implement the Python class `GroupsCoursesDetail` described below.
Class description:
### The GroupsCoursesDetail view allows clients to interact with a specific Group-Course relationship - URI: ```/api/groups/{group_id}/courses/{course_id}``` - GET: Returns a JSON representation of the specified Group-Course relations... | Implement the Python class `GroupsCoursesDetail` described below.
Class description:
### The GroupsCoursesDetail view allows clients to interact with a specific Group-Course relationship - URI: ```/api/groups/{group_id}/courses/{course_id}``` - GET: Returns a JSON representation of the specified Group-Course relations... | 37966aeda6e444bbfae23babc067646ab08d4ed5 | <|skeleton|>
class GroupsCoursesDetail:
"""### The GroupsCoursesDetail view allows clients to interact with a specific Group-Course relationship - URI: ```/api/groups/{group_id}/courses/{course_id}``` - GET: Returns a JSON representation of the specified Group-Course relationship - DELETE: Removes an existing Group... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GroupsCoursesDetail:
"""### The GroupsCoursesDetail view allows clients to interact with a specific Group-Course relationship - URI: ```/api/groups/{group_id}/courses/{course_id}``` - GET: Returns a JSON representation of the specified Group-Course relationship - DELETE: Removes an existing Group-Course relat... | the_stack_v2_python_sparse | api_manager/groups/views.py | eduStack/edx-serverapi | train | 0 |
c05347afaab8e3ec1ecd5a3e5d24d0ebb82c5c70 | [
"super().__init__(X)\nself.bands_subset = np.array(bands_subset)\nself.outliers_fraction = outliers_fraction\nself.assume_centered = assume_centered\nself.support_fraction = support_fraction\nself.no_data = no_data",
"n_used_bands = len(self.bands_subset)\nimage_bands_flattened = np.zeros((self.cols * self.rows, ... | <|body_start_0|>
super().__init__(X)
self.bands_subset = np.array(bands_subset)
self.outliers_fraction = outliers_fraction
self.assume_centered = assume_centered
self.support_fraction = support_fraction
self.no_data = no_data
<|end_body_0|>
<|body_start_1|>
n_use... | Antares implementation of elliptic envelop thresholding transformation This class implements the elliptic envelope method to threshold a difference image (like that prodced by the iMAD-MAF transform) to produce a change/no-change classes partition. It uses an elliptic envelope, this method will detect point in the data... | Transform | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transform:
"""Antares implementation of elliptic envelop thresholding transformation This class implements the elliptic envelope method to threshold a difference image (like that prodced by the iMAD-MAF transform) to produce a change/no-change classes partition. It uses an elliptic envelope, this... | stack_v2_sparse_classes_75kplus_train_066301 | 3,281 | no_license | [
{
"docstring": "Instantiate class Args: bands_subset (list): Which bands to consider. outlier_fraction (float): The proportion of outliers in the data set. assume_centered (bool): If True it will not center the data. support_fraction (float): The proportion of points to be included in the support of the raw MCD... | 2 | stack_v2_sparse_classes_30k_train_043888 | Implement the Python class `Transform` described below.
Class description:
Antares implementation of elliptic envelop thresholding transformation This class implements the elliptic envelope method to threshold a difference image (like that prodced by the iMAD-MAF transform) to produce a change/no-change classes partit... | Implement the Python class `Transform` described below.
Class description:
Antares implementation of elliptic envelop thresholding transformation This class implements the elliptic envelope method to threshold a difference image (like that prodced by the iMAD-MAF transform) to produce a change/no-change classes partit... | ab8073a4b45915ba51c718b5403795c44f9b0027 | <|skeleton|>
class Transform:
"""Antares implementation of elliptic envelop thresholding transformation This class implements the elliptic envelope method to threshold a difference image (like that prodced by the iMAD-MAF transform) to produce a change/no-change classes partition. It uses an elliptic envelope, this... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Transform:
"""Antares implementation of elliptic envelop thresholding transformation This class implements the elliptic envelope method to threshold a difference image (like that prodced by the iMAD-MAF transform) to produce a change/no-change classes partition. It uses an elliptic envelope, this method will ... | the_stack_v2_python_sparse | madmex/lcc/transform/elliptic.py | ixime/antares3 | train | 0 |
3093455e886f371492c9bb274c3b6e0f534eb14b | [
"prefix_sum_count = {}\nprefix_sum_count[0] = 1\nreturn self.helper(root, prefix_sum_count, sum, 0)",
"if not node:\n return 0\nres = 0\ncur_sum += node.val\nres += prefix_sum_count.get(cur_sum - target, 0)\nprefix_sum_count[cur_sum] = prefix_sum_count.get(cur_sum, 0) + 1\nres += self.helper(node.left, prefix_... | <|body_start_0|>
prefix_sum_count = {}
prefix_sum_count[0] = 1
return self.helper(root, prefix_sum_count, sum, 0)
<|end_body_0|>
<|body_start_1|>
if not node:
return 0
res = 0
cur_sum += node.val
res += prefix_sum_count.get(cur_sum - target, 0)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def pathSum(self, root, sum):
"""Args: root: TreeNode sum: int Return: int"""
<|body_0|>
def helper(self, node, prefix_sum_count, target, cur_sum):
"""Args: node: TreeNode prefix_sum_count: dict{int: int} target: int cur_sum: int Return: int"""
<|bo... | stack_v2_sparse_classes_75kplus_train_066302 | 1,878 | no_license | [
{
"docstring": "Args: root: TreeNode sum: int Return: int",
"name": "pathSum",
"signature": "def pathSum(self, root, sum)"
},
{
"docstring": "Args: node: TreeNode prefix_sum_count: dict{int: int} target: int cur_sum: int Return: int",
"name": "helper",
"signature": "def helper(self, node... | 2 | stack_v2_sparse_classes_30k_val_001417 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, root, sum): Args: root: TreeNode sum: int Return: int
- def helper(self, node, prefix_sum_count, target, cur_sum): Args: node: TreeNode prefix_sum_count: dict{i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pathSum(self, root, sum): Args: root: TreeNode sum: int Return: int
- def helper(self, node, prefix_sum_count, target, cur_sum): Args: node: TreeNode prefix_sum_count: dict{i... | 101bce2fac8b188a4eb2f5e017293d21ad0ecb21 | <|skeleton|>
class Solution:
def pathSum(self, root, sum):
"""Args: root: TreeNode sum: int Return: int"""
<|body_0|>
def helper(self, node, prefix_sum_count, target, cur_sum):
"""Args: node: TreeNode prefix_sum_count: dict{int: int} target: int cur_sum: int Return: int"""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def pathSum(self, root, sum):
"""Args: root: TreeNode sum: int Return: int"""
prefix_sum_count = {}
prefix_sum_count[0] = 1
return self.helper(root, prefix_sum_count, sum, 0)
def helper(self, node, prefix_sum_count, target, cur_sum):
"""Args: node: TreeNo... | the_stack_v2_python_sparse | code/437. 路径总和 III.py | AiZhanghan/Leetcode | train | 0 | |
5109d6ebed0e8b17a1640b293a7dd4b9a065b036 | [
"datafile_empty = self.get_file('empty.csv')\nschema_empty = [('col_A', int), ('col_B', int), ('col_C', str), ('col_D', float), ('col_E', float), ('col_F', str)]\nframe = self.context.frame.import_csv(datafile_empty, schema=schema_empty)\nself.assertEqual(frame.count(), 0)\nnull2 = frame.copy()\nself.assertEqual(nu... | <|body_start_0|>
datafile_empty = self.get_file('empty.csv')
schema_empty = [('col_A', int), ('col_B', int), ('col_C', str), ('col_D', float), ('col_E', float), ('col_F', str)]
frame = self.context.frame.import_csv(datafile_empty, schema=schema_empty)
self.assertEqual(frame.count(), 0)
... | FileLoadTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileLoadTest:
def test_import_empty(self):
"""Import an empty file."""
<|body_0|>
def test_import_whitespace(self):
"""Build frame with complex quoting and whitespace"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
datafile_empty = self.get_file('em... | stack_v2_sparse_classes_75kplus_train_066303 | 2,116 | permissive | [
{
"docstring": "Import an empty file.",
"name": "test_import_empty",
"signature": "def test_import_empty(self)"
},
{
"docstring": "Build frame with complex quoting and whitespace",
"name": "test_import_whitespace",
"signature": "def test_import_whitespace(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_023339 | Implement the Python class `FileLoadTest` described below.
Class description:
Implement the FileLoadTest class.
Method signatures and docstrings:
- def test_import_empty(self): Import an empty file.
- def test_import_whitespace(self): Build frame with complex quoting and whitespace | Implement the Python class `FileLoadTest` described below.
Class description:
Implement the FileLoadTest class.
Method signatures and docstrings:
- def test_import_empty(self): Import an empty file.
- def test_import_whitespace(self): Build frame with complex quoting and whitespace
<|skeleton|>
class FileLoadTest:
... | 5548fc925b5c278263cbdebbd9e8c7593320c2f4 | <|skeleton|>
class FileLoadTest:
def test_import_empty(self):
"""Import an empty file."""
<|body_0|>
def test_import_whitespace(self):
"""Build frame with complex quoting and whitespace"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileLoadTest:
def test_import_empty(self):
"""Import an empty file."""
datafile_empty = self.get_file('empty.csv')
schema_empty = [('col_A', int), ('col_B', int), ('col_C', str), ('col_D', float), ('col_E', float), ('col_F', str)]
frame = self.context.frame.import_csv(datafile_... | the_stack_v2_python_sparse | regression-tests/sparktkregtests/testcases/frames/file_load_test.py | trustedanalytics/spark-tk | train | 35 | |
d8e358028697cf503d7cafee7b67a629990a9e66 | [
"self.username = username\nself.first_name = first_name\nself.last_name = last_name\nself.application_id = application_id\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\nusername = dictionary.get('username')\nfirst_name = dictionary.get('firstName')\nlast_name = dic... | <|body_start_0|>
self.username = username
self.first_name = first_name
self.last_name = last_name
self.application_id = application_id
self.additional_properties = additional_properties
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
... | Implementation of the 'Add Customer Request' model. Request Structure For The Add Customer Endpoint and Add Testing Customer Endpoint Attributes: username (string): The customer’s username, assigned by the partner (a unique identifier), following these rules: minimum 6 characters maximum 255 characters any mix of upper... | AddCustomerRequest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddCustomerRequest:
"""Implementation of the 'Add Customer Request' model. Request Structure For The Add Customer Endpoint and Add Testing Customer Endpoint Attributes: username (string): The customer’s username, assigned by the partner (a unique identifier), following these rules: minimum 6 char... | stack_v2_sparse_classes_75kplus_train_066304 | 3,413 | permissive | [
{
"docstring": "Constructor for the AddCustomerRequest class",
"name": "__init__",
"signature": "def __init__(self, username=None, first_name=None, last_name=None, application_id=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: diction... | 2 | stack_v2_sparse_classes_30k_train_019805 | Implement the Python class `AddCustomerRequest` described below.
Class description:
Implementation of the 'Add Customer Request' model. Request Structure For The Add Customer Endpoint and Add Testing Customer Endpoint Attributes: username (string): The customer’s username, assigned by the partner (a unique identifier)... | Implement the Python class `AddCustomerRequest` described below.
Class description:
Implementation of the 'Add Customer Request' model. Request Structure For The Add Customer Endpoint and Add Testing Customer Endpoint Attributes: username (string): The customer’s username, assigned by the partner (a unique identifier)... | b2ab1ded435db75c78d42261f5e4acd2a3061487 | <|skeleton|>
class AddCustomerRequest:
"""Implementation of the 'Add Customer Request' model. Request Structure For The Add Customer Endpoint and Add Testing Customer Endpoint Attributes: username (string): The customer’s username, assigned by the partner (a unique identifier), following these rules: minimum 6 char... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddCustomerRequest:
"""Implementation of the 'Add Customer Request' model. Request Structure For The Add Customer Endpoint and Add Testing Customer Endpoint Attributes: username (string): The customer’s username, assigned by the partner (a unique identifier), following these rules: minimum 6 characters maximu... | the_stack_v2_python_sparse | finicityapi/models/add_customer_request.py | monarchmoney/finicity-python | train | 0 |
28ad1c9fb2a257c91e3f8c59fc172407c68dd02b | [
"Base.__init__(self, target, opts)\nself.host, self.port, self.scheme, self.path = self._parse_url(self.target)\nreturn",
"opts = f'-d {self.target} --timeout 5 --threads 15'\nopts += f\" --agent '{self.useragent}'\"\nif self.opts['cookies']:\n opts += f\" --cookies '{self.cookies}'\"\nif self.opts['web_user']... | <|body_start_0|>
Base.__init__(self, target, opts)
self.host, self.port, self.scheme, self.path = self._parse_url(self.target)
return
<|end_body_0|>
<|body_start_1|>
opts = f'-d {self.target} --timeout 5 --threads 15'
opts += f" --agent '{self.useragent}'"
if self.opts['... | Typo3 CMD module | Typo3 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Typo3:
"""Typo3 CMD module"""
def __init__(self, target, opts):
"""init"""
<|body_0|>
def typo_enumerator(self):
"""DESCR: Enumerate Typo3 version and extensions. (ext) TOOLS: typo-enumerator"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Base.... | stack_v2_sparse_classes_75kplus_train_066305 | 2,247 | no_license | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, target, opts)"
},
{
"docstring": "DESCR: Enumerate Typo3 version and extensions. (ext) TOOLS: typo-enumerator",
"name": "typo_enumerator",
"signature": "def typo_enumerator(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005681 | Implement the Python class `Typo3` described below.
Class description:
Typo3 CMD module
Method signatures and docstrings:
- def __init__(self, target, opts): init
- def typo_enumerator(self): DESCR: Enumerate Typo3 version and extensions. (ext) TOOLS: typo-enumerator | Implement the Python class `Typo3` described below.
Class description:
Typo3 CMD module
Method signatures and docstrings:
- def __init__(self, target, opts): init
- def typo_enumerator(self): DESCR: Enumerate Typo3 version and extensions. (ext) TOOLS: typo-enumerator
<|skeleton|>
class Typo3:
"""Typo3 CMD module... | ddc052c8d7d43a60fc00ea40d85111d5bd7a282e | <|skeleton|>
class Typo3:
"""Typo3 CMD module"""
def __init__(self, target, opts):
"""init"""
<|body_0|>
def typo_enumerator(self):
"""DESCR: Enumerate Typo3 version and extensions. (ext) TOOLS: typo-enumerator"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Typo3:
"""Typo3 CMD module"""
def __init__(self, target, opts):
"""init"""
Base.__init__(self, target, opts)
self.host, self.port, self.scheme, self.path = self._parse_url(self.target)
return
def typo_enumerator(self):
"""DESCR: Enumerate Typo3 version and ext... | the_stack_v2_python_sparse | src/modules/web/typo3.py | noptrix/nullscan | train | 52 |
5a807b4167d0d3283e082e1519e31c18a108b47a | [
"super().__init__(test_case=test_case, name=name, subdir=subdir)\nself.cell_width = cell_width\nself.opts.hfun_scal = 'absolute'\nself.opts.hfun_hmax = float('inf')\nself.opts.hfun_hmin = 0.0\nself.opts.mesh_dims = 2\nself.opts.optm_qlim = 0.9375\nself.opts.verbosity = 1",
"section = self.config['spherical_mesh']... | <|body_start_0|>
super().__init__(test_case=test_case, name=name, subdir=subdir)
self.cell_width = cell_width
self.opts.hfun_scal = 'absolute'
self.opts.hfun_hmax = float('inf')
self.opts.hfun_hmin = 0.0
self.opts.mesh_dims = 2
self.opts.optm_qlim = 0.9375
... | A step for creating a quasi-uniform JIGSAW mesh with a constant approximate cell width. Subclasses can override the ``build_cell_width_lat_lon()`` method to define a lon/lat map of cell width. They can override the ``make_jigsaw_mesh()`` method to change how the jigsaw mesh is generated. Attributes ---------- cell_widt... | QuasiUniformSphericalMeshStep | [
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuasiUniformSphericalMeshStep:
"""A step for creating a quasi-uniform JIGSAW mesh with a constant approximate cell width. Subclasses can override the ``build_cell_width_lat_lon()`` method to define a lon/lat map of cell width. They can override the ``make_jigsaw_mesh()`` method to change how the ... | stack_v2_sparse_classes_75kplus_train_066306 | 17,773 | permissive | [
{
"docstring": "Create a new step Parameters ---------- test_case : compass.testcase.TestCase The test case this step belongs to name : str, optional the name of the step subdir : {str, None}, optional the subdirectory for the step cell_width : float, optional The approximate cell width in km of the mesh if con... | 5 | stack_v2_sparse_classes_30k_train_011115 | Implement the Python class `QuasiUniformSphericalMeshStep` described below.
Class description:
A step for creating a quasi-uniform JIGSAW mesh with a constant approximate cell width. Subclasses can override the ``build_cell_width_lat_lon()`` method to define a lon/lat map of cell width. They can override the ``make_ji... | Implement the Python class `QuasiUniformSphericalMeshStep` described below.
Class description:
A step for creating a quasi-uniform JIGSAW mesh with a constant approximate cell width. Subclasses can override the ``build_cell_width_lat_lon()`` method to define a lon/lat map of cell width. They can override the ``make_ji... | 0b7440f0aa77c1ae052922a39e646bd35c267661 | <|skeleton|>
class QuasiUniformSphericalMeshStep:
"""A step for creating a quasi-uniform JIGSAW mesh with a constant approximate cell width. Subclasses can override the ``build_cell_width_lat_lon()`` method to define a lon/lat map of cell width. They can override the ``make_jigsaw_mesh()`` method to change how the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QuasiUniformSphericalMeshStep:
"""A step for creating a quasi-uniform JIGSAW mesh with a constant approximate cell width. Subclasses can override the ``build_cell_width_lat_lon()`` method to define a lon/lat map of cell width. They can override the ``make_jigsaw_mesh()`` method to change how the jigsaw mesh i... | the_stack_v2_python_sparse | compass/mesh/spherical.py | MPAS-Dev/compass | train | 10 |
5bd1b2096685be50dc512f52c12b1cf16e4a556d | [
"ClarinService.__init__(self)\nself.url_base = 'http://ws.clarin-pl.eu/nlprest2/base/startTask'\nself.url_check = 'http://ws.clarin-pl.eu/nlprest2/base/getStatus'\nself.url_download = 'http://ws.clarin-pl.eu/nlprest2/base/download'\nself.file_id = ''\nself.compressed_suffix = 'ann_morphosyntax.xml.gz'",
"raw_resp... | <|body_start_0|>
ClarinService.__init__(self)
self.url_base = 'http://ws.clarin-pl.eu/nlprest2/base/startTask'
self.url_check = 'http://ws.clarin-pl.eu/nlprest2/base/getStatus'
self.url_download = 'http://ws.clarin-pl.eu/nlprest2/base/download'
self.file_id = ''
self.comp... | Extended service for calling clarin backend api that must be called in asynchronous way | AsynchronousClarinService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsynchronousClarinService:
"""Extended service for calling clarin backend api that must be called in asynchronous way"""
def __init__(self):
"""Init service with asynchronous url"""
<|body_0|>
def is_document_ready(self) -> bool:
"""Ask clarin backend whether pro... | stack_v2_sparse_classes_75kplus_train_066307 | 9,033 | permissive | [
{
"docstring": "Init service with asynchronous url",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Ask clarin backend whether processed document is ready",
"name": "is_document_ready",
"signature": "def is_document_ready(self) -> bool"
},
{
"docstring":... | 5 | stack_v2_sparse_classes_30k_train_047250 | Implement the Python class `AsynchronousClarinService` described below.
Class description:
Extended service for calling clarin backend api that must be called in asynchronous way
Method signatures and docstrings:
- def __init__(self): Init service with asynchronous url
- def is_document_ready(self) -> bool: Ask clari... | Implement the Python class `AsynchronousClarinService` described below.
Class description:
Extended service for calling clarin backend api that must be called in asynchronous way
Method signatures and docstrings:
- def __init__(self): Init service with asynchronous url
- def is_document_ready(self) -> bool: Ask clari... | af03252e19075feec3fa478fa271ea3ae8cf8d11 | <|skeleton|>
class AsynchronousClarinService:
"""Extended service for calling clarin backend api that must be called in asynchronous way"""
def __init__(self):
"""Init service with asynchronous url"""
<|body_0|>
def is_document_ready(self) -> bool:
"""Ask clarin backend whether pro... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AsynchronousClarinService:
"""Extended service for calling clarin backend api that must be called in asynchronous way"""
def __init__(self):
"""Init service with asynchronous url"""
ClarinService.__init__(self)
self.url_base = 'http://ws.clarin-pl.eu/nlprest2/base/startTask'
... | the_stack_v2_python_sparse | services/ClarinServices.py | kubasikora/WEDT-Projekt | train | 0 |
b8567b9a89b79055688cd8461af3949d6a9dc843 | [
"result = []\nfor email in emails:\n result.append(self.newEmail(email))\nreturn len(set(result))",
"a = email.index('+')\nb = email.index('@')\nList = email[:a].split('.')\nres_s = ''\nfor s in List:\n res_s += s\nreturn res_s + email[b:]"
] | <|body_start_0|>
result = []
for email in emails:
result.append(self.newEmail(email))
return len(set(result))
<|end_body_0|>
<|body_start_1|>
a = email.index('+')
b = email.index('@')
List = email[:a].split('.')
res_s = ''
for s in List:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numUniqueEmails(self, emails):
""":type emails: List[str] :rtype: int"""
<|body_0|>
def newEmail(self, email):
"""按规则转换之后的emali"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = []
for email in emails:
result... | stack_v2_sparse_classes_75kplus_train_066308 | 615 | no_license | [
{
"docstring": ":type emails: List[str] :rtype: int",
"name": "numUniqueEmails",
"signature": "def numUniqueEmails(self, emails)"
},
{
"docstring": "按规则转换之后的emali",
"name": "newEmail",
"signature": "def newEmail(self, email)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015512 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numUniqueEmails(self, emails): :type emails: List[str] :rtype: int
- def newEmail(self, email): 按规则转换之后的emali | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numUniqueEmails(self, emails): :type emails: List[str] :rtype: int
- def newEmail(self, email): 按规则转换之后的emali
<|skeleton|>
class Solution:
def numUniqueEmails(self, ema... | 2df5d3b361bc7d25cd3d2afd5ac1c64fbc303920 | <|skeleton|>
class Solution:
def numUniqueEmails(self, emails):
""":type emails: List[str] :rtype: int"""
<|body_0|>
def newEmail(self, email):
"""按规则转换之后的emali"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def numUniqueEmails(self, emails):
""":type emails: List[str] :rtype: int"""
result = []
for email in emails:
result.append(self.newEmail(email))
return len(set(result))
def newEmail(self, email):
"""按规则转换之后的emali"""
a = email.index('+... | the_stack_v2_python_sparse | leetcode_929.py | SongJialiJiali/test | train | 0 | |
072a9010e93fdc08754c447269121d117e034df4 | [
"if self.dbconn.version < 90100:\n return\nfor ext in self.fetch():\n self[ext.key()] = ext",
"for key in inexts:\n if not key.startswith('extension '):\n raise KeyError('Unrecognized object type: %s' % key)\n ext = key[10:]\n inexten = inexts[key]\n self[ext] = Extension(name=ext, descri... | <|body_start_0|>
if self.dbconn.version < 90100:
return
for ext in self.fetch():
self[ext.key()] = ext
<|end_body_0|>
<|body_start_1|>
for key in inexts:
if not key.startswith('extension '):
raise KeyError('Unrecognized object type: %s' % key)... | The collection of extensions in a database | ExtensionDict | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExtensionDict:
"""The collection of extensions in a database"""
def _from_catalog(self):
"""Initialize the dictionary of extensions by querying the catalogs"""
<|body_0|>
def from_map(self, inexts, langtempls, newdb):
"""Initalize the dictionary of extensions by ... | stack_v2_sparse_classes_75kplus_train_066309 | 4,548 | permissive | [
{
"docstring": "Initialize the dictionary of extensions by querying the catalogs",
"name": "_from_catalog",
"signature": "def _from_catalog(self)"
},
{
"docstring": "Initalize the dictionary of extensions by converting the input map :param inexts: YAML map defining the extensions :param langtemp... | 4 | stack_v2_sparse_classes_30k_train_043741 | Implement the Python class `ExtensionDict` described below.
Class description:
The collection of extensions in a database
Method signatures and docstrings:
- def _from_catalog(self): Initialize the dictionary of extensions by querying the catalogs
- def from_map(self, inexts, langtempls, newdb): Initalize the diction... | Implement the Python class `ExtensionDict` described below.
Class description:
The collection of extensions in a database
Method signatures and docstrings:
- def _from_catalog(self): Initialize the dictionary of extensions by querying the catalogs
- def from_map(self, inexts, langtempls, newdb): Initalize the diction... | 0133f3bc522890e0564d27de6791824acb4d2773 | <|skeleton|>
class ExtensionDict:
"""The collection of extensions in a database"""
def _from_catalog(self):
"""Initialize the dictionary of extensions by querying the catalogs"""
<|body_0|>
def from_map(self, inexts, langtempls, newdb):
"""Initalize the dictionary of extensions by ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExtensionDict:
"""The collection of extensions in a database"""
def _from_catalog(self):
"""Initialize the dictionary of extensions by querying the catalogs"""
if self.dbconn.version < 90100:
return
for ext in self.fetch():
self[ext.key()] = ext
def fr... | the_stack_v2_python_sparse | pyrseas/dbobject/extension.py | vayerx/Pyrseas | train | 1 |
325c81baa5dde6d029b695b92740cc9ce1e8d08c | [
"if pool.vcf == None:\n self.sc = SnvCaller.SnvCaller(pool)\n self.sc.callSNVs(pool)\nself._executeBeagle(pool)",
"if pool.vcf.bcf == True:\n self.sc.callSNVs(pool)\nprefixes = self._createBeagleInput(pool)\nnewPrefixes = []\nfor prefix in prefixes:\n inputFile = prefix + '.BEAGLE.PL'\n cmd = 'java... | <|body_start_0|>
if pool.vcf == None:
self.sc = SnvCaller.SnvCaller(pool)
self.sc.callSNVs(pool)
self._executeBeagle(pool)
<|end_body_0|>
<|body_start_1|>
if pool.vcf.bcf == True:
self.sc.callSNVs(pool)
prefixes = self._createBeagleInput(pool)
... | The Haplotyper class regulates the haplotyping of a vcf file | Haplotyper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Haplotyper:
"""The Haplotyper class regulates the haplotyping of a vcf file"""
def callHaplotypes(self, pool):
"""The method callHaplotypes calls the haplotypes of a vcf file. When the vcf file is not set, first the SNVs are called with the :py:class:`SnvCaller.SnvCaller` object In f... | stack_v2_sparse_classes_75kplus_train_066310 | 3,519 | no_license | [
{
"docstring": "The method callHaplotypes calls the haplotypes of a vcf file. When the vcf file is not set, first the SNVs are called with the :py:class:`SnvCaller.SnvCaller` object In future when multiple programs for haplotyping are implemented, here the check will be performed which haplotyper to execute. Fi... | 4 | stack_v2_sparse_classes_30k_train_009999 | Implement the Python class `Haplotyper` described below.
Class description:
The Haplotyper class regulates the haplotyping of a vcf file
Method signatures and docstrings:
- def callHaplotypes(self, pool): The method callHaplotypes calls the haplotypes of a vcf file. When the vcf file is not set, first the SNVs are ca... | Implement the Python class `Haplotyper` described below.
Class description:
The Haplotyper class regulates the haplotyping of a vcf file
Method signatures and docstrings:
- def callHaplotypes(self, pool): The method callHaplotypes calls the haplotypes of a vcf file. When the vcf file is not set, first the SNVs are ca... | 2543f2bdb61fb07e2ee8ab76ffc930c13f0a4dbb | <|skeleton|>
class Haplotyper:
"""The Haplotyper class regulates the haplotyping of a vcf file"""
def callHaplotypes(self, pool):
"""The method callHaplotypes calls the haplotypes of a vcf file. When the vcf file is not set, first the SNVs are called with the :py:class:`SnvCaller.SnvCaller` object In f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Haplotyper:
"""The Haplotyper class regulates the haplotyping of a vcf file"""
def callHaplotypes(self, pool):
"""The method callHaplotypes calls the haplotypes of a vcf file. When the vcf file is not set, first the SNVs are called with the :py:class:`SnvCaller.SnvCaller` object In future when mu... | the_stack_v2_python_sparse | pythonCodeBase/src/programs/Haplotyper.py | VLPB/VLPB | train | 0 |
ce49af528a5ce92e32f7814b34783ac3e845c0b0 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AudioRoutingGroup()",
"from .entity import Entity\nfrom .routing_mode import RoutingMode\nfrom .entity import Entity\nfrom .routing_mode import RoutingMode\nfields: Dict[str, Callable[[Any], None]] = {'receivers': lambda n: setattr(sel... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AudioRoutingGroup()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .routing_mode import RoutingMode
from .entity import Entity
from .routing_mode import ... | AudioRoutingGroup | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AudioRoutingGroup:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AudioRoutingGroup:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object... | stack_v2_sparse_classes_75kplus_train_066311 | 2,660 | 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: AudioRoutingGroup",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_v... | 3 | stack_v2_sparse_classes_30k_train_046833 | Implement the Python class `AudioRoutingGroup` described below.
Class description:
Implement the AudioRoutingGroup class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AudioRoutingGroup: Creates a new instance of the appropriate class based on discrim... | Implement the Python class `AudioRoutingGroup` described below.
Class description:
Implement the AudioRoutingGroup class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AudioRoutingGroup: Creates a new instance of the appropriate class based on discrim... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AudioRoutingGroup:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AudioRoutingGroup:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AudioRoutingGroup:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AudioRoutingGroup:
"""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: Audi... | the_stack_v2_python_sparse | msgraph/generated/models/audio_routing_group.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
ba8cbde3934a244f362fc11ce2e8584d80fe25b9 | [
"super(SimulatedExecutionHandler, self).__init__(data_handler.events, False)\nself.data_handler = data_handler\nself.transaction_cost = transaction_cost",
"symbol = order_event.symbol\nquantity = order_event.quantity\naction = params.action_dict[order_event.direction, order_event.trade_type]\nprice_id = [params.P... | <|body_start_0|>
super(SimulatedExecutionHandler, self).__init__(data_handler.events, False)
self.data_handler = data_handler
self.transaction_cost = transaction_cost
<|end_body_0|>
<|body_start_1|>
symbol = order_event.symbol
quantity = order_event.quantity
action = par... | Simulated Execution Handler Class The simulated execution handler simply converts all order objects into their equivalent fill objects automatically without latency, slippage or fill-ratio issues. This allows a straightforward 'first go' test of any strategy, before implementation with a more sophisticated execution ha... | SimulatedExecutionHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimulatedExecutionHandler:
"""Simulated Execution Handler Class The simulated execution handler simply converts all order objects into their equivalent fill objects automatically without latency, slippage or fill-ratio issues. This allows a straightforward 'first go' test of any strategy, before ... | stack_v2_sparse_classes_75kplus_train_066312 | 2,574 | permissive | [
{
"docstring": "Initialize parameters of the simulated execution handler object.",
"name": "__init__",
"signature": "def __init__(self, data_handler, transaction_cost=0.0005)"
},
{
"docstring": "Implementation of abstract base class method.",
"name": "execute_order",
"signature": "def ex... | 2 | stack_v2_sparse_classes_30k_train_036937 | Implement the Python class `SimulatedExecutionHandler` described below.
Class description:
Simulated Execution Handler Class The simulated execution handler simply converts all order objects into their equivalent fill objects automatically without latency, slippage or fill-ratio issues. This allows a straightforward '... | Implement the Python class `SimulatedExecutionHandler` described below.
Class description:
Simulated Execution Handler Class The simulated execution handler simply converts all order objects into their equivalent fill objects automatically without latency, slippage or fill-ratio issues. This allows a straightforward '... | e2e9d638c68947d24f1260d35a3527dd84c2523f | <|skeleton|>
class SimulatedExecutionHandler:
"""Simulated Execution Handler Class The simulated execution handler simply converts all order objects into their equivalent fill objects automatically without latency, slippage or fill-ratio issues. This allows a straightforward 'first go' test of any strategy, before ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SimulatedExecutionHandler:
"""Simulated Execution Handler Class The simulated execution handler simply converts all order objects into their equivalent fill objects automatically without latency, slippage or fill-ratio issues. This allows a straightforward 'first go' test of any strategy, before implementatio... | the_stack_v2_python_sparse | odin/handlers/execution_handler/simulated_execution_handler.py | stjordanis/Odin | train | 0 |
224e05850e26d30e7e3be47255af498784dd0fc6 | [
"parser = super(ListVnfLcmOp, self).get_parser(program_name)\nparser.add_argument('--filter', metavar='<filter>', help=_('Attribute-based-filtering parameters'))\nfields_exclusive_group = parser.add_mutually_exclusive_group(required=False)\nfields_exclusive_group.add_argument('--fields', metavar='<fields>', help=_(... | <|body_start_0|>
parser = super(ListVnfLcmOp, self).get_parser(program_name)
parser.add_argument('--filter', metavar='<filter>', help=_('Attribute-based-filtering parameters'))
fields_exclusive_group = parser.add_mutually_exclusive_group(required=False)
fields_exclusive_group.add_argumen... | ListVnfLcmOp | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListVnfLcmOp:
def get_parser(self, program_name):
"""Add arguments to parser. Args: program_name ([type]): program name Returns: parser([ArgumentParser]):"""
<|body_0|>
def get_attributes(self, exclude=None):
"""Get attributes. Args: exclude([exclude]): a list of fie... | stack_v2_sparse_classes_75kplus_train_066313 | 11,909 | permissive | [
{
"docstring": "Add arguments to parser. Args: program_name ([type]): program name Returns: parser([ArgumentParser]):",
"name": "get_parser",
"signature": "def get_parser(self, program_name)"
},
{
"docstring": "Get attributes. Args: exclude([exclude]): a list of fields which needs to exclude. Re... | 3 | stack_v2_sparse_classes_30k_train_013334 | Implement the Python class `ListVnfLcmOp` described below.
Class description:
Implement the ListVnfLcmOp class.
Method signatures and docstrings:
- def get_parser(self, program_name): Add arguments to parser. Args: program_name ([type]): program name Returns: parser([ArgumentParser]):
- def get_attributes(self, exclu... | Implement the Python class `ListVnfLcmOp` described below.
Class description:
Implement the ListVnfLcmOp class.
Method signatures and docstrings:
- def get_parser(self, program_name): Add arguments to parser. Args: program_name ([type]): program name Returns: parser([ArgumentParser]):
- def get_attributes(self, exclu... | e8460be8c53ad5dfbac720367cf0ae2c3291dc3b | <|skeleton|>
class ListVnfLcmOp:
def get_parser(self, program_name):
"""Add arguments to parser. Args: program_name ([type]): program name Returns: parser([ArgumentParser]):"""
<|body_0|>
def get_attributes(self, exclude=None):
"""Get attributes. Args: exclude([exclude]): a list of fie... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ListVnfLcmOp:
def get_parser(self, program_name):
"""Add arguments to parser. Args: program_name ([type]): program name Returns: parser([ArgumentParser]):"""
parser = super(ListVnfLcmOp, self).get_parser(program_name)
parser.add_argument('--filter', metavar='<filter>', help=_('Attribut... | the_stack_v2_python_sparse | tackerclient/osc/v1/vnflcm/vnflcm_op_occs.py | openstack/python-tackerclient | train | 21 | |
a3f5ee8c94ead2d0b645203dcbfaa4d5feb95c41 | [
"vocab_set = set(list())\nfor document in data_set:\n vocab_set = vocab_set | set(document)\nreturn list(vocab_set)",
"return_vec = [0] * len(vocab_list)\nfor word in input_set:\n if word in vocab_list:\n return_vec[vocab_list.index(word)] = 1\n else:\n raise ActionError('the word: %s is no... | <|body_start_0|>
vocab_set = set(list())
for document in data_set:
vocab_set = vocab_set | set(document)
return list(vocab_set)
<|end_body_0|>
<|body_start_1|>
return_vec = [0] * len(vocab_list)
for word in input_set:
if word in vocab_list:
... | 朴素贝叶斯工具类 | BayesTool | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BayesTool:
"""朴素贝叶斯工具类"""
def create_vocab_list(data_set: list) -> list:
"""将模拟数据去重合成一个单一词汇表, 每一个词汇代表一个特征(去重) >>> BayesTool.create_vocab_list([['my', 'dog'], ['my']]) list('my', 'dog') :return:"""
<|body_0|>
def set_word_2_vec(vocab_list: list, input_set: list):
... | stack_v2_sparse_classes_75kplus_train_066314 | 2,170 | no_license | [
{
"docstring": "将模拟数据去重合成一个单一词汇表, 每一个词汇代表一个特征(去重) >>> BayesTool.create_vocab_list([['my', 'dog'], ['my']]) list('my', 'dog') :return:",
"name": "create_vocab_list",
"signature": "def create_vocab_list(data_set: list) -> list"
},
{
"docstring": "词集模型 检测input_set中的词汇是否属于vocab_list词汇表, 如果是则置为1, 否则为... | 3 | null | Implement the Python class `BayesTool` described below.
Class description:
朴素贝叶斯工具类
Method signatures and docstrings:
- def create_vocab_list(data_set: list) -> list: 将模拟数据去重合成一个单一词汇表, 每一个词汇代表一个特征(去重) >>> BayesTool.create_vocab_list([['my', 'dog'], ['my']]) list('my', 'dog') :return:
- def set_word_2_vec(vocab_list: ... | Implement the Python class `BayesTool` described below.
Class description:
朴素贝叶斯工具类
Method signatures and docstrings:
- def create_vocab_list(data_set: list) -> list: 将模拟数据去重合成一个单一词汇表, 每一个词汇代表一个特征(去重) >>> BayesTool.create_vocab_list([['my', 'dog'], ['my']]) list('my', 'dog') :return:
- def set_word_2_vec(vocab_list: ... | d13bb083fac7ad9886e1407e6d958139b7f87e26 | <|skeleton|>
class BayesTool:
"""朴素贝叶斯工具类"""
def create_vocab_list(data_set: list) -> list:
"""将模拟数据去重合成一个单一词汇表, 每一个词汇代表一个特征(去重) >>> BayesTool.create_vocab_list([['my', 'dog'], ['my']]) list('my', 'dog') :return:"""
<|body_0|>
def set_word_2_vec(vocab_list: list, input_set: list):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BayesTool:
"""朴素贝叶斯工具类"""
def create_vocab_list(data_set: list) -> list:
"""将模拟数据去重合成一个单一词汇表, 每一个词汇代表一个特征(去重) >>> BayesTool.create_vocab_list([['my', 'dog'], ['my']]) list('my', 'dog') :return:"""
vocab_set = set(list())
for document in data_set:
vocab_set = vocab_set ... | the_stack_v2_python_sparse | MachineLearingInAction/Code/Chapter4_Bayes/bayes_tool.py | shanwenhao1/Machine-Learning | train | 2 |
a5adc74c57ba674710d74d43fc68cf33969adc4b | [
"parser = reqparse.RequestParser()\nparser.add_argument('id', type=str, help='用例id')\nparser.add_argument('cur_page', type=int, help='当前属于第几页')\nparser.add_argument('pagesize', type=int, help='每页显示的数量')\nargs = parser.parse_args()\nif args.get('id'):\n paginates = Uicaseinfo.query.filter(Uicaseinfo.id == args.ge... | <|body_start_0|>
parser = reqparse.RequestParser()
parser.add_argument('id', type=str, help='用例id')
parser.add_argument('cur_page', type=int, help='当前属于第几页')
parser.add_argument('pagesize', type=int, help='每页显示的数量')
args = parser.parse_args()
if args.get('id'):
... | CaseInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CaseInfo:
def get(self):
"""根据id返回查询的数据测试用例"""
<|body_0|>
def post(self):
"""新增测试用例保存表数据"""
<|body_1|>
def put(self):
"""新增测试用例保存表数据"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
parser = reqparse.RequestParser()
parse... | stack_v2_sparse_classes_75kplus_train_066315 | 14,649 | no_license | [
{
"docstring": "根据id返回查询的数据测试用例",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "新增测试用例保存表数据",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "新增测试用例保存表数据",
"name": "put",
"signature": "def put(self)"
}
] | 3 | null | Implement the Python class `CaseInfo` described below.
Class description:
Implement the CaseInfo class.
Method signatures and docstrings:
- def get(self): 根据id返回查询的数据测试用例
- def post(self): 新增测试用例保存表数据
- def put(self): 新增测试用例保存表数据 | Implement the Python class `CaseInfo` described below.
Class description:
Implement the CaseInfo class.
Method signatures and docstrings:
- def get(self): 根据id返回查询的数据测试用例
- def post(self): 新增测试用例保存表数据
- def put(self): 新增测试用例保存表数据
<|skeleton|>
class CaseInfo:
def get(self):
"""根据id返回查询的数据测试用例"""
... | 0025cc46fa84db658987c9df109de4e5c3c4f5b9 | <|skeleton|>
class CaseInfo:
def get(self):
"""根据id返回查询的数据测试用例"""
<|body_0|>
def post(self):
"""新增测试用例保存表数据"""
<|body_1|>
def put(self):
"""新增测试用例保存表数据"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CaseInfo:
def get(self):
"""根据id返回查询的数据测试用例"""
parser = reqparse.RequestParser()
parser.add_argument('id', type=str, help='用例id')
parser.add_argument('cur_page', type=int, help='当前属于第几页')
parser.add_argument('pagesize', type=int, help='每页显示的数量')
args = parser.pa... | the_stack_v2_python_sparse | uiplatform/router/operationdata.py | abao0713/erybjp | train | 0 | |
62288bb47c70bd3b05fa887bf99c3deb3ba7d5c1 | [
"def iterator(node, arr):\n if node:\n arr.append(str(node.val))\n iterator(node.left, arr)\n iterator(node.right, arr)\n else:\n arr.append('null')\nresult = []\niterator(root, result)\nreturn ' '.join(result)",
"def iterator(it):\n val = next(it)\n if val != 'null':\n ... | <|body_start_0|>
def iterator(node, arr):
if node:
arr.append(str(node.val))
iterator(node.left, arr)
iterator(node.right, arr)
else:
arr.append('null')
result = []
iterator(root, result)
return ' '.j... | 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_75kplus_train_066316 | 1,430 | 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_022224 | 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:... | 057ed5c6fe19268f36a1d5051d27b07aae0b63e0 | <|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_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def iterator(node, arr):
if node:
arr.append(str(node.val))
iterator(node.left, arr)
iterator(node.right, arr)
els... | the_stack_v2_python_sparse | 2020/2020-03/06/eugene.py | wavetogether/wave_algorithm_challenge | train | 3 | |
bf9ec1291a1bc07293e6bfcbd16b5c752f394229 | [
"ans = ''\nfor chs in zip(*strs):\n chs_set = set(chs)\n if len(chs_set) == 1:\n ans += chs_set.pop()\n else:\n return ans\nreturn ans",
"if not strs:\n return ''\nans = ''\nmin_len = min([len(s) for s in strs])\nfor cidx in range(min_len):\n if len({s[cidx] for s in strs}) == 1:\n ... | <|body_start_0|>
ans = ''
for chs in zip(*strs):
chs_set = set(chs)
if len(chs_set) == 1:
ans += chs_set.pop()
else:
return ans
return ans
<|end_body_0|>
<|body_start_1|>
if not strs:
return ''
ans =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_0|>
def longestCommonPrefix_v0(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ans = ''
for chs i... | stack_v2_sparse_classes_75kplus_train_066317 | 1,845 | no_license | [
{
"docstring": ":type strs: List[str] :rtype: str",
"name": "longestCommonPrefix",
"signature": "def longestCommonPrefix(self, strs)"
},
{
"docstring": ":type strs: List[str] :rtype: str",
"name": "longestCommonPrefix_v0",
"signature": "def longestCommonPrefix_v0(self, strs)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str
- def longestCommonPrefix_v0(self, strs): :type strs: List[str] :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str
- def longestCommonPrefix_v0(self, strs): :type strs: List[str] :rtype: str
<|skeleton|>
class Solution:
... | b5e09f24e8e96454dc99e20281e853fb9fcc85ed | <|skeleton|>
class Solution:
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_0|>
def longestCommonPrefix_v0(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str"""
ans = ''
for chs in zip(*strs):
chs_set = set(chs)
if len(chs_set) == 1:
ans += chs_set.pop()
else:
return ans
return ans
... | the_stack_v2_python_sparse | python/14_Longest_Common_Prefix.py | Moby5/myleetcode | train | 2 | |
2905a2635964abbc53d3bb28889666d187455915 | [
"super().__init__()\nself.enc_img_attn = enc_img_attn\nif enc_img_attn == 'flat':\n self.multimodal_attn = FlatMMCrossAttentionSublayer(model_dim, n_heads, dropout, attn_dropout, pre_norm)\nelse:\n self.self_attn = SelfAttentionSublayer(model_dim, n_heads, dropout, attn_dropout, pre_norm)\nself.feed_forward =... | <|body_start_0|>
super().__init__()
self.enc_img_attn = enc_img_attn
if enc_img_attn == 'flat':
self.multimodal_attn = FlatMMCrossAttentionSublayer(model_dim, n_heads, dropout, attn_dropout, pre_norm)
else:
self.self_attn = SelfAttentionSublayer(model_dim, n_heads... | TFEncoderBlock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TFEncoderBlock:
def __init__(self, model_dim, ff_dim, n_heads, ff_activ='gelu', dropout=0.1, attn_dropout=0.0, pre_norm=True, enc_img_attn=None):
"""Creates a TFEncoderBlock, consisting of a self-attention sublayer and a position-wise feed forward sublayer. :param model_dim: The model di... | stack_v2_sparse_classes_75kplus_train_066318 | 6,612 | permissive | [
{
"docstring": "Creates a TFEncoderBlock, consisting of a self-attention sublayer and a position-wise feed forward sublayer. :param model_dim: The model dimensions. :param ff_dim: The feed forward network dimensions. :param n_heads: The number of attention heads. :param ff_activ: The feed forward network activa... | 2 | stack_v2_sparse_classes_30k_train_014733 | Implement the Python class `TFEncoderBlock` described below.
Class description:
Implement the TFEncoderBlock class.
Method signatures and docstrings:
- def __init__(self, model_dim, ff_dim, n_heads, ff_activ='gelu', dropout=0.1, attn_dropout=0.0, pre_norm=True, enc_img_attn=None): Creates a TFEncoderBlock, consisting... | Implement the Python class `TFEncoderBlock` described below.
Class description:
Implement the TFEncoderBlock class.
Method signatures and docstrings:
- def __init__(self, model_dim, ff_dim, n_heads, ff_activ='gelu', dropout=0.1, attn_dropout=0.0, pre_norm=True, enc_img_attn=None): Creates a TFEncoderBlock, consisting... | 6250b33dc518b3195da4fc9cc8d32ba7ada958c0 | <|skeleton|>
class TFEncoderBlock:
def __init__(self, model_dim, ff_dim, n_heads, ff_activ='gelu', dropout=0.1, attn_dropout=0.0, pre_norm=True, enc_img_attn=None):
"""Creates a TFEncoderBlock, consisting of a self-attention sublayer and a position-wise feed forward sublayer. :param model_dim: The model di... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TFEncoderBlock:
def __init__(self, model_dim, ff_dim, n_heads, ff_activ='gelu', dropout=0.1, attn_dropout=0.0, pre_norm=True, enc_img_attn=None):
"""Creates a TFEncoderBlock, consisting of a self-attention sublayer and a position-wise feed forward sublayer. :param model_dim: The model dimensions. :par... | the_stack_v2_python_sparse | pysimt/layers/encoders/transformers.py | welvin21/pysimt | train | 0 | |
c62c2f563f3c36428319d5c13bb0644237e3ebd4 | [
"self.total_iterations = 0\nself._current_iteration_delta = 0\nself.last_iteration_delta = 0\nself._model = model\nself._edges = list(model.edges)\nself._current_edge_index = 0\nself._max_iterations = max_iterations\nself._converge_delta = converge_delta",
"self.total_iterations = 0\nself._current_iteration_delta... | <|body_start_0|>
self.total_iterations = 0
self._current_iteration_delta = 0
self.last_iteration_delta = 0
self._model = model
self._edges = list(model.edges)
self._current_edge_index = 0
self._max_iterations = max_iterations
self._converge_delta = converg... | Defines an update ordering where updates are done in both directions for each edge in the cluster graph. | FloodingProtocol | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FloodingProtocol:
"""Defines an update ordering where updates are done in both directions for each edge in the cluster graph."""
def __init__(self, model, max_iterations=30, converge_delta=10 ** (-10)):
"""Constructor. :param model: The model. :param max_iterations: Maximum number of... | stack_v2_sparse_classes_75kplus_train_066319 | 18,882 | permissive | [
{
"docstring": "Constructor. :param model: The model. :param max_iterations: Maximum number of times to update each edge. :param converge_delta: Stop updates after the change in potential between two passes over all the edges is less than `converge_delta`.",
"name": "__init__",
"signature": "def __init_... | 3 | stack_v2_sparse_classes_30k_train_050429 | Implement the Python class `FloodingProtocol` described below.
Class description:
Defines an update ordering where updates are done in both directions for each edge in the cluster graph.
Method signatures and docstrings:
- def __init__(self, model, max_iterations=30, converge_delta=10 ** (-10)): Constructor. :param m... | Implement the Python class `FloodingProtocol` described below.
Class description:
Defines an update ordering where updates are done in both directions for each edge in the cluster graph.
Method signatures and docstrings:
- def __init__(self, model, max_iterations=30, converge_delta=10 ** (-10)): Constructor. :param m... | 445b2cf8736a4a28cff2b074a32afe8fe6986d53 | <|skeleton|>
class FloodingProtocol:
"""Defines an update ordering where updates are done in both directions for each edge in the cluster graph."""
def __init__(self, model, max_iterations=30, converge_delta=10 ** (-10)):
"""Constructor. :param model: The model. :param max_iterations: Maximum number of... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FloodingProtocol:
"""Defines an update ordering where updates are done in both directions for each edge in the cluster graph."""
def __init__(self, model, max_iterations=30, converge_delta=10 ** (-10)):
"""Constructor. :param model: The model. :param max_iterations: Maximum number of times to upd... | the_stack_v2_python_sparse | Statistical_methods/LoopyBeliefPropagation/pyugm/infer_message.py | WN1695173791/Background-Subtraction-Unsupervised-Learning | train | 1 |
f283c3eea95ff591eb2361fffd07b3fba56e5767 | [
"try:\n user = User.objects.get(pk=user_pk)\nexcept User.DoesNotExist:\n return Response({'message': _('Usuario no encontrado')}, status=status.HTTP_404_NOT_FOUND)\nif request.user == user:\n user.profile = Profile.objects.get(user=user)\n serializer = self.serializer_class(user)\n return Response(se... | <|body_start_0|>
try:
user = User.objects.get(pk=user_pk)
except User.DoesNotExist:
return Response({'message': _('Usuario no encontrado')}, status=status.HTTP_404_NOT_FOUND)
if request.user == user:
user.profile = Profile.objects.get(user=user)
se... | View for handle account creation | UserView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserView:
"""View for handle account creation"""
def get(self, request, user_pk):
"""Get the account data using Token authorization :param user_pk: :param request: :return:"""
<|body_0|>
def put(self, request, user_pk):
"""Handle the account data update :param us... | stack_v2_sparse_classes_75kplus_train_066320 | 3,798 | no_license | [
{
"docstring": "Get the account data using Token authorization :param user_pk: :param request: :return:",
"name": "get",
"signature": "def get(self, request, user_pk)"
},
{
"docstring": "Handle the account data update :param user_pk: :param request: :return:",
"name": "put",
"signature":... | 2 | null | Implement the Python class `UserView` described below.
Class description:
View for handle account creation
Method signatures and docstrings:
- def get(self, request, user_pk): Get the account data using Token authorization :param user_pk: :param request: :return:
- def put(self, request, user_pk): Handle the account ... | Implement the Python class `UserView` described below.
Class description:
View for handle account creation
Method signatures and docstrings:
- def get(self, request, user_pk): Get the account data using Token authorization :param user_pk: :param request: :return:
- def put(self, request, user_pk): Handle the account ... | 5c6f6443c7aaffbd0414c25f9adcdba72aeb7638 | <|skeleton|>
class UserView:
"""View for handle account creation"""
def get(self, request, user_pk):
"""Get the account data using Token authorization :param user_pk: :param request: :return:"""
<|body_0|>
def put(self, request, user_pk):
"""Handle the account data update :param us... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserView:
"""View for handle account creation"""
def get(self, request, user_pk):
"""Get the account data using Token authorization :param user_pk: :param request: :return:"""
try:
user = User.objects.get(pk=user_pk)
except User.DoesNotExist:
return Respons... | the_stack_v2_python_sparse | shop/applications/api_v1/views/users.py | RobertoFZ/shop-api | train | 0 |
2ec2443e9225a0c528fd3f3e38b5a8f66e1c2455 | [
"html = helpers.get_content(url)\nif not html:\n return None\nsoup = BeautifulSoup(html)\narticle = soup.article\nheadline = helpers.decode(article.h1.string)\nparagraphs = article.find_all('p', attrs={'class': None})\nbody = ' '.join([helpers.decode(p.get_text()) for p in paragraphs])\nreturn news_interface.Art... | <|body_start_0|>
html = helpers.get_content(url)
if not html:
return None
soup = BeautifulSoup(html)
article = soup.article
headline = helpers.decode(article.h1.string)
paragraphs = article.find_all('p', attrs={'class': None})
body = ' '.join([helpers.... | Methods for interacting with the USA Today website/API. | USAToday | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class USAToday:
"""Methods for interacting with the USA Today website/API."""
def get_article(self, url):
"""Implementation for getting an article from USA Today. url: A URL in the http://www.usatoday.com/story/* domain. Returns: The Article representing the article at that url."""
... | stack_v2_sparse_classes_75kplus_train_066321 | 1,671 | no_license | [
{
"docstring": "Implementation for getting an article from USA Today. url: A URL in the http://www.usatoday.com/story/* domain. Returns: The Article representing the article at that url.",
"name": "get_article",
"signature": "def get_article(self, url)"
},
{
"docstring": "Implementation for keyw... | 2 | stack_v2_sparse_classes_30k_train_037597 | Implement the Python class `USAToday` described below.
Class description:
Methods for interacting with the USA Today website/API.
Method signatures and docstrings:
- def get_article(self, url): Implementation for getting an article from USA Today. url: A URL in the http://www.usatoday.com/story/* domain. Returns: The... | Implement the Python class `USAToday` described below.
Class description:
Methods for interacting with the USA Today website/API.
Method signatures and docstrings:
- def get_article(self, url): Implementation for getting an article from USA Today. url: A URL in the http://www.usatoday.com/story/* domain. Returns: The... | b1adf7d582eb78623a44611dc07749823da84d5f | <|skeleton|>
class USAToday:
"""Methods for interacting with the USA Today website/API."""
def get_article(self, url):
"""Implementation for getting an article from USA Today. url: A URL in the http://www.usatoday.com/story/* domain. Returns: The Article representing the article at that url."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class USAToday:
"""Methods for interacting with the USA Today website/API."""
def get_article(self, url):
"""Implementation for getting an article from USA Today. url: A URL in the http://www.usatoday.com/story/* domain. Returns: The Article representing the article at that url."""
html = helpe... | the_stack_v2_python_sparse | analysis/scraping/usa_today.py | pandrewhk/perspectives | train | 0 |
17a890142194e42a94a7fcb05261ecd6d39400ae | [
"self.BASE_URL = 'https://finviz.com/groups.ashx?{group}&v=310'\nself.url = self.BASE_URL.format(group='g=sector')\nOverview._loadSetting(self)",
"if group not in self.group_dict:\n raise ValueError()\nif order not in self.order_dict:\n raise ValueError()\nself.url = self.BASE_URL.format(group=self.group_di... | <|body_start_0|>
self.BASE_URL = 'https://finviz.com/groups.ashx?{group}&v=310'
self.url = self.BASE_URL.format(group='g=sector')
Overview._loadSetting(self)
<|end_body_0|>
<|body_start_1|>
if group not in self.group_dict:
raise ValueError()
if order not in self.orde... | Spectrum inherit from overview module. Getting information from the finviz group spectrum page. | Spectrum | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Spectrum:
"""Spectrum inherit from overview module. Getting information from the finviz group spectrum page."""
def __init__(self):
"""initiate module"""
<|body_0|>
def ScreenerView(self, group='Sector', order='Name', out_dir=''):
"""Get screener table. Args: gro... | stack_v2_sparse_classes_75kplus_train_066322 | 1,217 | permissive | [
{
"docstring": "initiate module",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Get screener table. Args: group(str): choice of group option. order(str): sort the table by the choice of order.",
"name": "ScreenerView",
"signature": "def ScreenerView(self, group... | 2 | stack_v2_sparse_classes_30k_train_046309 | Implement the Python class `Spectrum` described below.
Class description:
Spectrum inherit from overview module. Getting information from the finviz group spectrum page.
Method signatures and docstrings:
- def __init__(self): initiate module
- def ScreenerView(self, group='Sector', order='Name', out_dir=''): Get scre... | Implement the Python class `Spectrum` described below.
Class description:
Spectrum inherit from overview module. Getting information from the finviz group spectrum page.
Method signatures and docstrings:
- def __init__(self): initiate module
- def ScreenerView(self, group='Sector', order='Name', out_dir=''): Get scre... | 3447ce22a04c02cdfc31e5d3f8e08aeca2abc8d0 | <|skeleton|>
class Spectrum:
"""Spectrum inherit from overview module. Getting information from the finviz group spectrum page."""
def __init__(self):
"""initiate module"""
<|body_0|>
def ScreenerView(self, group='Sector', order='Name', out_dir=''):
"""Get screener table. Args: gro... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Spectrum:
"""Spectrum inherit from overview module. Getting information from the finviz group spectrum page."""
def __init__(self):
"""initiate module"""
self.BASE_URL = 'https://finviz.com/groups.ashx?{group}&v=310'
self.url = self.BASE_URL.format(group='g=sector')
Overvi... | the_stack_v2_python_sparse | finvizfinance/group/spectrum.py | willtejeda/finvizfinance | train | 0 |
1f6374c349a04fadf8a8006876b9e47ff411b776 | [
"if arr is None:\n return\nn = len(arr)\nif n <= 1:\n return\nQuickSort.do_quick_sort(arr, 0, n - 1)",
"if start < end:\n pi = QuickSort.partition(arr, start, end)\n QuickSort.do_quick_sort(arr, start, pi - 1)\n QuickSort.do_quick_sort(arr, pi + 1, end)",
"pivot = arr[end]\ni = start\nfor j in ra... | <|body_start_0|>
if arr is None:
return
n = len(arr)
if n <= 1:
return
QuickSort.do_quick_sort(arr, 0, n - 1)
<|end_body_0|>
<|body_start_1|>
if start < end:
pi = QuickSort.partition(arr, start, end)
QuickSort.do_quick_sort(arr, st... | QuickSort | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuickSort:
def quick_sort(arr):
"""Quick sort arr in place. :param arr: List[int], the list to be sorted. :return: void, list will be sorted in place"""
<|body_0|>
def do_quick_sort(arr, start, end):
"""Quick sort array in memory with given range. :param arr: List[in... | stack_v2_sparse_classes_75kplus_train_066323 | 3,016 | permissive | [
{
"docstring": "Quick sort arr in place. :param arr: List[int], the list to be sorted. :return: void, list will be sorted in place",
"name": "quick_sort",
"signature": "def quick_sort(arr)"
},
{
"docstring": "Quick sort array in memory with given range. :param arr: List[int], list to be sorted :... | 3 | null | Implement the Python class `QuickSort` described below.
Class description:
Implement the QuickSort class.
Method signatures and docstrings:
- def quick_sort(arr): Quick sort arr in place. :param arr: List[int], the list to be sorted. :return: void, list will be sorted in place
- def do_quick_sort(arr, start, end): Qu... | Implement the Python class `QuickSort` described below.
Class description:
Implement the QuickSort class.
Method signatures and docstrings:
- def quick_sort(arr): Quick sort arr in place. :param arr: List[int], the list to be sorted. :return: void, list will be sorted in place
- def do_quick_sort(arr, start, end): Qu... | 8504db89a3f6a1596c0bb7343a4936884b44e6ea | <|skeleton|>
class QuickSort:
def quick_sort(arr):
"""Quick sort arr in place. :param arr: List[int], the list to be sorted. :return: void, list will be sorted in place"""
<|body_0|>
def do_quick_sort(arr, start, end):
"""Quick sort array in memory with given range. :param arr: List[in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QuickSort:
def quick_sort(arr):
"""Quick sort arr in place. :param arr: List[int], the list to be sorted. :return: void, list will be sorted in place"""
if arr is None:
return
n = len(arr)
if n <= 1:
return
QuickSort.do_quick_sort(arr, 0, n - 1)
... | the_stack_v2_python_sparse | sorting/quick_sort.py | fimh/dsa-py | train | 2 | |
3e676a0487467960ba477b169e3e028a22a28896 | [
"line = line.rstrip('\\n')\ntry:\n super(DataSamplerTaskHadoop, self).__init__(line)\nexcept ValueError as e:\n raise DataSamplerTaskInitError('%s' % e)\ntry:\n self._ratio = self.get_attribute('ratio', self._json, 'ratio')\n self._encode = self.get_attribute('encode', self._json, 'code')\n self._dec... | <|body_start_0|>
line = line.rstrip('\n')
try:
super(DataSamplerTaskHadoop, self).__init__(line)
except ValueError as e:
raise DataSamplerTaskInitError('%s' % e)
try:
self._ratio = self.get_attribute('ratio', self._json, 'ratio')
self._enco... | hadoop data sampler task | DataSamplerTaskHadoop | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataSamplerTaskHadoop:
"""hadoop data sampler task"""
def __init__(self, line):
"""Change line to taskconf object Args: line: str Exception: DataSamplerTaskInitError"""
<|body_0|>
def excute(self):
"""begin to sample Args: None Return: 0"""
<|body_1|>
<|... | stack_v2_sparse_classes_75kplus_train_066324 | 6,255 | no_license | [
{
"docstring": "Change line to taskconf object Args: line: str Exception: DataSamplerTaskInitError",
"name": "__init__",
"signature": "def __init__(self, line)"
},
{
"docstring": "begin to sample Args: None Return: 0",
"name": "excute",
"signature": "def excute(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_050512 | Implement the Python class `DataSamplerTaskHadoop` described below.
Class description:
hadoop data sampler task
Method signatures and docstrings:
- def __init__(self, line): Change line to taskconf object Args: line: str Exception: DataSamplerTaskInitError
- def excute(self): begin to sample Args: None Return: 0 | Implement the Python class `DataSamplerTaskHadoop` described below.
Class description:
hadoop data sampler task
Method signatures and docstrings:
- def __init__(self, line): Change line to taskconf object Args: line: str Exception: DataSamplerTaskInitError
- def excute(self): begin to sample Args: None Return: 0
<|s... | 913fb4af29f4395f4a300d35c00236065075960e | <|skeleton|>
class DataSamplerTaskHadoop:
"""hadoop data sampler task"""
def __init__(self, line):
"""Change line to taskconf object Args: line: str Exception: DataSamplerTaskInitError"""
<|body_0|>
def excute(self):
"""begin to sample Args: None Return: 0"""
<|body_1|>
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataSamplerTaskHadoop:
"""hadoop data sampler task"""
def __init__(self, line):
"""Change line to taskconf object Args: line: str Exception: DataSamplerTaskInitError"""
line = line.rstrip('\n')
try:
super(DataSamplerTaskHadoop, self).__init__(line)
except Value... | the_stack_v2_python_sparse | script/data_sampler_task.py | jhuangpku/data_checker | train | 0 |
76dfa2d0dbb2711c5c98fefe831a2e84e4733d1e | [
"now_sum = cnt = max_num = 0\nfor i, v in enumerate(light):\n now_sum += 1\n max_num = max(v, max_num)\n if max_num == now_sum:\n cnt += 1\nreturn cnt",
"answer = 0\nmax_num = 0\nfor index_i, i in enumerate(light):\n if max_num < i:\n max_num = i\n if index_i + 1 == max_num:\n ... | <|body_start_0|>
now_sum = cnt = max_num = 0
for i, v in enumerate(light):
now_sum += 1
max_num = max(v, max_num)
if max_num == now_sum:
cnt += 1
return cnt
<|end_body_0|>
<|body_start_1|>
answer = 0
max_num = 0
for ind... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numTimesAllBlue(self, light):
""":type light: List[int] :rtype: int"""
<|body_0|>
def numTimesAllBlue(self, light):
""":type light: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
now_sum = cnt = max_num = 0
... | stack_v2_sparse_classes_75kplus_train_066325 | 875 | no_license | [
{
"docstring": ":type light: List[int] :rtype: int",
"name": "numTimesAllBlue",
"signature": "def numTimesAllBlue(self, light)"
},
{
"docstring": ":type light: List[int] :rtype: int",
"name": "numTimesAllBlue",
"signature": "def numTimesAllBlue(self, light)"
}
] | 2 | stack_v2_sparse_classes_30k_val_001221 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numTimesAllBlue(self, light): :type light: List[int] :rtype: int
- def numTimesAllBlue(self, light): :type light: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numTimesAllBlue(self, light): :type light: List[int] :rtype: int
- def numTimesAllBlue(self, light): :type light: List[int] :rtype: int
<|skeleton|>
class Solution:
def... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def numTimesAllBlue(self, light):
""":type light: List[int] :rtype: int"""
<|body_0|>
def numTimesAllBlue(self, light):
""":type light: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def numTimesAllBlue(self, light):
""":type light: List[int] :rtype: int"""
now_sum = cnt = max_num = 0
for i, v in enumerate(light):
now_sum += 1
max_num = max(v, max_num)
if max_num == now_sum:
cnt += 1
return cnt
... | the_stack_v2_python_sparse | 1375_Bulb_Switcher_III.py | bingli8802/leetcode | train | 0 | |
a53ef81d61fe65ee64f1c7d7a196fbdaa0b42cdf | [
"self.block = block\nself.input_id = input_id\nself.output_id = output_id\nself.include_input_id = self._block_defines_input_id(block)",
"args_spec = inspect.getargspec(block.process_signals)\nif len(args_spec.args) == 2:\n return False\nelif len(args_spec.args) == 3:\n return True\nelse:\n raise Invalid... | <|body_start_0|>
self.block = block
self.input_id = input_id
self.output_id = output_id
self.include_input_id = self._block_defines_input_id(block)
<|end_body_0|>
<|body_start_1|>
args_spec = inspect.getargspec(block.process_signals)
if len(args_spec.args) == 2:
... | A class that defines block receiver information. An instance of this class is created for each block receiver and accessed when delivering signals | BlockReceiverData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlockReceiverData:
"""A class that defines block receiver information. An instance of this class is created for each block receiver and accessed when delivering signals"""
def __init__(self, block, input_id, output_id):
"""Create a new block receiver data. Take care of setting up ins... | stack_v2_sparse_classes_75kplus_train_066326 | 15,979 | no_license | [
{
"docstring": "Create a new block receiver data. Take care of setting up instance variables.",
"name": "__init__",
"signature": "def __init__(self, block, input_id, output_id)"
},
{
"docstring": "Returns True if the block developer can receive the input ID",
"name": "_block_defines_input_id... | 2 | stack_v2_sparse_classes_30k_train_029710 | Implement the Python class `BlockReceiverData` described below.
Class description:
A class that defines block receiver information. An instance of this class is created for each block receiver and accessed when delivering signals
Method signatures and docstrings:
- def __init__(self, block, input_id, output_id): Crea... | Implement the Python class `BlockReceiverData` described below.
Class description:
A class that defines block receiver information. An instance of this class is created for each block receiver and accessed when delivering signals
Method signatures and docstrings:
- def __init__(self, block, input_id, output_id): Crea... | e2ef4c7b56c4e7e06964fe6f64ae6c497ac31727 | <|skeleton|>
class BlockReceiverData:
"""A class that defines block receiver information. An instance of this class is created for each block receiver and accessed when delivering signals"""
def __init__(self, block, input_id, output_id):
"""Create a new block receiver data. Take care of setting up ins... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BlockReceiverData:
"""A class that defines block receiver information. An instance of this class is created for each block receiver and accessed when delivering signals"""
def __init__(self, block, input_id, output_id):
"""Create a new block receiver data. Take care of setting up instance variabl... | the_stack_v2_python_sparse | nio/router/base.py | niolabs/nio | train | 5 |
e8ce26f290a44857c8747cbe426e242e5640064e | [
"if task.node.provision_state in (states.DEPLOYING, states.RESCUING, states.CLEANING):\n prepare_node_for_deploy(task)\nsuper(IloPXEBoot, self).prepare_ramdisk(task, ramdisk_params)",
"ilo_common.update_boot_mode(task)\nboot_mode = boot_mode_utils.get_boot_mode(task.node)\nif deploy_utils.is_iscsi_boot(task) a... | <|body_start_0|>
if task.node.provision_state in (states.DEPLOYING, states.RESCUING, states.CLEANING):
prepare_node_for_deploy(task)
super(IloPXEBoot, self).prepare_ramdisk(task, ramdisk_params)
<|end_body_0|>
<|body_start_1|>
ilo_common.update_boot_mode(task)
boot_mode = bo... | IloPXEBoot | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IloPXEBoot:
def prepare_ramdisk(self, task, ramdisk_params):
"""Prepares the boot of Ironic ramdisk using PXE. This method prepares the boot of the deploy or rescue ramdisk after reading relevant information from the node's driver_info and instance_info. :param task: a task from TaskMana... | stack_v2_sparse_classes_75kplus_train_066327 | 46,872 | permissive | [
{
"docstring": "Prepares the boot of Ironic ramdisk using PXE. This method prepares the boot of the deploy or rescue ramdisk after reading relevant information from the node's driver_info and instance_info. :param task: a task from TaskManager. :param ramdisk_params: the parameters to be passed to the ramdisk. ... | 3 | stack_v2_sparse_classes_30k_train_003145 | Implement the Python class `IloPXEBoot` described below.
Class description:
Implement the IloPXEBoot class.
Method signatures and docstrings:
- def prepare_ramdisk(self, task, ramdisk_params): Prepares the boot of Ironic ramdisk using PXE. This method prepares the boot of the deploy or rescue ramdisk after reading re... | Implement the Python class `IloPXEBoot` described below.
Class description:
Implement the IloPXEBoot class.
Method signatures and docstrings:
- def prepare_ramdisk(self, task, ramdisk_params): Prepares the boot of Ironic ramdisk using PXE. This method prepares the boot of the deploy or rescue ramdisk after reading re... | ab76ff12e1c3c2208455e917f1a40d4000b4e990 | <|skeleton|>
class IloPXEBoot:
def prepare_ramdisk(self, task, ramdisk_params):
"""Prepares the boot of Ironic ramdisk using PXE. This method prepares the boot of the deploy or rescue ramdisk after reading relevant information from the node's driver_info and instance_info. :param task: a task from TaskMana... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IloPXEBoot:
def prepare_ramdisk(self, task, ramdisk_params):
"""Prepares the boot of Ironic ramdisk using PXE. This method prepares the boot of the deploy or rescue ramdisk after reading relevant information from the node's driver_info and instance_info. :param task: a task from TaskManager. :param ra... | the_stack_v2_python_sparse | ironic/drivers/modules/ilo/boot.py | openstack/ironic | train | 411 | |
2d64146a0001a1efb3e5e98209c9553d882e14b9 | [
"menu_item.MenuItem.__init__(self, main_menu, frame)\nself.create_menu_item_button('Help')\nself.menu_item_button['command'] = self.get_help_window",
"self.gui.active_window.hide()\nself.associated_window = help_window.HelpWindow(self.gui)\nself.gui.active_window = self.associated_window\nself.gui.active_window.s... | <|body_start_0|>
menu_item.MenuItem.__init__(self, main_menu, frame)
self.create_menu_item_button('Help')
self.menu_item_button['command'] = self.get_help_window
<|end_body_0|>
<|body_start_1|>
self.gui.active_window.hide()
self.associated_window = help_window.HelpWindow(self.gu... | This class is used to create a button that will bring the user to the Help menu. | HelpMenuItem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HelpMenuItem:
"""This class is used to create a button that will bring the user to the Help menu."""
def __init__(self, main_menu, frame):
"""Args: main_menu ([]): this class must know about the main menu because it knows about the GUI, and we need to alter the GUI's active window"""... | stack_v2_sparse_classes_75kplus_train_066328 | 994 | no_license | [
{
"docstring": "Args: main_menu ([]): this class must know about the main menu because it knows about the GUI, and we need to alter the GUI's active window",
"name": "__init__",
"signature": "def __init__(self, main_menu, frame)"
},
{
"docstring": "This function will hide everything on the activ... | 2 | stack_v2_sparse_classes_30k_train_029401 | Implement the Python class `HelpMenuItem` described below.
Class description:
This class is used to create a button that will bring the user to the Help menu.
Method signatures and docstrings:
- def __init__(self, main_menu, frame): Args: main_menu ([]): this class must know about the main menu because it knows about... | Implement the Python class `HelpMenuItem` described below.
Class description:
This class is used to create a button that will bring the user to the Help menu.
Method signatures and docstrings:
- def __init__(self, main_menu, frame): Args: main_menu ([]): this class must know about the main menu because it knows about... | e26d9450b98fa0f372bcdf6eaf251a2c9dcba44e | <|skeleton|>
class HelpMenuItem:
"""This class is used to create a button that will bring the user to the Help menu."""
def __init__(self, main_menu, frame):
"""Args: main_menu ([]): this class must know about the main menu because it knows about the GUI, and we need to alter the GUI's active window"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HelpMenuItem:
"""This class is used to create a button that will bring the user to the Help menu."""
def __init__(self, main_menu, frame):
"""Args: main_menu ([]): this class must know about the main menu because it knows about the GUI, and we need to alter the GUI's active window"""
menu... | the_stack_v2_python_sparse | user_interface/menu_items/help_menu_item.py | pucheng-tan/WordFlow | train | 0 |
d511a6eb4da6b3f81faef056ec2fd690e7a78eca | [
"dp = [2147483646] * (amount + 1)\ndp[0] = 0\ncoins = set(coins)\nfor coin in coins:\n for i in range(coin, amount + 1):\n dp[i] = min(dp[i - coin] + 1, dp[i])\nreturn dp[amount] if dp[amount] != 2147483646 else -1",
"coins.sort(reverse=True)\ncount = 2147483647\n\ndef greedy(value, last, depth):\n n... | <|body_start_0|>
dp = [2147483646] * (amount + 1)
dp[0] = 0
coins = set(coins)
for coin in coins:
for i in range(coin, amount + 1):
dp[i] = min(dp[i - coin] + 1, dp[i])
return dp[amount] if dp[amount] != 2147483646 else -1
<|end_body_0|>
<|body_start_... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def coinChange(self, coins, amount):
"""动态规划问题常用的填坑法,下标代表能组合出的数(不能组合的 为INF),数组值代表组合出此数的最少步骤 这题改用其他语言做了,Python死活超时......"""
<|body_0|>
def coinChange_0(self, coins, amount):
"""最开始的想法,按照人的思维,先上大的,不行从上一个继续尝试小的,可惜 超时了。 :type coins: List[int] :type amount: int ... | stack_v2_sparse_classes_75kplus_train_066329 | 1,608 | permissive | [
{
"docstring": "动态规划问题常用的填坑法,下标代表能组合出的数(不能组合的 为INF),数组值代表组合出此数的最少步骤 这题改用其他语言做了,Python死活超时......",
"name": "coinChange",
"signature": "def coinChange(self, coins, amount)"
},
{
"docstring": "最开始的想法,按照人的思维,先上大的,不行从上一个继续尝试小的,可惜 超时了。 :type coins: List[int] :type amount: int :rtype: int",
"name":... | 2 | stack_v2_sparse_classes_30k_train_000158 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins, amount): 动态规划问题常用的填坑法,下标代表能组合出的数(不能组合的 为INF),数组值代表组合出此数的最少步骤 这题改用其他语言做了,Python死活超时......
- def coinChange_0(self, coins, amount): 最开始的想法,按照人的思维,先上大的,不... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins, amount): 动态规划问题常用的填坑法,下标代表能组合出的数(不能组合的 为INF),数组值代表组合出此数的最少步骤 这题改用其他语言做了,Python死活超时......
- def coinChange_0(self, coins, amount): 最开始的想法,按照人的思维,先上大的,不... | d203aecd1afe1af13a0384a9c657c8424aab322d | <|skeleton|>
class Solution:
def coinChange(self, coins, amount):
"""动态规划问题常用的填坑法,下标代表能组合出的数(不能组合的 为INF),数组值代表组合出此数的最少步骤 这题改用其他语言做了,Python死活超时......"""
<|body_0|>
def coinChange_0(self, coins, amount):
"""最开始的想法,按照人的思维,先上大的,不行从上一个继续尝试小的,可惜 超时了。 :type coins: List[int] :type amount: int ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def coinChange(self, coins, amount):
"""动态规划问题常用的填坑法,下标代表能组合出的数(不能组合的 为INF),数组值代表组合出此数的最少步骤 这题改用其他语言做了,Python死活超时......"""
dp = [2147483646] * (amount + 1)
dp[0] = 0
coins = set(coins)
for coin in coins:
for i in range(coin, amount + 1):
... | the_stack_v2_python_sparse | medium/Q322_CoinChange.py | Kaciras/leetcode | train | 0 | |
0acea9c2bbe9a5ec308a76d2744a7c4b9d19b9c4 | [
"self.rect = Rect(x, y, w, h)\nself.image = image\nself.toState = toState\nself.isDown = False",
"if self.rect.collidepoint(mousePos):\n return True\nelse:\n return False",
"mousePos = pygame.mouse.get_pos()\nclick = pygame.mouse.get_pressed()\nif self.checkCollision(mousePos) and click[0] == 1:\n retu... | <|body_start_0|>
self.rect = Rect(x, y, w, h)
self.image = image
self.toState = toState
self.isDown = False
<|end_body_0|>
<|body_start_1|>
if self.rect.collidepoint(mousePos):
return True
else:
return False
<|end_body_1|>
<|body_start_2|>
... | Manages Button creation and click events | Button | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Button:
"""Manages Button creation and click events"""
def __init__(self, toState, image, x, y, w, h):
"""Initializes button's draw rectangle, image, isDown state and click event transition state"""
<|body_0|>
def checkCollision(self, mousePos):
"""Checks if the ... | stack_v2_sparse_classes_75kplus_train_066330 | 1,548 | no_license | [
{
"docstring": "Initializes button's draw rectangle, image, isDown state and click event transition state",
"name": "__init__",
"signature": "def __init__(self, toState, image, x, y, w, h)"
},
{
"docstring": "Checks if the current mouse position is inside the button's rectangle",
"name": "ch... | 4 | stack_v2_sparse_classes_30k_train_018590 | Implement the Python class `Button` described below.
Class description:
Manages Button creation and click events
Method signatures and docstrings:
- def __init__(self, toState, image, x, y, w, h): Initializes button's draw rectangle, image, isDown state and click event transition state
- def checkCollision(self, mous... | Implement the Python class `Button` described below.
Class description:
Manages Button creation and click events
Method signatures and docstrings:
- def __init__(self, toState, image, x, y, w, h): Initializes button's draw rectangle, image, isDown state and click event transition state
- def checkCollision(self, mous... | 73fa3eb2b3181be824a504ecbaf414ceea070678 | <|skeleton|>
class Button:
"""Manages Button creation and click events"""
def __init__(self, toState, image, x, y, w, h):
"""Initializes button's draw rectangle, image, isDown state and click event transition state"""
<|body_0|>
def checkCollision(self, mousePos):
"""Checks if the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Button:
"""Manages Button creation and click events"""
def __init__(self, toState, image, x, y, w, h):
"""Initializes button's draw rectangle, image, isDown state and click event transition state"""
self.rect = Rect(x, y, w, h)
self.image = image
self.toState = toState
... | the_stack_v2_python_sparse | Final/src/minesweeper/content/ui/Button.py | JusDOrr/Python | train | 0 |
55e123c048b6bfbd71d26d2360506a2bfc9a7951 | [
"def dfs(root: Node) -> None:\n res.append(str(root.val))\n res.append(str(len(root.children)))\n for c in root.children:\n dfs(c)\nif not root:\n return '#'\nres = []\ndfs(root)\nreturn '#'.join(res)",
"def dfs() -> Node:\n node = Node(int(q.popleft()), [])\n size = int(q.popleft())\n ... | <|body_start_0|>
def dfs(root: Node) -> None:
res.append(str(root.val))
res.append(str(len(root.children)))
for c in root.children:
dfs(c)
if not root:
return '#'
res = []
dfs(root)
return '#'.join(res)
<|end_body_0|... | Codec428 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec428:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_066331 | 42,611 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root: 'Node') -> str"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def des... | 2 | stack_v2_sparse_classes_30k_train_054432 | Implement the Python class `Codec428` described below.
Class description:
Implement the Codec428 class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data ... | Implement the Python class `Codec428` described below.
Class description:
Implement the Codec428 class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data ... | d8a3dade7c79d843370e87d3dd0c75ed386a9a4b | <|skeleton|>
class Codec428:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec428:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
def dfs(root: Node) -> None:
res.append(str(root.val))
res.append(str(len(root.children)))
for c in root.children:
dfs(c... | the_stack_v2_python_sparse | tree.py | zplchn/m_amzn | train | 0 | |
dc297c2479f93801a920f3453a00e7ee69a81b36 | [
"if 'register' in self.user.apps:\n return html.a('New User?', href='/register')\nreturn ''",
"if 'forgot' in self.user.apps:\n return load_content('views/forgot_password.pug')\nreturn ''",
"remember_me = zoom.system.site.config.get('site', 'remember_me', True)\nif remember_me in zoom.utils.POSITIVE:\n ... | <|body_start_0|>
if 'register' in self.user.apps:
return html.a('New User?', href='/register')
return ''
<|end_body_0|>
<|body_start_1|>
if 'forgot' in self.user.apps:
return load_content('views/forgot_password.pug')
return ''
<|end_body_1|>
<|body_start_2|>
... | LoginForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoginForm:
def registration_link(self):
"""returns registration link for new users"""
<|body_0|>
def forgot_password(self):
"""returns link to password recovery app"""
<|body_1|>
def remember_me_checkbox(self):
"""return Remember Me checkbox"""
... | stack_v2_sparse_classes_75kplus_train_066332 | 3,089 | permissive | [
{
"docstring": "returns registration link for new users",
"name": "registration_link",
"signature": "def registration_link(self)"
},
{
"docstring": "returns link to password recovery app",
"name": "forgot_password",
"signature": "def forgot_password(self)"
},
{
"docstring": "retu... | 3 | stack_v2_sparse_classes_30k_train_013443 | Implement the Python class `LoginForm` described below.
Class description:
Implement the LoginForm class.
Method signatures and docstrings:
- def registration_link(self): returns registration link for new users
- def forgot_password(self): returns link to password recovery app
- def remember_me_checkbox(self): return... | Implement the Python class `LoginForm` described below.
Class description:
Implement the LoginForm class.
Method signatures and docstrings:
- def registration_link(self): returns registration link for new users
- def forgot_password(self): returns link to password recovery app
- def remember_me_checkbox(self): return... | b34cb4b2ee7cc40b2c99015f05bfcc12d4b49065 | <|skeleton|>
class LoginForm:
def registration_link(self):
"""returns registration link for new users"""
<|body_0|>
def forgot_password(self):
"""returns link to password recovery app"""
<|body_1|>
def remember_me_checkbox(self):
"""return Remember Me checkbox"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LoginForm:
def registration_link(self):
"""returns registration link for new users"""
if 'register' in self.user.apps:
return html.a('New User?', href='/register')
return ''
def forgot_password(self):
"""returns link to password recovery app"""
if 'forg... | the_stack_v2_python_sparse | zoom/_assets/standard_apps/login/index.py | dsilabs/zoom | train | 9 | |
00ab7900988e82c3df8f65b057668ad4d2e6ade7 | [
"super().__init__()\nself.qc = 0.7\nself.qf = 0.5\nself.pc = 0.4\nself.pt = 0.95\nself.tmax = 0.85\nself.tmin = 0.85\nself.eps = 1e-15\nself.device = device",
"reference = torch.clamp(reference, 0, 65536.0)\ntest = torch.clamp(test, 0, 65536.0)\nif start_exposure is None or stop_exposure is None:\n c_start, c_... | <|body_start_0|>
super().__init__()
self.qc = 0.7
self.qf = 0.5
self.pc = 0.4
self.pt = 0.95
self.tmax = 0.85
self.tmin = 0.85
self.eps = 1e-15
self.device = device
<|end_body_0|>
<|body_start_1|>
reference = torch.clamp(reference, 0, 6553... | Class for computing HDR-FLIP | HDRFLIPLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HDRFLIPLoss:
"""Class for computing HDR-FLIP"""
def __init__(self, device='cpu'):
"""Init"""
<|body_0|>
def forward(self, test, reference, pixels_per_degree=0.7 * 3840 / 0.7 * np.pi / 180, tone_mapper='aces', start_exposure=None, stop_exposure=None):
"""Computes ... | stack_v2_sparse_classes_75kplus_train_066333 | 29,583 | permissive | [
{
"docstring": "Init",
"name": "__init__",
"signature": "def __init__(self, device='cpu')"
},
{
"docstring": "Computes the HDR-FLIP error map between two HDR images, assuming the images are observed at a certain number of pixels per degree of visual angle :param test: test tensor (with NxCxHxW l... | 2 | stack_v2_sparse_classes_30k_train_038894 | Implement the Python class `HDRFLIPLoss` described below.
Class description:
Class for computing HDR-FLIP
Method signatures and docstrings:
- def __init__(self, device='cpu'): Init
- def forward(self, test, reference, pixels_per_degree=0.7 * 3840 / 0.7 * np.pi / 180, tone_mapper='aces', start_exposure=None, stop_expo... | Implement the Python class `HDRFLIPLoss` described below.
Class description:
Class for computing HDR-FLIP
Method signatures and docstrings:
- def __init__(self, device='cpu'): Init
- def forward(self, test, reference, pixels_per_degree=0.7 * 3840 / 0.7 * np.pi / 180, tone_mapper='aces', start_exposure=None, stop_expo... | 3075d63177e8ac04ee91784d5b0c56379335740f | <|skeleton|>
class HDRFLIPLoss:
"""Class for computing HDR-FLIP"""
def __init__(self, device='cpu'):
"""Init"""
<|body_0|>
def forward(self, test, reference, pixels_per_degree=0.7 * 3840 / 0.7 * np.pi / 180, tone_mapper='aces', start_exposure=None, stop_exposure=None):
"""Computes ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HDRFLIPLoss:
"""Class for computing HDR-FLIP"""
def __init__(self, device='cpu'):
"""Init"""
super().__init__()
self.qc = 0.7
self.qf = 0.5
self.pc = 0.4
self.pt = 0.95
self.tmax = 0.85
self.tmin = 0.85
self.eps = 1e-15
self.... | the_stack_v2_python_sparse | util/flip_loss.py | wi1k1n/nrf-accelerations | train | 1 |
522e38d8d8e209522f73df52b27263cd65318ac0 | [
"for i in range(int(c ** 0.5) + 1):\n j = int((c - i * i) ** 0.5)\n if i * i + j * j == c:\n return True\nreturn False",
"i = 2\nwhile i * i <= c:\n if c % i == 0:\n cnt = 0\n while c % i == 0:\n c //= i\n cnt += 1\n if i % 4 == 3 and cnt % 2 != 0:\n ... | <|body_start_0|>
for i in range(int(c ** 0.5) + 1):
j = int((c - i * i) ** 0.5)
if i * i + j * j == c:
return True
return False
<|end_body_0|>
<|body_start_1|>
i = 2
while i * i <= c:
if c % i == 0:
cnt = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def judgeSquareSum_MK1(self, c: int) -> bool:
"""Time complexity: O(√clgc). Space complexity: O(1)."""
<|body_0|>
def judgeSquareSum_MK2(self, c: int) -> bool:
"""Fermat Theorem: Any positive number n is expressible as a sum of two squares if and only if th... | stack_v2_sparse_classes_75kplus_train_066334 | 985 | no_license | [
{
"docstring": "Time complexity: O(√clgc). Space complexity: O(1).",
"name": "judgeSquareSum_MK1",
"signature": "def judgeSquareSum_MK1(self, c: int) -> bool"
},
{
"docstring": "Fermat Theorem: Any positive number n is expressible as a sum of two squares if and only if the prime factorization of... | 2 | stack_v2_sparse_classes_30k_train_013476 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def judgeSquareSum_MK1(self, c: int) -> bool: Time complexity: O(√clgc). Space complexity: O(1).
- def judgeSquareSum_MK2(self, c: int) -> bool: Fermat Theorem: Any positive numb... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def judgeSquareSum_MK1(self, c: int) -> bool: Time complexity: O(√clgc). Space complexity: O(1).
- def judgeSquareSum_MK2(self, c: int) -> bool: Fermat Theorem: Any positive numb... | d7ba416d22becfa8f2a2ae4eee04c86617cd9332 | <|skeleton|>
class Solution:
def judgeSquareSum_MK1(self, c: int) -> bool:
"""Time complexity: O(√clgc). Space complexity: O(1)."""
<|body_0|>
def judgeSquareSum_MK2(self, c: int) -> bool:
"""Fermat Theorem: Any positive number n is expressible as a sum of two squares if and only if th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def judgeSquareSum_MK1(self, c: int) -> bool:
"""Time complexity: O(√clgc). Space complexity: O(1)."""
for i in range(int(c ** 0.5) + 1):
j = int((c - i * i) ** 0.5)
if i * i + j * j == c:
return True
return False
def judgeSquareSu... | the_stack_v2_python_sparse | 0633. Sum of Square Numbers/Solution.py | faterazer/LeetCode | train | 4 | |
0b0340a48943e1e8f622985a01afa56f2ce4278b | [
"self.selected_year = kwargs.get('selected_year', datetime.now().year)\nassert str(self.selected_year).isdigit(), 'selected_year must be an integer'\nself.time_now = datetime.now()\nself.monthly_user_counts = []\nself.calculate_new_users()",
"for month_num in range(1, 13):\n if self.selected_year == self.time_... | <|body_start_0|>
self.selected_year = kwargs.get('selected_year', datetime.now().year)
assert str(self.selected_year).isdigit(), 'selected_year must be an integer'
self.time_now = datetime.now()
self.monthly_user_counts = []
self.calculate_new_users()
<|end_body_0|>
<|body_start... | MonthlyNewUserStats | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MonthlyNewUserStats:
def __init__(self, **kwargs):
"""num_days = how many days back from today to count users who logged in"""
<|body_0|>
def calculate_new_users(self):
"""Calculate new user info for the given year"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_75kplus_train_066335 | 4,273 | no_license | [
{
"docstring": "num_days = how many days back from today to count users who logged in",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Calculate new user info for the given year",
"name": "calculate_new_users",
"signature": "def calculate_new_users(sel... | 2 | stack_v2_sparse_classes_30k_train_005836 | Implement the Python class `MonthlyNewUserStats` described below.
Class description:
Implement the MonthlyNewUserStats class.
Method signatures and docstrings:
- def __init__(self, **kwargs): num_days = how many days back from today to count users who logged in
- def calculate_new_users(self): Calculate new user info... | Implement the Python class `MonthlyNewUserStats` described below.
Class description:
Implement the MonthlyNewUserStats class.
Method signatures and docstrings:
- def __init__(self, **kwargs): num_days = how many days back from today to count users who logged in
- def calculate_new_users(self): Calculate new user info... | 2a17e5ba918d6d1c7d38c192e0504e6cd96b32d2 | <|skeleton|>
class MonthlyNewUserStats:
def __init__(self, **kwargs):
"""num_days = how many days back from today to count users who logged in"""
<|body_0|>
def calculate_new_users(self):
"""Calculate new user info for the given year"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MonthlyNewUserStats:
def __init__(self, **kwargs):
"""num_days = how many days back from today to count users who logged in"""
self.selected_year = kwargs.get('selected_year', datetime.now().year)
assert str(self.selected_year).isdigit(), 'selected_year must be an integer'
self... | the_stack_v2_python_sparse | dv_apps/dataverse_auth/util_logins.py | IQSS/miniverse | train | 3 | |
4ff22b7683aa12ee3d4804c1f46a46681ba4304d | [
"if minfo is None:\n minfo = {}\nsuper(QuorumCompleteVoteMessage, self).__init__(minfo)\nself.IsSystemMessage = False\nself.IsForward = False\nself.IsReliable = True\nself.BlockNumber = minfo.get('BlockNumber', 0)\nself.TransactionIDs = []\nif 'TransactionIDs' in minfo:\n for txnid in minfo['TransactionIDs']:... | <|body_start_0|>
if minfo is None:
minfo = {}
super(QuorumCompleteVoteMessage, self).__init__(minfo)
self.IsSystemMessage = False
self.IsForward = False
self.IsReliable = True
self.BlockNumber = minfo.get('BlockNumber', 0)
self.TransactionIDs = []
... | Quorum complete vote messages represent the message format for exchanging information between peers when voting has completed. Attributes: QuorumCompleteVoteMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this message is a system message. IsForward (bool): Whether or not... | QuorumCompleteVoteMessage | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuorumCompleteVoteMessage:
"""Quorum complete vote messages represent the message format for exchanging information between peers when voting has completed. Attributes: QuorumCompleteVoteMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this message ... | stack_v2_sparse_classes_75kplus_train_066336 | 8,559 | permissive | [
{
"docstring": "Constructor for QuorumCompleteVoteMessage. Args: minfo (dict): A dict containing initial values for the new QuorumCompleteVoteMessage.",
"name": "__init__",
"signature": "def __init__(self, minfo=None)"
},
{
"docstring": "Returns a dict containing information about the quorum com... | 2 | stack_v2_sparse_classes_30k_train_002779 | Implement the Python class `QuorumCompleteVoteMessage` described below.
Class description:
Quorum complete vote messages represent the message format for exchanging information between peers when voting has completed. Attributes: QuorumCompleteVoteMessage.MessageType (str): The class name of the message. IsSystemMessa... | Implement the Python class `QuorumCompleteVoteMessage` described below.
Class description:
Quorum complete vote messages represent the message format for exchanging information between peers when voting has completed. Attributes: QuorumCompleteVoteMessage.MessageType (str): The class name of the message. IsSystemMessa... | e3eb79f32c97a25993c87eda7f77a02fd2086c7c | <|skeleton|>
class QuorumCompleteVoteMessage:
"""Quorum complete vote messages represent the message format for exchanging information between peers when voting has completed. Attributes: QuorumCompleteVoteMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this message ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QuorumCompleteVoteMessage:
"""Quorum complete vote messages represent the message format for exchanging information between peers when voting has completed. Attributes: QuorumCompleteVoteMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this message is a system m... | the_stack_v2_python_sparse | validator/sawtooth_validator/consensus/quorum/messages/quorum_ballot.py | jrineck/sawtooth-core | train | 0 |
4245ade607ca2fd2e1b5250fa863d965c8f1c933 | [
"if not xml:\n if xml == '':\n xml = 'empty'\n raise MetaPubError('Cannot build MetaPubObject; xml string was %s' % xml)\nself.xml = xml\nself.content = self.parse_xml(xml, root)",
"if isinstance(xml, str) or isinstance(xml, bytes):\n dom = etree.XML(xml)\nelse:\n dom = etree.XML(xml)\nif root:... | <|body_start_0|>
if not xml:
if xml == '':
xml = 'empty'
raise MetaPubError('Cannot build MetaPubObject; xml string was %s' % xml)
self.xml = xml
self.content = self.parse_xml(xml, root)
<|end_body_0|>
<|body_start_1|>
if isinstance(xml, str) or i... | Base class for XML parsing objects (e.g. PubMedArticle) | MetaPubObject | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetaPubObject:
"""Base class for XML parsing objects (e.g. PubMedArticle)"""
def __init__(self, xml, root=None, *args, **kwargs):
"""Instantiate with "xml" as string or bytes containing valid XML. Supply name of root element (string) to set virtual top level. (optional)."""
<... | stack_v2_sparse_classes_75kplus_train_066337 | 2,868 | permissive | [
{
"docstring": "Instantiate with \"xml\" as string or bytes containing valid XML. Supply name of root element (string) to set virtual top level. (optional).",
"name": "__init__",
"signature": "def __init__(self, xml, root=None, *args, **kwargs)"
},
{
"docstring": "Takes xml (str or bytes) and (o... | 3 | stack_v2_sparse_classes_30k_train_016131 | Implement the Python class `MetaPubObject` described below.
Class description:
Base class for XML parsing objects (e.g. PubMedArticle)
Method signatures and docstrings:
- def __init__(self, xml, root=None, *args, **kwargs): Instantiate with "xml" as string or bytes containing valid XML. Supply name of root element (s... | Implement the Python class `MetaPubObject` described below.
Class description:
Base class for XML parsing objects (e.g. PubMedArticle)
Method signatures and docstrings:
- def __init__(self, xml, root=None, *args, **kwargs): Instantiate with "xml" as string or bytes containing valid XML. Supply name of root element (s... | 7dc3f2321720191d461056deeaedf69cd1479157 | <|skeleton|>
class MetaPubObject:
"""Base class for XML parsing objects (e.g. PubMedArticle)"""
def __init__(self, xml, root=None, *args, **kwargs):
"""Instantiate with "xml" as string or bytes containing valid XML. Supply name of root element (string) to set virtual top level. (optional)."""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MetaPubObject:
"""Base class for XML parsing objects (e.g. PubMedArticle)"""
def __init__(self, xml, root=None, *args, **kwargs):
"""Instantiate with "xml" as string or bytes containing valid XML. Supply name of root element (string) to set virtual top level. (optional)."""
if not xml:
... | the_stack_v2_python_sparse | metapub/base.py | pmartin23/metapub | train | 0 |
32ce5660a515575c1e42f153bda5c95c948c92a9 | [
"self.window_size = window_size\nself.stride_size = stride_size\nself.scope = scope\nself.device_spec = get_device_spec(default_gpu_id, num_gpus)\nwith tf.variable_scope(self.scope, reuse=tf.AUTO_REUSE), tf.device(self.device_spec):\n self.pooling_layer = tf.layers.MaxPooling3D(self.window_size, self.stride_size... | <|body_start_0|>
self.window_size = window_size
self.stride_size = stride_size
self.scope = scope
self.device_spec = get_device_spec(default_gpu_id, num_gpus)
with tf.variable_scope(self.scope, reuse=tf.AUTO_REUSE), tf.device(self.device_spec):
self.pooling_layer = tf... | max pooling layer | MaxPooling3D | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaxPooling3D:
"""max pooling layer"""
def __init__(self, window_size, stride_size, num_gpus=1, default_gpu_id=0, scope='max_pool_3d'):
"""initialize 3d max pooling layer"""
<|body_0|>
def __call__(self, input_data, input_mask):
"""call 3d max pooling layer"""
... | stack_v2_sparse_classes_75kplus_train_066338 | 6,321 | permissive | [
{
"docstring": "initialize 3d max pooling layer",
"name": "__init__",
"signature": "def __init__(self, window_size, stride_size, num_gpus=1, default_gpu_id=0, scope='max_pool_3d')"
},
{
"docstring": "call 3d max pooling layer",
"name": "__call__",
"signature": "def __call__(self, input_d... | 2 | stack_v2_sparse_classes_30k_train_035056 | Implement the Python class `MaxPooling3D` described below.
Class description:
max pooling layer
Method signatures and docstrings:
- def __init__(self, window_size, stride_size, num_gpus=1, default_gpu_id=0, scope='max_pool_3d'): initialize 3d max pooling layer
- def __call__(self, input_data, input_mask): call 3d max... | Implement the Python class `MaxPooling3D` described below.
Class description:
max pooling layer
Method signatures and docstrings:
- def __init__(self, window_size, stride_size, num_gpus=1, default_gpu_id=0, scope='max_pool_3d'): initialize 3d max pooling layer
- def __call__(self, input_data, input_mask): call 3d max... | 05fcbec15e359e3db86af6c3798c13be8a6c58ee | <|skeleton|>
class MaxPooling3D:
"""max pooling layer"""
def __init__(self, window_size, stride_size, num_gpus=1, default_gpu_id=0, scope='max_pool_3d'):
"""initialize 3d max pooling layer"""
<|body_0|>
def __call__(self, input_data, input_mask):
"""call 3d max pooling layer"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MaxPooling3D:
"""max pooling layer"""
def __init__(self, window_size, stride_size, num_gpus=1, default_gpu_id=0, scope='max_pool_3d'):
"""initialize 3d max pooling layer"""
self.window_size = window_size
self.stride_size = stride_size
self.scope = scope
self.device... | the_stack_v2_python_sparse | sequence_labeling/layer/pooling.py | stevezheng23/sequence_labeling_tf | train | 18 |
a02aae8b0ad9829c94253ecbd7d633c80ff9b73a | [
"super().__init__(config)\nself.in_proj_weight = nn.Parameter(torch.cat([bart_layer.self_attn.q_proj.weight, bart_layer.self_attn.k_proj.weight, bart_layer.self_attn.v_proj.weight]))\nself.in_proj_bias = nn.Parameter(torch.cat([bart_layer.self_attn.q_proj.bias, bart_layer.self_attn.k_proj.bias, bart_layer.self_attn... | <|body_start_0|>
super().__init__(config)
self.in_proj_weight = nn.Parameter(torch.cat([bart_layer.self_attn.q_proj.weight, bart_layer.self_attn.k_proj.weight, bart_layer.self_attn.v_proj.weight]))
self.in_proj_bias = nn.Parameter(torch.cat([bart_layer.self_attn.q_proj.bias, bart_layer.self_attn... | BartEncoderLayerBetterTransformer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BartEncoderLayerBetterTransformer:
def __init__(self, bart_layer, config):
"""A simple conversion of the `BartEncoderLayer` to its `BetterTransformer` implementation. Args: bart_layer (`torch.nn.Module`): The original `BartEncoderLayer` where the weights needs to be retrieved."""
... | stack_v2_sparse_classes_75kplus_train_066339 | 43,670 | no_license | [
{
"docstring": "A simple conversion of the `BartEncoderLayer` to its `BetterTransformer` implementation. Args: bart_layer (`torch.nn.Module`): The original `BartEncoderLayer` where the weights needs to be retrieved.",
"name": "__init__",
"signature": "def __init__(self, bart_layer, config)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_007323 | Implement the Python class `BartEncoderLayerBetterTransformer` described below.
Class description:
Implement the BartEncoderLayerBetterTransformer class.
Method signatures and docstrings:
- def __init__(self, bart_layer, config): A simple conversion of the `BartEncoderLayer` to its `BetterTransformer` implementation.... | Implement the Python class `BartEncoderLayerBetterTransformer` described below.
Class description:
Implement the BartEncoderLayerBetterTransformer class.
Method signatures and docstrings:
- def __init__(self, bart_layer, config): A simple conversion of the `BartEncoderLayer` to its `BetterTransformer` implementation.... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class BartEncoderLayerBetterTransformer:
def __init__(self, bart_layer, config):
"""A simple conversion of the `BartEncoderLayer` to its `BetterTransformer` implementation. Args: bart_layer (`torch.nn.Module`): The original `BartEncoderLayer` where the weights needs to be retrieved."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BartEncoderLayerBetterTransformer:
def __init__(self, bart_layer, config):
"""A simple conversion of the `BartEncoderLayer` to its `BetterTransformer` implementation. Args: bart_layer (`torch.nn.Module`): The original `BartEncoderLayer` where the weights needs to be retrieved."""
super().__ini... | the_stack_v2_python_sparse | generated/test_huggingface_optimum.py | jansel/pytorch-jit-paritybench | train | 35 | |
3329648e2501b7dca8b637fc70b95d04a9f3a69a | [
"def delete_forward_extremities_for_room_txn(txn: LoggingTransaction) -> int:\n sql = '\\n SELECT event_id FROM event_forward_extremities\\n INNER JOIN events USING (room_id, event_id)\\n WHERE room_id = ?\\n ORDER BY stream_ordering DESC\\n ... | <|body_start_0|>
def delete_forward_extremities_for_room_txn(txn: LoggingTransaction) -> int:
sql = '\n SELECT event_id FROM event_forward_extremities\n INNER JOIN events USING (room_id, event_id)\n WHERE room_id = ?\n ORDER BY stream_order... | EventForwardExtremitiesStore | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventForwardExtremitiesStore:
async def delete_forward_extremities_for_room(self, room_id: str) -> int:
"""Delete any extra forward extremities for a room. Invalidates the "get_latest_event_ids_in_room" cache if any forward extremities were deleted. Returns count deleted."""
<|bo... | stack_v2_sparse_classes_75kplus_train_066340 | 4,031 | permissive | [
{
"docstring": "Delete any extra forward extremities for a room. Invalidates the \"get_latest_event_ids_in_room\" cache if any forward extremities were deleted. Returns count deleted.",
"name": "delete_forward_extremities_for_room",
"signature": "async def delete_forward_extremities_for_room(self, room_... | 2 | stack_v2_sparse_classes_30k_train_031956 | Implement the Python class `EventForwardExtremitiesStore` described below.
Class description:
Implement the EventForwardExtremitiesStore class.
Method signatures and docstrings:
- async def delete_forward_extremities_for_room(self, room_id: str) -> int: Delete any extra forward extremities for a room. Invalidates the... | Implement the Python class `EventForwardExtremitiesStore` described below.
Class description:
Implement the EventForwardExtremitiesStore class.
Method signatures and docstrings:
- async def delete_forward_extremities_for_room(self, room_id: str) -> int: Delete any extra forward extremities for a room. Invalidates the... | d35bed8369514fe727b4fe1afb68f48cc8b2655a | <|skeleton|>
class EventForwardExtremitiesStore:
async def delete_forward_extremities_for_room(self, room_id: str) -> int:
"""Delete any extra forward extremities for a room. Invalidates the "get_latest_event_ids_in_room" cache if any forward extremities were deleted. Returns count deleted."""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EventForwardExtremitiesStore:
async def delete_forward_extremities_for_room(self, room_id: str) -> int:
"""Delete any extra forward extremities for a room. Invalidates the "get_latest_event_ids_in_room" cache if any forward extremities were deleted. Returns count deleted."""
def delete_forward... | the_stack_v2_python_sparse | synapse/storage/databases/main/events_forward_extremities.py | matrix-org/synapse | train | 12,215 | |
79ed1eb381c0a1ef0afb6bdd7d0c176aa5a557f4 | [
"super(ResBlk, self).__init__()\nself.conv1 = nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=1, padding=1)\nself.bn1 = nn.BatchNorm2d(ch_out)\nself.conv2 = nn.Conv2d(ch_out, ch_out, kernel_size=3, stride=1, padding=1)\nself.bn2 = nn.BatchNorm2d(ch_out)\nself.extra = nn.Sequential()\nif ch_out != ch_in:\n self.ex... | <|body_start_0|>
super(ResBlk, self).__init__()
self.conv1 = nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=1, padding=1)
self.bn1 = nn.BatchNorm2d(ch_out)
self.conv2 = nn.Conv2d(ch_out, ch_out, kernel_size=3, stride=1, padding=1)
self.bn2 = nn.BatchNorm2d(ch_out)
self.ex... | ResBlk | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResBlk:
def __init__(self, ch_in, ch_out):
""":param ch_in: :param ch_out:"""
<|body_0|>
def forward(self, x):
""":param x: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(ResBlk, self).__init__()
self.conv1 = nn.Conv2d(ch_in,... | stack_v2_sparse_classes_75kplus_train_066341 | 3,472 | no_license | [
{
"docstring": ":param ch_in: :param ch_out:",
"name": "__init__",
"signature": "def __init__(self, ch_in, ch_out)"
},
{
"docstring": ":param x: :return:",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020252 | Implement the Python class `ResBlk` described below.
Class description:
Implement the ResBlk class.
Method signatures and docstrings:
- def __init__(self, ch_in, ch_out): :param ch_in: :param ch_out:
- def forward(self, x): :param x: :return: | Implement the Python class `ResBlk` described below.
Class description:
Implement the ResBlk class.
Method signatures and docstrings:
- def __init__(self, ch_in, ch_out): :param ch_in: :param ch_out:
- def forward(self, x): :param x: :return:
<|skeleton|>
class ResBlk:
def __init__(self, ch_in, ch_out):
... | 44aaa338dd7a55fa8e76416c4dd94247e99a3b73 | <|skeleton|>
class ResBlk:
def __init__(self, ch_in, ch_out):
""":param ch_in: :param ch_out:"""
<|body_0|>
def forward(self, x):
""":param x: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResBlk:
def __init__(self, ch_in, ch_out):
""":param ch_in: :param ch_out:"""
super(ResBlk, self).__init__()
self.conv1 = nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=1, padding=1)
self.bn1 = nn.BatchNorm2d(ch_out)
self.conv2 = nn.Conv2d(ch_out, ch_out, kernel_size=3,... | the_stack_v2_python_sparse | middle/LeNet/RestNet.py | hdhcy/pytorch_learning | train | 0 | |
67389f2ca5dee6ebc8a819de78dfe4c28c179172 | [
"length = len(nums)\nif length <= 2:\n return False\nleft_min = [float('inf')] * length\nfor i in range(1, length):\n left_min[i] = min(left_min[i - 1], nums[i - 1])\nstack = []\nfor i in range(length - 1, -1, -1):\n nums_k = float('-inf')\n while stack and stack[-1] < nums[i]:\n nums_k = stack.p... | <|body_start_0|>
length = len(nums)
if length <= 2:
return False
left_min = [float('inf')] * length
for i in range(1, length):
left_min[i] = min(left_min[i - 1], nums[i - 1])
stack = []
for i in range(length - 1, -1, -1):
nums_k = float... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def find132pattern(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def my_find132pattern(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
length = len(nums)
if leng... | stack_v2_sparse_classes_75kplus_train_066342 | 1,676 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "find132pattern",
"signature": "def find132pattern(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "my_find132pattern",
"signature": "def my_find132pattern(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def find132pattern(self, nums): :type nums: List[int] :rtype: bool
- def my_find132pattern(self, nums): :type nums: List[int] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def find132pattern(self, nums): :type nums: List[int] :rtype: bool
- def my_find132pattern(self, nums): :type nums: List[int] :rtype: bool
<|skeleton|>
class Solution:
def ... | f43d70cac56bdf6377b22b865174af822902ff78 | <|skeleton|>
class Solution:
def find132pattern(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def my_find132pattern(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def find132pattern(self, nums):
""":type nums: List[int] :rtype: bool"""
length = len(nums)
if length <= 2:
return False
left_min = [float('inf')] * length
for i in range(1, length):
left_min[i] = min(left_min[i - 1], nums[i - 1])
... | the_stack_v2_python_sparse | 栈/单调栈/LeetCode456_132模式.py | ltzp/LeetCode | train | 0 | |
1e14dda7c8c051e6e2e7eabdd98119524c1f1b07 | [
"if isinstance(db_field, models.GeometryField):\n request = kwargs.pop('request', None)\n kwargs['widget'] = self.get_map_widget(db_field)\n return db_field.formfield(**kwargs)\nelse:\n return super(GeoModelAdmin, self).formfield_for_dbfield(db_field, **kwargs)",
"is_collection = db_field.geom_type in... | <|body_start_0|>
if isinstance(db_field, models.GeometryField):
request = kwargs.pop('request', None)
kwargs['widget'] = self.get_map_widget(db_field)
return db_field.formfield(**kwargs)
else:
return super(GeoModelAdmin, self).formfield_for_dbfield(db_fiel... | GeoModelAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeoModelAdmin:
def formfield_for_dbfield(self, db_field, **kwargs):
"""Overloaded from ModelAdmin to use our map widget."""
<|body_0|>
def get_map_widget(self, db_field):
"""Returns an OLWidget subclass with options appropriate for the given field."""
<|body_... | stack_v2_sparse_classes_75kplus_train_066343 | 3,504 | no_license | [
{
"docstring": "Overloaded from ModelAdmin to use our map widget.",
"name": "formfield_for_dbfield",
"signature": "def formfield_for_dbfield(self, db_field, **kwargs)"
},
{
"docstring": "Returns an OLWidget subclass with options appropriate for the given field.",
"name": "get_map_widget",
... | 2 | stack_v2_sparse_classes_30k_train_043483 | Implement the Python class `GeoModelAdmin` described below.
Class description:
Implement the GeoModelAdmin class.
Method signatures and docstrings:
- def formfield_for_dbfield(self, db_field, **kwargs): Overloaded from ModelAdmin to use our map widget.
- def get_map_widget(self, db_field): Returns an OLWidget subclas... | Implement the Python class `GeoModelAdmin` described below.
Class description:
Implement the GeoModelAdmin class.
Method signatures and docstrings:
- def formfield_for_dbfield(self, db_field, **kwargs): Overloaded from ModelAdmin to use our map widget.
- def get_map_widget(self, db_field): Returns an OLWidget subclas... | 4dd08a9ab49c435f83c17fcf45340678363c0c1d | <|skeleton|>
class GeoModelAdmin:
def formfield_for_dbfield(self, db_field, **kwargs):
"""Overloaded from ModelAdmin to use our map widget."""
<|body_0|>
def get_map_widget(self, db_field):
"""Returns an OLWidget subclass with options appropriate for the given field."""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GeoModelAdmin:
def formfield_for_dbfield(self, db_field, **kwargs):
"""Overloaded from ModelAdmin to use our map widget."""
if isinstance(db_field, models.GeometryField):
request = kwargs.pop('request', None)
kwargs['widget'] = self.get_map_widget(db_field)
... | the_stack_v2_python_sparse | apps/olwidget/admin.py | skyl/mycogia.com | train | 6 | |
87b001a30868775edf4fb6fe0cdf7699d8beab68 | [
"doc = await user_model.find_by_id(login_user_id)\nnew_doc = await user_model.trans_obj_id(doc)\nself_schema = WriteSelfFollowInfoSchema()\nlogin_data = self_schema.load(new_doc)\nassert not login_data.errors, ('关注数据异常', login_data.errors)\nfollow_doc = await user_model.find_by_id(following_user_id)\nnew_follow_doc... | <|body_start_0|>
doc = await user_model.find_by_id(login_user_id)
new_doc = await user_model.trans_obj_id(doc)
self_schema = WriteSelfFollowInfoSchema()
login_data = self_schema.load(new_doc)
assert not login_data.errors, ('关注数据异常', login_data.errors)
follow_doc = await u... | WriteModelServer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WriteModelServer:
async def write_follower_relationship(self, app, follower_model, user_model, friends_model, login_user_id, following_user_id):
"""Service segmentation :param app: :param follower_model: :param user_model: :param friends_model: :param login_user_id: :param following_user... | stack_v2_sparse_classes_75kplus_train_066344 | 7,936 | no_license | [
{
"docstring": "Service segmentation :param app: :param follower_model: :param user_model: :param friends_model: :param login_user_id: :param following_user_id: :return:",
"name": "write_follower_relationship",
"signature": "async def write_follower_relationship(self, app, follower_model, user_model, fr... | 3 | stack_v2_sparse_classes_30k_train_040289 | Implement the Python class `WriteModelServer` described below.
Class description:
Implement the WriteModelServer class.
Method signatures and docstrings:
- async def write_follower_relationship(self, app, follower_model, user_model, friends_model, login_user_id, following_user_id): Service segmentation :param app: :p... | Implement the Python class `WriteModelServer` described below.
Class description:
Implement the WriteModelServer class.
Method signatures and docstrings:
- async def write_follower_relationship(self, app, follower_model, user_model, friends_model, login_user_id, following_user_id): Service segmentation :param app: :p... | 39f76210267968bdef10d7e5efcd9727d4c03c3b | <|skeleton|>
class WriteModelServer:
async def write_follower_relationship(self, app, follower_model, user_model, friends_model, login_user_id, following_user_id):
"""Service segmentation :param app: :param follower_model: :param user_model: :param friends_model: :param login_user_id: :param following_user... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WriteModelServer:
async def write_follower_relationship(self, app, follower_model, user_model, friends_model, login_user_id, following_user_id):
"""Service segmentation :param app: :param follower_model: :param user_model: :param friends_model: :param login_user_id: :param following_user_id: :return:"... | the_stack_v2_python_sparse | user/services/WriteServices.py | liansheng/sanic_demo | train | 3 | |
0858c9427ab81feacf86a3f817b01aa398837c25 | [
"kb_dir = os.path.join('GRIDD', 'resources', KB_FOLDERNAME, 'kb')\ntemplate_file = os.path.join('GRIDD', 'resources', KB_FOLDERNAME, 'elit_dp_templates.kg')\nelit_dp_to_logic = ElitDPToLogic(ConceptGraph(kb_dir), template_file, device=device)\nreturn elit_dp_to_logic",
"tok = [Span.from_string('<span>i(0,1,0,0,1)... | <|body_start_0|>
kb_dir = os.path.join('GRIDD', 'resources', KB_FOLDERNAME, 'kb')
template_file = os.path.join('GRIDD', 'resources', KB_FOLDERNAME, 'elit_dp_templates.kg')
elit_dp_to_logic = ElitDPToLogic(ConceptGraph(kb_dir), template_file, device=device)
return elit_dp_to_logic
<|end_b... | ElitDPSpec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElitDPSpec:
def ELITDP(ElitDPToLogic, knowledge_base, template_file_names, device='cpu'):
"""`knowledge_base` is a KnowledgeBase object that the expression working memory has access to `template_file_names` are a variable number of filenames specifying parse-to-logic templates to load `d... | stack_v2_sparse_classes_75kplus_train_066345 | 2,204 | no_license | [
{
"docstring": "`knowledge_base` is a KnowledgeBase object that the expression working memory has access to `template_file_names` are a variable number of filenames specifying parse-to-logic templates to load `device` specifies whether to run the inference engine on cpu or gpu for the conversions",
"name": ... | 2 | stack_v2_sparse_classes_30k_train_021383 | Implement the Python class `ElitDPSpec` described below.
Class description:
Implement the ElitDPSpec class.
Method signatures and docstrings:
- def ELITDP(ElitDPToLogic, knowledge_base, template_file_names, device='cpu'): `knowledge_base` is a KnowledgeBase object that the expression working memory has access to `tem... | Implement the Python class `ElitDPSpec` described below.
Class description:
Implement the ElitDPSpec class.
Method signatures and docstrings:
- def ELITDP(ElitDPToLogic, knowledge_base, template_file_names, device='cpu'): `knowledge_base` is a KnowledgeBase object that the expression working memory has access to `tem... | fd8f2c65369e7001b6e599b4af6be69eb256aad1 | <|skeleton|>
class ElitDPSpec:
def ELITDP(ElitDPToLogic, knowledge_base, template_file_names, device='cpu'):
"""`knowledge_base` is a KnowledgeBase object that the expression working memory has access to `template_file_names` are a variable number of filenames specifying parse-to-logic templates to load `d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ElitDPSpec:
def ELITDP(ElitDPToLogic, knowledge_base, template_file_names, device='cpu'):
"""`knowledge_base` is a KnowledgeBase object that the expression working memory has access to `template_file_names` are a variable number of filenames specifying parse-to-logic templates to load `device` specifi... | the_stack_v2_python_sparse | modules/elit_dp_to_logic_spec.py | emora-chat/GRIDD | train | 1 | |
472186c9bce40eb4289aa161f8a94a7e4958ec6b | [
"if not agave_client and (not user):\n raise TypeError(\"Must specify one of 'agave_client' or 'user'.\")\nself.user = user\nself._ac = agave_client\nif not self._ac and self.user:\n self._ac = self.user.agave_oauth.client",
"metas = self._ac.meta.listMetadata(q=json.dumps({'value.projectId': project_id}))\... | <|body_start_0|>
if not agave_client and (not user):
raise TypeError("Must specify one of 'agave_client' or 'user'.")
self.user = user
self._ac = agave_client
if not self._ac and self.user:
self._ac = self.user.agave_oauth.client
<|end_body_0|>
<|body_start_1|>
... | Base projects manager. | ProjectsManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectsManager:
"""Base projects manager."""
def __init__(self, agave_client=None, user=None):
"""Initialize base projects manager. Can be initialized with a custom agave client or with a Django user object. :param agave_client: Cusotm agave client :param user: Django user object.""... | stack_v2_sparse_classes_75kplus_train_066346 | 2,547 | no_license | [
{
"docstring": "Initialize base projects manager. Can be initialized with a custom agave client or with a Django user object. :param agave_client: Cusotm agave client :param user: Django user object.",
"name": "__init__",
"signature": "def __init__(self, agave_client=None, user=None)"
},
{
"docs... | 3 | stack_v2_sparse_classes_30k_test_000432 | Implement the Python class `ProjectsManager` described below.
Class description:
Base projects manager.
Method signatures and docstrings:
- def __init__(self, agave_client=None, user=None): Initialize base projects manager. Can be initialized with a custom agave client or with a Django user object. :param agave_clien... | Implement the Python class `ProjectsManager` described below.
Class description:
Base projects manager.
Method signatures and docstrings:
- def __init__(self, agave_client=None, user=None): Initialize base projects manager. Can be initialized with a custom agave client or with a Django user object. :param agave_clien... | 040e0d88eac6037703a6128d6f4644b5a99ea11b | <|skeleton|>
class ProjectsManager:
"""Base projects manager."""
def __init__(self, agave_client=None, user=None):
"""Initialize base projects manager. Can be initialized with a custom agave client or with a Django user object. :param agave_client: Cusotm agave client :param user: Django user object.""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProjectsManager:
"""Base projects manager."""
def __init__(self, agave_client=None, user=None):
"""Initialize base projects manager. Can be initialized with a custom agave client or with a Django user object. :param agave_client: Cusotm agave client :param user: Django user object."""
if ... | the_stack_v2_python_sparse | designsafe/apps/projects/managers/base.py | DesignSafe-CI/portal | train | 12 |
f23037c61e04c0aab7f8604600f243b27f598317 | [
"super().__init__()\nself._matching_dim = matching_dim\nself._channels = channels\nself._normalize = normalize\nself._init_diag = init_diag\nself.interaction_matrix = torch.empty(self._channels, self._matching_dim, self._matching_dim)\nif self._init_diag:\n self.interaction_matrix = self.interaction_matrix.unifo... | <|body_start_0|>
super().__init__()
self._matching_dim = matching_dim
self._channels = channels
self._normalize = normalize
self._init_diag = init_diag
self.interaction_matrix = torch.empty(self._channels, self._matching_dim, self._matching_dim)
if self._init_diag... | Module that captures the basic interactions between two tensors. :param matching_dims: Word dimension of two interaction texts. :param channels: Number of word interaction tensor channels. :param normalize: Whether to L2-normalize samples along the dot product axis before taking the dot product. If set to True, then th... | MatchingTensor | [
"MIT",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MatchingTensor:
"""Module that captures the basic interactions between two tensors. :param matching_dims: Word dimension of two interaction texts. :param channels: Number of word interaction tensor channels. :param normalize: Whether to L2-normalize samples along the dot product axis before takin... | stack_v2_sparse_classes_75kplus_train_066347 | 2,319 | permissive | [
{
"docstring": ":class:`MatchingTensor` constructor.",
"name": "__init__",
"signature": "def __init__(self, matching_dim: int, channels: int=4, normalize: bool=True, init_diag: bool=True)"
},
{
"docstring": "The computation logic of MatchingTensor. :param inputs: two input tensors.",
"name":... | 2 | null | Implement the Python class `MatchingTensor` described below.
Class description:
Module that captures the basic interactions between two tensors. :param matching_dims: Word dimension of two interaction texts. :param channels: Number of word interaction tensor channels. :param normalize: Whether to L2-normalize samples ... | Implement the Python class `MatchingTensor` described below.
Class description:
Module that captures the basic interactions between two tensors. :param matching_dims: Word dimension of two interaction texts. :param channels: Number of word interaction tensor channels. :param normalize: Whether to L2-normalize samples ... | 4198ebce942f4afe7ddca6a96ab6f4464ade4518 | <|skeleton|>
class MatchingTensor:
"""Module that captures the basic interactions between two tensors. :param matching_dims: Word dimension of two interaction texts. :param channels: Number of word interaction tensor channels. :param normalize: Whether to L2-normalize samples along the dot product axis before takin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MatchingTensor:
"""Module that captures the basic interactions between two tensors. :param matching_dims: Word dimension of two interaction texts. :param channels: Number of word interaction tensor channels. :param normalize: Whether to L2-normalize samples along the dot product axis before taking the dot pro... | the_stack_v2_python_sparse | poset_decoding/traversal_path_prediction/MatchZoo-py/matchzoo/modules/matching_tensor.py | microsoft/ContextualSP | train | 332 |
02db38fb89c357f036f45f740b00371119c28582 | [
"if not username:\n raise ValueError('User must have an email address')\nif not first_name:\n raise ValueError('Please provide your first name')\nif not last_name:\n raise ValueError('Please provide your last name')\nusername = self.normalize_email(username)\nuser = self.model(username=username, first_name... | <|body_start_0|>
if not username:
raise ValueError('User must have an email address')
if not first_name:
raise ValueError('Please provide your first name')
if not last_name:
raise ValueError('Please provide your last name')
username = self.normalize_em... | Manager for member profiles | MemberManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MemberManager:
"""Manager for member profiles"""
def create_user(self, username, first_name, last_name, password=None):
"""Create a new user profile"""
<|body_0|>
def create_superuser(self, username, first_name, last_name, password):
"""Create and save a new supe... | stack_v2_sparse_classes_75kplus_train_066348 | 5,195 | no_license | [
{
"docstring": "Create a new user profile",
"name": "create_user",
"signature": "def create_user(self, username, first_name, last_name, password=None)"
},
{
"docstring": "Create and save a new superuser with given details",
"name": "create_superuser",
"signature": "def create_superuser(s... | 2 | null | Implement the Python class `MemberManager` described below.
Class description:
Manager for member profiles
Method signatures and docstrings:
- def create_user(self, username, first_name, last_name, password=None): Create a new user profile
- def create_superuser(self, username, first_name, last_name, password): Creat... | Implement the Python class `MemberManager` described below.
Class description:
Manager for member profiles
Method signatures and docstrings:
- def create_user(self, username, first_name, last_name, password=None): Create a new user profile
- def create_superuser(self, username, first_name, last_name, password): Creat... | 8abe5792e0dd869725f4aa794e91a9cd7e577e34 | <|skeleton|>
class MemberManager:
"""Manager for member profiles"""
def create_user(self, username, first_name, last_name, password=None):
"""Create a new user profile"""
<|body_0|>
def create_superuser(self, username, first_name, last_name, password):
"""Create and save a new supe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MemberManager:
"""Manager for member profiles"""
def create_user(self, username, first_name, last_name, password=None):
"""Create a new user profile"""
if not username:
raise ValueError('User must have an email address')
if not first_name:
raise ValueError(... | the_stack_v2_python_sparse | members/models.py | adminstratserver/hbihub-app | train | 0 |
4044b2325d9b03543e5d2640960adccc141694bd | [
"calificacion_producto = get_calificacion_producto_id(id_calificacion_producto)\nif not calificacion_producto:\n api.abort(404)\nelse:\n return calificacion_producto",
"data = request.json\ncalificacion_producto = update_calificacion_producto(id_calificacion_producto, data)\nif not calificacion_producto:\n ... | <|body_start_0|>
calificacion_producto = get_calificacion_producto_id(id_calificacion_producto)
if not calificacion_producto:
api.abort(404)
else:
return calificacion_producto
<|end_body_0|>
<|body_start_1|>
data = request.json
calificacion_producto = upd... | Calificacion_producto | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Calificacion_producto:
def get(self, id_calificacion_producto):
"""get a calificacion_producto given its identifier"""
<|body_0|>
def put(self, id_calificacion_producto):
"""update a calificacion_producto given its identifier"""
<|body_1|>
def delete(sel... | stack_v2_sparse_classes_75kplus_train_066349 | 2,616 | no_license | [
{
"docstring": "get a calificacion_producto given its identifier",
"name": "get",
"signature": "def get(self, id_calificacion_producto)"
},
{
"docstring": "update a calificacion_producto given its identifier",
"name": "put",
"signature": "def put(self, id_calificacion_producto)"
},
{... | 3 | null | Implement the Python class `Calificacion_producto` described below.
Class description:
Implement the Calificacion_producto class.
Method signatures and docstrings:
- def get(self, id_calificacion_producto): get a calificacion_producto given its identifier
- def put(self, id_calificacion_producto): update a calificaci... | Implement the Python class `Calificacion_producto` described below.
Class description:
Implement the Calificacion_producto class.
Method signatures and docstrings:
- def get(self, id_calificacion_producto): get a calificacion_producto given its identifier
- def put(self, id_calificacion_producto): update a calificaci... | e3e6d716102280e73932e5eba65b2ff27eec45e0 | <|skeleton|>
class Calificacion_producto:
def get(self, id_calificacion_producto):
"""get a calificacion_producto given its identifier"""
<|body_0|>
def put(self, id_calificacion_producto):
"""update a calificacion_producto given its identifier"""
<|body_1|>
def delete(sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Calificacion_producto:
def get(self, id_calificacion_producto):
"""get a calificacion_producto given its identifier"""
calificacion_producto = get_calificacion_producto_id(id_calificacion_producto)
if not calificacion_producto:
api.abort(404)
else:
retur... | the_stack_v2_python_sparse | app/main/controller/calificacion_producto_controller.py | Team-3-TCS/api-my-store | train | 1 | |
fc8b4ccd477953ab1a3f95df69d7e4f2c520cddc | [
"if n_features <= 0:\n raise ValueError('The number of features must be positive')\nif depth <= 0:\n raise ValueError('The region graph depth must be positive')\nif depth > int(np.log2(n_features)):\n raise ValueError('Invalid region graph depth based on the number of features')\nself.items = tuple(range(n... | <|body_start_0|>
if n_features <= 0:
raise ValueError('The number of features must be positive')
if depth <= 0:
raise ValueError('The region graph depth must be positive')
if depth > int(np.log2(n_features)):
raise ValueError('Invalid region graph depth based ... | RegionGraph | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegionGraph:
def __init__(self, n_features: int, depth: int, random_state: Optional[RandomState]=None):
"""Initialize a region graph. A region graph is defined w.r.t. a set of indices of random variable in a SPN. A *region* R is defined as a non-empty subset of the indices, and represent... | stack_v2_sparse_classes_75kplus_train_066350 | 4,391 | permissive | [
{
"docstring": "Initialize a region graph. A region graph is defined w.r.t. a set of indices of random variable in a SPN. A *region* R is defined as a non-empty subset of the indices, and represented as sorted tuples with unique entries. A *partition* P of a region R is defined as a collection of non-empty sets... | 3 | stack_v2_sparse_classes_30k_train_011136 | Implement the Python class `RegionGraph` described below.
Class description:
Implement the RegionGraph class.
Method signatures and docstrings:
- def __init__(self, n_features: int, depth: int, random_state: Optional[RandomState]=None): Initialize a region graph. A region graph is defined w.r.t. a set of indices of r... | Implement the Python class `RegionGraph` described below.
Class description:
Implement the RegionGraph class.
Method signatures and docstrings:
- def __init__(self, n_features: int, depth: int, random_state: Optional[RandomState]=None): Initialize a region graph. A region graph is defined w.r.t. a set of indices of r... | 76094fb627e97867542ba2be1292a070028dbfdd | <|skeleton|>
class RegionGraph:
def __init__(self, n_features: int, depth: int, random_state: Optional[RandomState]=None):
"""Initialize a region graph. A region graph is defined w.r.t. a set of indices of random variable in a SPN. A *region* R is defined as a non-empty subset of the indices, and represent... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RegionGraph:
def __init__(self, n_features: int, depth: int, random_state: Optional[RandomState]=None):
"""Initialize a region graph. A region graph is defined w.r.t. a set of indices of random variable in a SPN. A *region* R is defined as a non-empty subset of the indices, and represented as sorted t... | the_stack_v2_python_sparse | deeprob/utils/region.py | deeprob-org/deeprob-kit | train | 66 | |
34df6bae770f18d7f38b3bbc53514008d139426f | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ApprovalSettings()",
"from .unified_approval_stage import UnifiedApprovalStage\nfrom .unified_approval_stage import UnifiedApprovalStage\nfields: Dict[str, Callable[[Any], None]] = {'approvalMode': lambda n: setattr(self, 'approval_mod... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ApprovalSettings()
<|end_body_0|>
<|body_start_1|>
from .unified_approval_stage import UnifiedApprovalStage
from .unified_approval_stage import UnifiedApprovalStage
fields: Dict[... | ApprovalSettings | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApprovalSettings:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ApprovalSettings:
"""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 R... | stack_v2_sparse_classes_75kplus_train_066351 | 4,301 | 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: ApprovalSettings",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_va... | 3 | stack_v2_sparse_classes_30k_train_044353 | Implement the Python class `ApprovalSettings` described below.
Class description:
Implement the ApprovalSettings class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ApprovalSettings: Creates a new instance of the appropriate class based on discrimina... | Implement the Python class `ApprovalSettings` described below.
Class description:
Implement the ApprovalSettings class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ApprovalSettings: Creates a new instance of the appropriate class based on discrimina... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ApprovalSettings:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ApprovalSettings:
"""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 R... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ApprovalSettings:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ApprovalSettings:
"""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: Approv... | the_stack_v2_python_sparse | msgraph/generated/models/approval_settings.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
23a132cbd8bd7855b639e2e447030b7030b815bc | [
"result = parse_ip_and_port(self.get(section, option), default_port)\nif result == (None, 0):\n result = None\nreturn result",
"try:\n return ConfigParser.get(self, section, option)\nexcept (NoSectionError, NoOptionError):\n return None",
"try:\n return ConfigParser.getint(self, section, option)\nex... | <|body_start_0|>
result = parse_ip_and_port(self.get(section, option), default_port)
if result == (None, 0):
result = None
return result
<|end_body_0|>
<|body_start_1|>
try:
return ConfigParser.get(self, section, option)
except (NoSectionError, NoOptionEr... | Adds basic exception handling to ConfigParser. Adds a method to parse IP address and store it in a tuple. | ExtendedConfigParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExtendedConfigParser:
"""Adds basic exception handling to ConfigParser. Adds a method to parse IP address and store it in a tuple."""
def getaddress(self, section, option, default_port=None):
"""Gets IP address with port and stores it in a tuple. Returns None on invalid format or exc... | stack_v2_sparse_classes_75kplus_train_066352 | 1,315 | no_license | [
{
"docstring": "Gets IP address with port and stores it in a tuple. Returns None on invalid format or exceptions.",
"name": "getaddress",
"signature": "def getaddress(self, section, option, default_port=None)"
},
{
"docstring": "Gets string value. Returns None on exceptions.",
"name": "get",... | 4 | stack_v2_sparse_classes_30k_train_013938 | Implement the Python class `ExtendedConfigParser` described below.
Class description:
Adds basic exception handling to ConfigParser. Adds a method to parse IP address and store it in a tuple.
Method signatures and docstrings:
- def getaddress(self, section, option, default_port=None): Gets IP address with port and st... | Implement the Python class `ExtendedConfigParser` described below.
Class description:
Adds basic exception handling to ConfigParser. Adds a method to parse IP address and store it in a tuple.
Method signatures and docstrings:
- def getaddress(self, section, option, default_port=None): Gets IP address with port and st... | 0abf116e1703bca09a946f39d18b1f537a38ccdc | <|skeleton|>
class ExtendedConfigParser:
"""Adds basic exception handling to ConfigParser. Adds a method to parse IP address and store it in a tuple."""
def getaddress(self, section, option, default_port=None):
"""Gets IP address with port and stores it in a tuple. Returns None on invalid format or exc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExtendedConfigParser:
"""Adds basic exception handling to ConfigParser. Adds a method to parse IP address and store it in a tuple."""
def getaddress(self, section, option, default_port=None):
"""Gets IP address with port and stores it in a tuple. Returns None on invalid format or exceptions."""
... | the_stack_v2_python_sparse | ExtendedConfigParser.py | wojtekka/gort | train | 0 |
53f8b4e2d4f91f8c63931242138d7bca69b6a5ed | [
"self.alpha_x = alpha_x\nself.beta_x = beta_x\nself.alpha_y = alpha_y\nself.beta_y = beta_y\nself.dapp_x = dapp_x\nself.dapp_y = dapp_y\nself.dapp_xy = dapp_xy\nself.dapp_yx = dapp_yx",
"Jx = 1 / 2 * ((1 + self.alpha_x ** 2) / self.beta_x * beam.x ** 2 + 2 * self.alpha_x * beam.x * beam.xp + self.beta_x * beam.xp... | <|body_start_0|>
self.alpha_x = alpha_x
self.beta_x = beta_x
self.alpha_y = alpha_y
self.beta_y = beta_y
self.dapp_x = dapp_x
self.dapp_y = dapp_y
self.dapp_xy = dapp_xy
self.dapp_yx = dapp_yx
<|end_body_0|>
<|body_start_1|>
Jx = 1 / 2 * ((1 + sel... | Detuning object for a segment of the accelerator ring to describe amplitude detuning (introduced by octupoles). | AmplitudeDetuningSegment | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AmplitudeDetuningSegment:
"""Detuning object for a segment of the accelerator ring to describe amplitude detuning (introduced by octupoles)."""
def __init__(self, dapp_x, dapp_y, dapp_xy, dapp_yx, alpha_x, beta_x, alpha_y, beta_y):
"""Return an instance of an AmplitudeDetuningSegment... | stack_v2_sparse_classes_75kplus_train_066353 | 12,981 | permissive | [
{
"docstring": "Return an instance of an AmplitudeDetuningSegment by passing the coefficients of detuning strength dapp_x, dapp_y, dapp_xy, dapp_yx (scaled to the segment length. NOT normalized to beam.p0 yet). Note that beta_{x,y} are only used to correctly calculate the transverse actions J_{x,y}. Although th... | 2 | null | Implement the Python class `AmplitudeDetuningSegment` described below.
Class description:
Detuning object for a segment of the accelerator ring to describe amplitude detuning (introduced by octupoles).
Method signatures and docstrings:
- def __init__(self, dapp_x, dapp_y, dapp_xy, dapp_yx, alpha_x, beta_x, alpha_y, b... | Implement the Python class `AmplitudeDetuningSegment` described below.
Class description:
Detuning object for a segment of the accelerator ring to describe amplitude detuning (introduced by octupoles).
Method signatures and docstrings:
- def __init__(self, dapp_x, dapp_y, dapp_xy, dapp_yx, alpha_x, beta_x, alpha_y, b... | b238bf3fbea02fcfaf8795ee54cc0e3134de477a | <|skeleton|>
class AmplitudeDetuningSegment:
"""Detuning object for a segment of the accelerator ring to describe amplitude detuning (introduced by octupoles)."""
def __init__(self, dapp_x, dapp_y, dapp_xy, dapp_yx, alpha_x, beta_x, alpha_y, beta_y):
"""Return an instance of an AmplitudeDetuningSegment... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AmplitudeDetuningSegment:
"""Detuning object for a segment of the accelerator ring to describe amplitude detuning (introduced by octupoles)."""
def __init__(self, dapp_x, dapp_y, dapp_xy, dapp_yx, alpha_x, beta_x, alpha_y, beta_y):
"""Return an instance of an AmplitudeDetuningSegment by passing t... | the_stack_v2_python_sparse | PyHEADTAIL/trackers/detuners.py | PyCOMPLETE/PyHEADTAIL | train | 39 |
6f115dbfeaec3b7fe6b6c51d0a278f094c8096f9 | [
"super(QuestionnaireWidget, self).__init__(rows=2 * len(main_app.question_list) + 1, cols=1)\nself.parent_screen = parent_screen\nself.main_app = main_app\nself.question_list = self.main_app.question_list\nself.questionsArray = []\nself.main_app.user_answers = []\nself.set_questions(self.question_list)\nstore = Jso... | <|body_start_0|>
super(QuestionnaireWidget, self).__init__(rows=2 * len(main_app.question_list) + 1, cols=1)
self.parent_screen = parent_screen
self.main_app = main_app
self.question_list = self.main_app.question_list
self.questionsArray = []
self.main_app.user_answers = ... | QuestionnaireWidget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionnaireWidget:
def __init__(self, parent_screen, main_app):
""":param main_app: The main app that runs the program. We use it to pass on the question list and the user answers"""
<|body_0|>
def submit_action(self, instance):
"""Called when the user presses the ... | stack_v2_sparse_classes_75kplus_train_066354 | 4,800 | no_license | [
{
"docstring": ":param main_app: The main app that runs the program. We use it to pass on the question list and the user answers",
"name": "__init__",
"signature": "def __init__(self, parent_screen, main_app)"
},
{
"docstring": "Called when the user presses the submit button. Saves the user's an... | 3 | stack_v2_sparse_classes_30k_train_001769 | Implement the Python class `QuestionnaireWidget` described below.
Class description:
Implement the QuestionnaireWidget class.
Method signatures and docstrings:
- def __init__(self, parent_screen, main_app): :param main_app: The main app that runs the program. We use it to pass on the question list and the user answer... | Implement the Python class `QuestionnaireWidget` described below.
Class description:
Implement the QuestionnaireWidget class.
Method signatures and docstrings:
- def __init__(self, parent_screen, main_app): :param main_app: The main app that runs the program. We use it to pass on the question list and the user answer... | d276e3d1bd4ee690c995915f99dbda2729fba213 | <|skeleton|>
class QuestionnaireWidget:
def __init__(self, parent_screen, main_app):
""":param main_app: The main app that runs the program. We use it to pass on the question list and the user answers"""
<|body_0|>
def submit_action(self, instance):
"""Called when the user presses the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QuestionnaireWidget:
def __init__(self, parent_screen, main_app):
""":param main_app: The main app that runs the program. We use it to pass on the question list and the user answers"""
super(QuestionnaireWidget, self).__init__(rows=2 * len(main_app.question_list) + 1, cols=1)
self.pare... | the_stack_v2_python_sparse | KivyFiles/Questions/QuestionsDisplay.py | CuriosityLabTAU/graph_game_app | train | 0 | |
2d17536c7321e88617531aabf4f5fb9f24682064 | [
"super().__init__(config, ['WindowedFrequency'], FrequencyVariationPlugin.NAME, exit_event)\nself.freq_ref = float(self.config_get('plugins.FrequencyVariationPlugin.frequency.ref'))\nself.freq_var_low = float(self.config_get('plugins.FrequencyVariationPlugin.frequency.variation.threshold.low'))\nself.freq_var_high ... | <|body_start_0|>
super().__init__(config, ['WindowedFrequency'], FrequencyVariationPlugin.NAME, exit_event)
self.freq_ref = float(self.config_get('plugins.FrequencyVariationPlugin.frequency.ref'))
self.freq_var_low = float(self.config_get('plugins.FrequencyVariationPlugin.frequency.variation.thr... | Mauka plugin that classifies and stores frequency variation incidents for any event that includes a raw waveform | FrequencyVariationPlugin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FrequencyVariationPlugin:
"""Mauka plugin that classifies and stores frequency variation incidents for any event that includes a raw waveform"""
def __init__(self, config: typing.Dict, exit_event: multiprocessing.Event):
"""Initializes this plugin :param config: Mauka configuration :... | stack_v2_sparse_classes_75kplus_train_066355 | 9,666 | no_license | [
{
"docstring": "Initializes this plugin :param config: Mauka configuration :param exit_event: Exit event that can disable this plugin from parent process",
"name": "__init__",
"signature": "def __init__(self, config: typing.Dict, exit_event: multiprocessing.Event)"
},
{
"docstring": "Called asyn... | 2 | stack_v2_sparse_classes_30k_train_018695 | Implement the Python class `FrequencyVariationPlugin` described below.
Class description:
Mauka plugin that classifies and stores frequency variation incidents for any event that includes a raw waveform
Method signatures and docstrings:
- def __init__(self, config: typing.Dict, exit_event: multiprocessing.Event): Ini... | Implement the Python class `FrequencyVariationPlugin` described below.
Class description:
Mauka plugin that classifies and stores frequency variation incidents for any event that includes a raw waveform
Method signatures and docstrings:
- def __init__(self, config: typing.Dict, exit_event: multiprocessing.Event): Ini... | 0795f6140bc93c0a74d8ac788bdea547428517b5 | <|skeleton|>
class FrequencyVariationPlugin:
"""Mauka plugin that classifies and stores frequency variation incidents for any event that includes a raw waveform"""
def __init__(self, config: typing.Dict, exit_event: multiprocessing.Event):
"""Initializes this plugin :param config: Mauka configuration :... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FrequencyVariationPlugin:
"""Mauka plugin that classifies and stores frequency variation incidents for any event that includes a raw waveform"""
def __init__(self, config: typing.Dict, exit_event: multiprocessing.Event):
"""Initializes this plugin :param config: Mauka configuration :param exit_ev... | the_stack_v2_python_sparse | mauka/plugins/frequency_variation_plugin.py | vinipletsch/opq | train | 0 |
5c42dbb93b57ea8ea4b85e8945c89c589c9a037b | [
"num = str(num)\nn = len(num)\nif n <= 1:\n return n\ndp = [0] * n\ndp[0] = 1\nif int(num[:2]) > 25:\n dp[1] = 1\nelse:\n dp[1] = 2\nfor i in range(2, n):\n if int(num[i - 1:i + 1]) <= 25 and int(num[i - 1]) != 0:\n dp[i] = dp[i - 1] + dp[i - 2]\n else:\n dp[i] = dp[i - 1]\nreturn dp[n ... | <|body_start_0|>
num = str(num)
n = len(num)
if n <= 1:
return n
dp = [0] * n
dp[0] = 1
if int(num[:2]) > 25:
dp[1] = 1
else:
dp[1] = 2
for i in range(2, n):
if int(num[i - 1:i + 1]) <= 25 and int(num[i - 1])... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def translateNum0(self, num):
""":type num: int :rtype: int"""
<|body_0|>
def translateNum(self, num):
""":type num: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
num = str(num)
n = len(num)
if n <= 1:
... | stack_v2_sparse_classes_75kplus_train_066356 | 1,620 | no_license | [
{
"docstring": ":type num: int :rtype: int",
"name": "translateNum0",
"signature": "def translateNum0(self, num)"
},
{
"docstring": ":type num: int :rtype: int",
"name": "translateNum",
"signature": "def translateNum(self, num)"
}
] | 2 | stack_v2_sparse_classes_30k_train_035082 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def translateNum0(self, num): :type num: int :rtype: int
- def translateNum(self, num): :type num: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def translateNum0(self, num): :type num: int :rtype: int
- def translateNum(self, num): :type num: int :rtype: int
<|skeleton|>
class Solution:
def translateNum0(self, num)... | 6e18c5d257840489cc3fb1079ae3804c743982a4 | <|skeleton|>
class Solution:
def translateNum0(self, num):
""":type num: int :rtype: int"""
<|body_0|>
def translateNum(self, num):
""":type num: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def translateNum0(self, num):
""":type num: int :rtype: int"""
num = str(num)
n = len(num)
if n <= 1:
return n
dp = [0] * n
dp[0] = 1
if int(num[:2]) > 25:
dp[1] = 1
else:
dp[1] = 2
for i in r... | the_stack_v2_python_sparse | 剑指 Offer 46. 把数字翻译成字符串.py | yangyuxiang1996/leetcode | train | 0 | |
050c285f69a8bd0acd996ab7beec5462991dfc75 | [
"if key is None or item is None:\n pass\nelse:\n self.cache_data[key] = item",
"if key is None:\n return None\ntry:\n value = self.cache_data[key]\nexcept KeyError:\n return None\nreturn value"
] | <|body_start_0|>
if key is None or item is None:
pass
else:
self.cache_data[key] = item
<|end_body_0|>
<|body_start_1|>
if key is None:
return None
try:
value = self.cache_data[key]
except KeyError:
return None
... | Basic cache module that inherits from BaseCaching Args: BaseCaching ([BaseCaching]): [Parent class] | BasicCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicCache:
"""Basic cache module that inherits from BaseCaching Args: BaseCaching ([BaseCaching]): [Parent class]"""
def put(self, key, item):
"""Function to put a new item Args: key ([type]): [Key] item ([type]): [Value]"""
<|body_0|>
def get(self, key):
"""Fun... | stack_v2_sparse_classes_75kplus_train_066357 | 895 | no_license | [
{
"docstring": "Function to put a new item Args: key ([type]): [Key] item ([type]): [Value]",
"name": "put",
"signature": "def put(self, key, item)"
},
{
"docstring": "Funtion to get a value element Args: key ([type]): [Key of the value] Returns: [type]: [value0]",
"name": "get",
"signat... | 2 | null | Implement the Python class `BasicCache` described below.
Class description:
Basic cache module that inherits from BaseCaching Args: BaseCaching ([BaseCaching]): [Parent class]
Method signatures and docstrings:
- def put(self, key, item): Function to put a new item Args: key ([type]): [Key] item ([type]): [Value]
- de... | Implement the Python class `BasicCache` described below.
Class description:
Basic cache module that inherits from BaseCaching Args: BaseCaching ([BaseCaching]): [Parent class]
Method signatures and docstrings:
- def put(self, key, item): Function to put a new item Args: key ([type]): [Key] item ([type]): [Value]
- de... | 014fc078421a2daca65322c51b367a936fa8e20a | <|skeleton|>
class BasicCache:
"""Basic cache module that inherits from BaseCaching Args: BaseCaching ([BaseCaching]): [Parent class]"""
def put(self, key, item):
"""Function to put a new item Args: key ([type]): [Key] item ([type]): [Value]"""
<|body_0|>
def get(self, key):
"""Fun... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BasicCache:
"""Basic cache module that inherits from BaseCaching Args: BaseCaching ([BaseCaching]): [Parent class]"""
def put(self, key, item):
"""Function to put a new item Args: key ([type]): [Key] item ([type]): [Value]"""
if key is None or item is None:
pass
else:
... | the_stack_v2_python_sparse | 0x03-caching/0-basic_cache.py | Nicolanz/holbertonschool-web_back_end | train | 0 |
b2ad43324c89818665a18ededef35ad62fdeddf1 | [
"running_cost = 0\nheapq.heapify(pearl_cost)\nwhile n > 1:\n i = heapq.heappop(pearl_cost)\n j = heapq.heappop(pearl_cost)\n running_cost = running_cost + i + j\n heapq.heappush(pearl_cost, i + j)\n n = n - 1\nreturn running_cost % (10 ** 9 + 7)",
"running_cost = 0\npearl_cost = numpy.array(pearl_c... | <|body_start_0|>
running_cost = 0
heapq.heapify(pearl_cost)
while n > 1:
i = heapq.heappop(pearl_cost)
j = heapq.heappop(pearl_cost)
running_cost = running_cost + i + j
heapq.heappush(pearl_cost, i + j)
n = n - 1
return running_... | PearlsSolution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PearlsSolution:
def Pearls(self, n, pearl_cost):
"""n: number of on the string pearl_cost: list of ints representing cost of joining pearls It always makes sense to merge the two smallest pearls on the string"""
<|body_0|>
def Pearls_numpy(self, n, pearl_cost):
"""n:... | stack_v2_sparse_classes_75kplus_train_066358 | 3,411 | no_license | [
{
"docstring": "n: number of on the string pearl_cost: list of ints representing cost of joining pearls It always makes sense to merge the two smallest pearls on the string",
"name": "Pearls",
"signature": "def Pearls(self, n, pearl_cost)"
},
{
"docstring": "n: number of on the string pearl_cost... | 2 | null | Implement the Python class `PearlsSolution` described below.
Class description:
Implement the PearlsSolution class.
Method signatures and docstrings:
- def Pearls(self, n, pearl_cost): n: number of on the string pearl_cost: list of ints representing cost of joining pearls It always makes sense to merge the two smalle... | Implement the Python class `PearlsSolution` described below.
Class description:
Implement the PearlsSolution class.
Method signatures and docstrings:
- def Pearls(self, n, pearl_cost): n: number of on the string pearl_cost: list of ints representing cost of joining pearls It always makes sense to merge the two smalle... | ddf53992451a834c801471ab7c2acedf95f5c3cc | <|skeleton|>
class PearlsSolution:
def Pearls(self, n, pearl_cost):
"""n: number of on the string pearl_cost: list of ints representing cost of joining pearls It always makes sense to merge the two smallest pearls on the string"""
<|body_0|>
def Pearls_numpy(self, n, pearl_cost):
"""n:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PearlsSolution:
def Pearls(self, n, pearl_cost):
"""n: number of on the string pearl_cost: list of ints representing cost of joining pearls It always makes sense to merge the two smallest pearls on the string"""
running_cost = 0
heapq.heapify(pearl_cost)
while n > 1:
... | the_stack_v2_python_sparse | pearls.py | bridgette/Python100 | train | 4 | |
750aba8ef9a9d27db035f91dea7ee61322273d39 | [
"self.model_path = model_path\nself.model = FPN(num_blocks=[2, 4, 23, 3], num_classes=4, back_bone='resnet101')\nself.model.load_state_dict(torch.load(self.model_path, map_location='cpu'))\nself.model.eval()\nself.transforms = transforms.Compose([transforms.Resize(size=(448, 448)), transforms.ToTensor()])",
"imag... | <|body_start_0|>
self.model_path = model_path
self.model = FPN(num_blocks=[2, 4, 23, 3], num_classes=4, back_bone='resnet101')
self.model.load_state_dict(torch.load(self.model_path, map_location='cpu'))
self.model.eval()
self.transforms = transforms.Compose([transforms.Resize(siz... | EchoCardioInference class. | TTTSInference | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TTTSInference:
"""EchoCardioInference class."""
def __init__(self, model_path: str=None) -> None:
"""Args: model_path:"""
<|body_0|>
def get_visual_prediction(self, image_name, mask_name):
"""Args: image_name: mask_name: Returns:"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus_train_066359 | 2,235 | no_license | [
{
"docstring": "Args: model_path:",
"name": "__init__",
"signature": "def __init__(self, model_path: str=None) -> None"
},
{
"docstring": "Args: image_name: mask_name: Returns:",
"name": "get_visual_prediction",
"signature": "def get_visual_prediction(self, image_name, mask_name)"
}
] | 2 | null | Implement the Python class `TTTSInference` described below.
Class description:
EchoCardioInference class.
Method signatures and docstrings:
- def __init__(self, model_path: str=None) -> None: Args: model_path:
- def get_visual_prediction(self, image_name, mask_name): Args: image_name: mask_name: Returns: | Implement the Python class `TTTSInference` described below.
Class description:
EchoCardioInference class.
Method signatures and docstrings:
- def __init__(self, model_path: str=None) -> None: Args: model_path:
- def get_visual_prediction(self, image_name, mask_name): Args: image_name: mask_name: Returns:
<|skeleton|... | b2caba188cae55458594d3b5e8cfa4c9a7b744ec | <|skeleton|>
class TTTSInference:
"""EchoCardioInference class."""
def __init__(self, model_path: str=None) -> None:
"""Args: model_path:"""
<|body_0|>
def get_visual_prediction(self, image_name, mask_name):
"""Args: image_name: mask_name: Returns:"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TTTSInference:
"""EchoCardioInference class."""
def __init__(self, model_path: str=None) -> None:
"""Args: model_path:"""
self.model_path = model_path
self.model = FPN(num_blocks=[2, 4, 23, 3], num_classes=4, back_bone='resnet101')
self.model.load_state_dict(torch.load(sel... | the_stack_v2_python_sparse | src/inference.py | SanoScience/TTTS_CV | train | 0 |
0cd21a9218d9ec6cf0252c3ecec1bf2fec6352d5 | [
"super().__init__(config, VoltageThresholdPlugin.NAME, exit_event)\nself.voltage_ref = float(self.config_get('plugins.ThresholdPlugin.voltage.ref'))\n'Reference frequency (steady state)'\nself.voltage_percent_low = float(self.config_get('plugins.ThresholdPlugin.voltage.threshold.percent.low'))\n'Percent below refer... | <|body_start_0|>
super().__init__(config, VoltageThresholdPlugin.NAME, exit_event)
self.voltage_ref = float(self.config_get('plugins.ThresholdPlugin.voltage.ref'))
'Reference frequency (steady state)'
self.voltage_percent_low = float(self.config_get('plugins.ThresholdPlugin.voltage.thres... | This module contains the voltage threshold plugin which is responsible for classifying voltage dips and swells | VoltageThresholdPlugin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VoltageThresholdPlugin:
"""This module contains the voltage threshold plugin which is responsible for classifying voltage dips and swells"""
def __init__(self, config: typing.Dict, exit_event: multiprocessing.Event):
"""Initializes this plugin :param config: Configuration dictionary"... | stack_v2_sparse_classes_75kplus_train_066360 | 2,571 | no_license | [
{
"docstring": "Initializes this plugin :param config: Configuration dictionary",
"name": "__init__",
"signature": "def __init__(self, config: typing.Dict, exit_event: multiprocessing.Event)"
},
{
"docstring": "Called when base plugin records a complete threshold event. This will produce a Volta... | 2 | stack_v2_sparse_classes_30k_train_005733 | Implement the Python class `VoltageThresholdPlugin` described below.
Class description:
This module contains the voltage threshold plugin which is responsible for classifying voltage dips and swells
Method signatures and docstrings:
- def __init__(self, config: typing.Dict, exit_event: multiprocessing.Event): Initial... | Implement the Python class `VoltageThresholdPlugin` described below.
Class description:
This module contains the voltage threshold plugin which is responsible for classifying voltage dips and swells
Method signatures and docstrings:
- def __init__(self, config: typing.Dict, exit_event: multiprocessing.Event): Initial... | 0795f6140bc93c0a74d8ac788bdea547428517b5 | <|skeleton|>
class VoltageThresholdPlugin:
"""This module contains the voltage threshold plugin which is responsible for classifying voltage dips and swells"""
def __init__(self, config: typing.Dict, exit_event: multiprocessing.Event):
"""Initializes this plugin :param config: Configuration dictionary"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VoltageThresholdPlugin:
"""This module contains the voltage threshold plugin which is responsible for classifying voltage dips and swells"""
def __init__(self, config: typing.Dict, exit_event: multiprocessing.Event):
"""Initializes this plugin :param config: Configuration dictionary"""
su... | the_stack_v2_python_sparse | mauka/plugins/voltage_threshold_plugin.py | vinipletsch/opq | train | 0 |
0891556a02c3e716d72519031a58e99d7be02e0e | [
"id = str(id)\nif User.exists(id=id):\n resp.media = User.get(id=id).unload()\n resp.status = HTTP_OK\nelse:\n raise HTTPNotFound()",
"id = str(id)\nif User.exists(id=id):\n user = User.get(id=id)\n try:\n update = user.clean(req.media, partial=('id',))\n except ValidationError as error:\... | <|body_start_0|>
id = str(id)
if User.exists(id=id):
resp.media = User.get(id=id).unload()
resp.status = HTTP_OK
else:
raise HTTPNotFound()
<|end_body_0|>
<|body_start_1|>
id = str(id)
if User.exists(id=id):
user = User.get(id=id)
... | UserDetail | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserDetail:
def on_get(self, req, resp, id, **params):
"""Get specifig user based on their id. --- tags: - user summary: Show user data description: Get specific user information operationId: getUser consumes: - application/json produces: - application/json parameters: - in: header name:... | stack_v2_sparse_classes_75kplus_train_066361 | 8,731 | permissive | [
{
"docstring": "Get specifig user based on their id. --- tags: - user summary: Show user data description: Get specific user information operationId: getUser consumes: - application/json produces: - application/json parameters: - in: header name: origin type: string required: true description: CORS request orig... | 3 | stack_v2_sparse_classes_30k_train_001776 | Implement the Python class `UserDetail` described below.
Class description:
Implement the UserDetail class.
Method signatures and docstrings:
- def on_get(self, req, resp, id, **params): Get specifig user based on their id. --- tags: - user summary: Show user data description: Get specific user information operationI... | Implement the Python class `UserDetail` described below.
Class description:
Implement the UserDetail class.
Method signatures and docstrings:
- def on_get(self, req, resp, id, **params): Get specifig user based on their id. --- tags: - user summary: Show user data description: Get specific user information operationI... | 98b85b399ccf528794c775c0765bceb88f47ad5a | <|skeleton|>
class UserDetail:
def on_get(self, req, resp, id, **params):
"""Get specifig user based on their id. --- tags: - user summary: Show user data description: Get specific user information operationId: getUser consumes: - application/json produces: - application/json parameters: - in: header name:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserDetail:
def on_get(self, req, resp, id, **params):
"""Get specifig user based on their id. --- tags: - user summary: Show user data description: Get specific user information operationId: getUser consumes: - application/json produces: - application/json parameters: - in: header name: origin type: ... | the_stack_v2_python_sparse | muria/resource/user.py | xakiy/muria | train | 1 | |
1451ccf5ff0951b9c8a222db4384a22ec0166fec | [
"super(ConvolutionModule, self).__init__()\nassert (depthwise_kernel_size - 1) % 2 == 0, \"kernel_size should be a odd number for 'SAME' padding\"\nself.layer_norm = LayerNorm(embed_dim, export=export)\nself.pointwise_conv1 = torch.nn.Conv1d(embed_dim, 2 * channels, kernel_size=1, stride=1, padding=0, bias=bias)\ns... | <|body_start_0|>
super(ConvolutionModule, self).__init__()
assert (depthwise_kernel_size - 1) % 2 == 0, "kernel_size should be a odd number for 'SAME' padding"
self.layer_norm = LayerNorm(embed_dim, export=export)
self.pointwise_conv1 = torch.nn.Conv1d(embed_dim, 2 * channels, kernel_siz... | Convolution block used in the conformer block | ConvolutionModule | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"LGPL-2.1-or-later",
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvolutionModule:
"""Convolution block used in the conformer block"""
def __init__(self, embed_dim, channels, depthwise_kernel_size, dropout, activation_fn='swish', bias=False, export=False):
"""Args: embed_dim: Embedding dimension channels: Number of channels in depthwise conv laye... | stack_v2_sparse_classes_75kplus_train_066362 | 9,087 | permissive | [
{
"docstring": "Args: embed_dim: Embedding dimension channels: Number of channels in depthwise conv layers depthwise_kernel_size: Depthwise conv layer kernel size dropout: dropout value activation_fn: Activation function to use after depthwise convolution kernel bias: If bias should be added to conv layers expo... | 2 | stack_v2_sparse_classes_30k_train_014422 | Implement the Python class `ConvolutionModule` described below.
Class description:
Convolution block used in the conformer block
Method signatures and docstrings:
- def __init__(self, embed_dim, channels, depthwise_kernel_size, dropout, activation_fn='swish', bias=False, export=False): Args: embed_dim: Embedding dime... | Implement the Python class `ConvolutionModule` described below.
Class description:
Convolution block used in the conformer block
Method signatures and docstrings:
- def __init__(self, embed_dim, channels, depthwise_kernel_size, dropout, activation_fn='swish', bias=False, export=False): Args: embed_dim: Embedding dime... | b60c741f746877293bb85eed6806736fc8fa0ffd | <|skeleton|>
class ConvolutionModule:
"""Convolution block used in the conformer block"""
def __init__(self, embed_dim, channels, depthwise_kernel_size, dropout, activation_fn='swish', bias=False, export=False):
"""Args: embed_dim: Embedding dimension channels: Number of channels in depthwise conv laye... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConvolutionModule:
"""Convolution block used in the conformer block"""
def __init__(self, embed_dim, channels, depthwise_kernel_size, dropout, activation_fn='swish', bias=False, export=False):
"""Args: embed_dim: Embedding dimension channels: Number of channels in depthwise conv layers depthwise_... | the_stack_v2_python_sparse | kosmos-2/fairseq/fairseq/modules/conformer_layer.py | microsoft/unilm | train | 15,313 |
9668b28e0c7fe3e60959dab2a17ca53bc4762273 | [
"n = len(seats)\nL = [float('inf') for _ in range(n)]\nR = [float('inf') for _ in range(n)]\nfor i in range(n):\n if seats[i] == 1:\n L[i] = 0\n elif i - 1 >= 0:\n L[i] = L[i - 1] + 1\nfor i in range(n - 1, -1, -1):\n if seats[i] == 1:\n R[i] = 0\n elif i + 1 < n:\n R[i] = R[... | <|body_start_0|>
n = len(seats)
L = [float('inf') for _ in range(n)]
R = [float('inf') for _ in range(n)]
for i in range(n):
if seats[i] == 1:
L[i] = 0
elif i - 1 >= 0:
L[i] = L[i - 1] + 1
for i in range(n - 1, -1, -1):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxDistToClosest(self, seats: List[int]) -> int:
"""DP from left and right - next array Let L[i] be the distant to the left 1 at A[i] Let R[i] ..."""
<|body_0|>
def maxDistToClosest2(self, seats: List[int]) -> int:
"""maintain a sorrted index array"""
... | stack_v2_sparse_classes_75kplus_train_066363 | 2,432 | no_license | [
{
"docstring": "DP from left and right - next array Let L[i] be the distant to the left 1 at A[i] Let R[i] ...",
"name": "maxDistToClosest",
"signature": "def maxDistToClosest(self, seats: List[int]) -> int"
},
{
"docstring": "maintain a sorrted index array",
"name": "maxDistToClosest2",
... | 2 | stack_v2_sparse_classes_30k_train_002715 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDistToClosest(self, seats: List[int]) -> int: DP from left and right - next array Let L[i] be the distant to the left 1 at A[i] Let R[i] ...
- def maxDistToClosest2(self, ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDistToClosest(self, seats: List[int]) -> int: DP from left and right - next array Let L[i] be the distant to the left 1 at A[i] Let R[i] ...
- def maxDistToClosest2(self, ... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def maxDistToClosest(self, seats: List[int]) -> int:
"""DP from left and right - next array Let L[i] be the distant to the left 1 at A[i] Let R[i] ..."""
<|body_0|>
def maxDistToClosest2(self, seats: List[int]) -> int:
"""maintain a sorrted index array"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxDistToClosest(self, seats: List[int]) -> int:
"""DP from left and right - next array Let L[i] be the distant to the left 1 at A[i] Let R[i] ..."""
n = len(seats)
L = [float('inf') for _ in range(n)]
R = [float('inf') for _ in range(n)]
for i in range(n)... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetCode/849 Maximize Distance to Closest Person.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
cd30f1d2bb62be7377df61423cd19a3d3f1c7e80 | [
"wb = load_workbook('APITestCases.xlsx')\nst = wb['register']\nall_row = []\nfor i in range(2, st.max_row + 1):\n each_row = []\n for j in range(1, st.max_column):\n res = st.cell(i, j).value\n each_row.append(res)\n all_row.append(each_row)\nreturn all_row",
"wb = load_workbook('APITestCas... | <|body_start_0|>
wb = load_workbook('APITestCases.xlsx')
st = wb['register']
all_row = []
for i in range(2, st.max_row + 1):
each_row = []
for j in range(1, st.max_column):
res = st.cell(i, j).value
each_row.append(res)
... | 从excel中测试数据,并且能够写回测试结果,要求有返回值 | DoExcel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DoExcel:
"""从excel中测试数据,并且能够写回测试结果,要求有返回值"""
def read_excel(self):
"""读取数据"""
<|body_0|>
def write_result(self, row, column, value):
"""写回测试结果"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
wb = load_workbook('APITestCases.xlsx')
st = w... | stack_v2_sparse_classes_75kplus_train_066364 | 1,959 | no_license | [
{
"docstring": "读取数据",
"name": "read_excel",
"signature": "def read_excel(self)"
},
{
"docstring": "写回测试结果",
"name": "write_result",
"signature": "def write_result(self, row, column, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_050330 | Implement the Python class `DoExcel` described below.
Class description:
从excel中测试数据,并且能够写回测试结果,要求有返回值
Method signatures and docstrings:
- def read_excel(self): 读取数据
- def write_result(self, row, column, value): 写回测试结果 | Implement the Python class `DoExcel` described below.
Class description:
从excel中测试数据,并且能够写回测试结果,要求有返回值
Method signatures and docstrings:
- def read_excel(self): 读取数据
- def write_result(self, row, column, value): 写回测试结果
<|skeleton|>
class DoExcel:
"""从excel中测试数据,并且能够写回测试结果,要求有返回值"""
def read_excel(self):
... | ca931cd49192ea07a8f8b3640e2a3513b6338288 | <|skeleton|>
class DoExcel:
"""从excel中测试数据,并且能够写回测试结果,要求有返回值"""
def read_excel(self):
"""读取数据"""
<|body_0|>
def write_result(self, row, column, value):
"""写回测试结果"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DoExcel:
"""从excel中测试数据,并且能够写回测试结果,要求有返回值"""
def read_excel(self):
"""读取数据"""
wb = load_workbook('APITestCases.xlsx')
st = wb['register']
all_row = []
for i in range(2, st.max_row + 1):
each_row = []
for j in range(1, st.max_column):
... | the_stack_v2_python_sparse | week_8/task_0308/request_excel.py | futurewujun/python_14_0402 | train | 0 |
8d925e4c7a2719ac7a10c0546a33b42d738b758e | [
"self.api_adapter = api_adapter\nself.gke_uri = gke_uri\nself.gke_cluster = gke_cluster\nself.kubeconfig = kubeconfig\nself.internal_ip = internal_ip\nself.cross_connect_subnetwork = cross_connect_subnetwork\nself.private_endpoint_fqdn = private_endpoint_fqdn\nself.context = context\nif not c_util.CheckKubectlInsta... | <|body_start_0|>
self.api_adapter = api_adapter
self.gke_uri = gke_uri
self.gke_cluster = gke_cluster
self.kubeconfig = kubeconfig
self.internal_ip = internal_ip
self.cross_connect_subnetwork = cross_connect_subnetwork
self.private_endpoint_fqdn = private_endpoint... | A helper class that processes kubeconfig and context arguments. | KubeconfigProcessor | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KubeconfigProcessor:
"""A helper class that processes kubeconfig and context arguments."""
def __init__(self, api_adapter, gke_uri, gke_cluster, kubeconfig, internal_ip, cross_connect_subnetwork, private_endpoint_fqdn, context):
"""Constructor for KubeconfigProcessor. Args: api_adapt... | stack_v2_sparse_classes_75kplus_train_066365 | 44,482 | permissive | [
{
"docstring": "Constructor for KubeconfigProcessor. Args: api_adapter: the GKE api adapter used for running kubernetes commands gke_uri: the URI of the GKE cluster; for example, 'https://container.googleapis.com/v1/projects/my-project/locations/us-central1-a/clusters/my-cluster' gke_cluster: the \"location/nam... | 3 | stack_v2_sparse_classes_30k_train_049528 | Implement the Python class `KubeconfigProcessor` described below.
Class description:
A helper class that processes kubeconfig and context arguments.
Method signatures and docstrings:
- def __init__(self, api_adapter, gke_uri, gke_cluster, kubeconfig, internal_ip, cross_connect_subnetwork, private_endpoint_fqdn, conte... | Implement the Python class `KubeconfigProcessor` described below.
Class description:
A helper class that processes kubeconfig and context arguments.
Method signatures and docstrings:
- def __init__(self, api_adapter, gke_uri, gke_cluster, kubeconfig, internal_ip, cross_connect_subnetwork, private_endpoint_fqdn, conte... | 1f9b424c40a87b46656fc9f5e2e9c81895c7e614 | <|skeleton|>
class KubeconfigProcessor:
"""A helper class that processes kubeconfig and context arguments."""
def __init__(self, api_adapter, gke_uri, gke_cluster, kubeconfig, internal_ip, cross_connect_subnetwork, private_endpoint_fqdn, context):
"""Constructor for KubeconfigProcessor. Args: api_adapt... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KubeconfigProcessor:
"""A helper class that processes kubeconfig and context arguments."""
def __init__(self, api_adapter, gke_uri, gke_cluster, kubeconfig, internal_ip, cross_connect_subnetwork, private_endpoint_fqdn, context):
"""Constructor for KubeconfigProcessor. Args: api_adapter: the GKE a... | the_stack_v2_python_sparse | google-cloud-sdk/lib/googlecloudsdk/command_lib/container/hub/kube_util.py | twistedpair/google-cloud-sdk | train | 58 |
2608b18f0a56618f78bebbe08254762554d26b37 | [
"if Generation.__instance == None:\n Generation()\nreturn Generation.__instance",
"if Generation.__instance != None:\n raise Exception('This class is a singleton!')\nelse:\n Generation.__instance = self\nself.index = index"
] | <|body_start_0|>
if Generation.__instance == None:
Generation()
return Generation.__instance
<|end_body_0|>
<|body_start_1|>
if Generation.__instance != None:
raise Exception('This class is a singleton!')
else:
Generation.__instance = self
sel... | Generation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Generation:
def getInstance():
"""Static access method."""
<|body_0|>
def __init__(self, index=0):
"""Virtually private constructor."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if Generation.__instance == None:
Generation()
r... | stack_v2_sparse_classes_75kplus_train_066366 | 686 | no_license | [
{
"docstring": "Static access method.",
"name": "getInstance",
"signature": "def getInstance()"
},
{
"docstring": "Virtually private constructor.",
"name": "__init__",
"signature": "def __init__(self, index=0)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013071 | Implement the Python class `Generation` described below.
Class description:
Implement the Generation class.
Method signatures and docstrings:
- def getInstance(): Static access method.
- def __init__(self, index=0): Virtually private constructor. | Implement the Python class `Generation` described below.
Class description:
Implement the Generation class.
Method signatures and docstrings:
- def getInstance(): Static access method.
- def __init__(self, index=0): Virtually private constructor.
<|skeleton|>
class Generation:
def getInstance():
"""Stat... | 443e2e4ebddc069d8bd7765de59ded1a3b9cc831 | <|skeleton|>
class Generation:
def getInstance():
"""Static access method."""
<|body_0|>
def __init__(self, index=0):
"""Virtually private constructor."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Generation:
def getInstance():
"""Static access method."""
if Generation.__instance == None:
Generation()
return Generation.__instance
def __init__(self, index=0):
"""Virtually private constructor."""
if Generation.__instance != None:
raise ... | the_stack_v2_python_sparse | src/presenter/generation.py | karinemiras/evo_gan | train | 0 | |
506507bac4769c857f5466906e713d3118799ea0 | [
"super(ConsolePrompt, self).__init__()\nself.daemon = True\nself._message = message\nself._callback = callback\nself._color = color\nself._stop_event = threading.Event()\nself._answered = False",
"self._stop_event.set()\nif not self._answered:\n console_output.cli_print(os.linesep, color=self._color, end='', l... | <|body_start_0|>
super(ConsolePrompt, self).__init__()
self.daemon = True
self._message = message
self._callback = callback
self._color = color
self._stop_event = threading.Event()
self._answered = False
<|end_body_0|>
<|body_start_1|>
self._stop_event.se... | Thread that displays a prompt to the console and waits for a response. This should not be used for processes that run in the background. | ConsolePrompt | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConsolePrompt:
"""Thread that displays a prompt to the console and waits for a response. This should not be used for processes that run in the background."""
def __init__(self, message: Text, callback: Callable[[Text], None], color: Text=''):
"""Initializes a ConsolePrompt. Args: mes... | stack_v2_sparse_classes_75kplus_train_066367 | 10,088 | permissive | [
{
"docstring": "Initializes a ConsolePrompt. Args: message: A string to be presented to the user. callback: A function to be called with the response string. color: An ANSI color code, or the empty string.",
"name": "__init__",
"signature": "def __init__(self, message: Text, callback: Callable[[Text], N... | 3 | stack_v2_sparse_classes_30k_train_001545 | Implement the Python class `ConsolePrompt` described below.
Class description:
Thread that displays a prompt to the console and waits for a response. This should not be used for processes that run in the background.
Method signatures and docstrings:
- def __init__(self, message: Text, callback: Callable[[Text], None]... | Implement the Python class `ConsolePrompt` described below.
Class description:
Thread that displays a prompt to the console and waits for a response. This should not be used for processes that run in the background.
Method signatures and docstrings:
- def __init__(self, message: Text, callback: Callable[[Text], None]... | 3a9a24987b2b34782fca55a8df8d007167dbb19a | <|skeleton|>
class ConsolePrompt:
"""Thread that displays a prompt to the console and waits for a response. This should not be used for processes that run in the background."""
def __init__(self, message: Text, callback: Callable[[Text], None], color: Text=''):
"""Initializes a ConsolePrompt. Args: mes... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConsolePrompt:
"""Thread that displays a prompt to the console and waits for a response. This should not be used for processes that run in the background."""
def __init__(self, message: Text, callback: Callable[[Text], None], color: Text=''):
"""Initializes a ConsolePrompt. Args: message: A strin... | the_stack_v2_python_sparse | openhtf/plugs/user_input.py | google/openhtf | train | 471 |
475a6962b06771ae2aa84b58ed3df32c6db3d0ca | [
"if not db_dict:\n ValueError('Database definition required to open database is empty. Data base may not be defined in config file.')\ntry:\n connection = MySQLConnection(host=db_dict['host'], database=db_dict['database'], user=db_dict['user'], password=db_dict['password'])\n if connection.is_connected():... | <|body_start_0|>
if not db_dict:
ValueError('Database definition required to open database is empty. Data base may not be defined in config file.')
try:
connection = MySQLConnection(host=db_dict['host'], database=db_dict['database'], user=db_dict['user'], password=db_dict['passw... | Provides some common methods to mixin in with the MySQL...Tables classes Returns Raises: ValueError if defintion not valid or database cannot be opened. | MySQLDBMixin | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MySQLDBMixin:
"""Provides some common methods to mixin in with the MySQL...Tables classes Returns Raises: ValueError if defintion not valid or database cannot be opened."""
def connectdb(self, db_dict, verbose):
"""Connect the db"""
<|body_0|>
def _load_table(self):
... | stack_v2_sparse_classes_75kplus_train_066368 | 3,038 | permissive | [
{
"docstring": "Connect the db",
"name": "connectdb",
"signature": "def connectdb(self, db_dict, verbose)"
},
{
"docstring": "Load the internal dictionary from the database based on the fields definition",
"name": "_load_table",
"signature": "def _load_table(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017995 | Implement the Python class `MySQLDBMixin` described below.
Class description:
Provides some common methods to mixin in with the MySQL...Tables classes Returns Raises: ValueError if defintion not valid or database cannot be opened.
Method signatures and docstrings:
- def connectdb(self, db_dict, verbose): Connect the ... | Implement the Python class `MySQLDBMixin` described below.
Class description:
Provides some common methods to mixin in with the MySQL...Tables classes Returns Raises: ValueError if defintion not valid or database cannot be opened.
Method signatures and docstrings:
- def connectdb(self, db_dict, verbose): Connect the ... | 9c60b3489f02592bd9099b8719ca23ae43a9eaa5 | <|skeleton|>
class MySQLDBMixin:
"""Provides some common methods to mixin in with the MySQL...Tables classes Returns Raises: ValueError if defintion not valid or database cannot be opened."""
def connectdb(self, db_dict, verbose):
"""Connect the db"""
<|body_0|>
def _load_table(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MySQLDBMixin:
"""Provides some common methods to mixin in with the MySQL...Tables classes Returns Raises: ValueError if defintion not valid or database cannot be opened."""
def connectdb(self, db_dict, verbose):
"""Connect the db"""
if not db_dict:
ValueError('Database definit... | the_stack_v2_python_sparse | smipyping/_mysqldbmixin.py | KSchopmeyer/smipyping | train | 0 |
aa3827ace2e5554bf982e5dad99076878354973c | [
"super(NonLocalBlock, self).__init__()\nself.compression_factor = 1 if args.use_precomputed_hiddens else compression_factor\nself.theta_conv = nn.Conv2d(inplanes, inplanes // 2, kernel_size=1, bias=False)\nself.phi_conv = nn.Conv2d(inplanes, inplanes // 2, kernel_size=1, bias=False)\nself.g_conv = nn.Conv2d(inplane... | <|body_start_0|>
super(NonLocalBlock, self).__init__()
self.compression_factor = 1 if args.use_precomputed_hiddens else compression_factor
self.theta_conv = nn.Conv2d(inplanes, inplanes // 2, kernel_size=1, bias=False)
self.phi_conv = nn.Conv2d(inplanes, inplanes // 2, kernel_size=1, bia... | An embedded gaussian non-local block. | NonLocalBlock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NonLocalBlock:
"""An embedded gaussian non-local block."""
def __init__(self, args, inplanes, planes, stride=1, downsample=None, compression_factor=2):
"""Initializes the NonLocalBlock. Arguments: inplanes(int): The depth (number of channels) of the input. planes(int): The depth (num... | stack_v2_sparse_classes_75kplus_train_066369 | 4,206 | permissive | [
{
"docstring": "Initializes the NonLocalBlock. Arguments: inplanes(int): The depth (number of channels) of the input. planes(int): The depth (number of channels) of the output. downsample(nn.Module): When not none, used to downsample output to planes. compression_factor(int): The compression factor to use when ... | 2 | stack_v2_sparse_classes_30k_train_013137 | Implement the Python class `NonLocalBlock` described below.
Class description:
An embedded gaussian non-local block.
Method signatures and docstrings:
- def __init__(self, args, inplanes, planes, stride=1, downsample=None, compression_factor=2): Initializes the NonLocalBlock. Arguments: inplanes(int): The depth (numb... | Implement the Python class `NonLocalBlock` described below.
Class description:
An embedded gaussian non-local block.
Method signatures and docstrings:
- def __init__(self, args, inplanes, planes, stride=1, downsample=None, compression_factor=2): Initializes the NonLocalBlock. Arguments: inplanes(int): The depth (numb... | 12bace8fd6ce9c5bb129fd0d30a46a00a2f7b054 | <|skeleton|>
class NonLocalBlock:
"""An embedded gaussian non-local block."""
def __init__(self, args, inplanes, planes, stride=1, downsample=None, compression_factor=2):
"""Initializes the NonLocalBlock. Arguments: inplanes(int): The depth (number of channels) of the input. planes(int): The depth (num... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NonLocalBlock:
"""An embedded gaussian non-local block."""
def __init__(self, args, inplanes, planes, stride=1, downsample=None, compression_factor=2):
"""Initializes the NonLocalBlock. Arguments: inplanes(int): The depth (number of channels) of the input. planes(int): The depth (number of channe... | the_stack_v2_python_sparse | onconet/models/blocks/non_local_block.py | yala/Mirai | train | 66 |
ac3a03cb6049f3ee25d61ec2cc0d211dadabb7f3 | [
"self.l = nums\nself.l_cum_sum = []\ns = 0\nfor i in range(len(nums)):\n s = s + nums[i]\n self.l_cum_sum.append(s)",
"if left == 0:\n return self.l_cum_sum[right]\nelse:\n return self.l_cum_sum[right] - self.l_cum_sum[left - 1]"
] | <|body_start_0|>
self.l = nums
self.l_cum_sum = []
s = 0
for i in range(len(nums)):
s = s + nums[i]
self.l_cum_sum.append(s)
<|end_body_0|>
<|body_start_1|>
if left == 0:
return self.l_cum_sum[right]
else:
return self.l_cum... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, left, right):
""":type left: int :type right: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.l = nums
self.l_cum_sum = []
... | stack_v2_sparse_classes_75kplus_train_066370 | 892 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type left: int :type right: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, left, right)"
}
] | 2 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, left, right): :type left: int :type right: int :rtype: int | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, left, right): :type left: int :type right: int :rtype: int
<|skeleton|>
class NumArray:
def __init__(se... | 013c16574fd6082ae80aa074f1d9579a077261b7 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, left, right):
""":type left: int :type right: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self.l = nums
self.l_cum_sum = []
s = 0
for i in range(len(nums)):
s = s + nums[i]
self.l_cum_sum.append(s)
def sumRange(self, left, right):
""":type left: int :type rig... | the_stack_v2_python_sparse | E_303. Range Sum Query - Immutable.py | Xuan4dream/Leetcode | train | 0 | |
74740fad7b96eeb46118e5d97bf81abef5df8f6e | [
"super().__init__(coordinator, device, 'extra', 'Extra meter', f'extra_{dev_type}')\nself._type = dev_type\nself._attr_name = f'Extra {dev_type}'",
"if self.coordinator.data.extra_meter is None:\n return None\nreturn getattr(self.coordinator.data.extra_meter, f'_{self._type}', None)"
] | <|body_start_0|>
super().__init__(coordinator, device, 'extra', 'Extra meter', f'extra_{dev_type}')
self._type = dev_type
self._attr_name = f'Extra {dev_type}'
<|end_body_0|>
<|body_start_1|>
if self.coordinator.data.extra_meter is None:
return None
return getattr(se... | The Youless extra meter power value sensor (s0). | ExtraMeterPowerSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExtraMeterPowerSensor:
"""The Youless extra meter power value sensor (s0)."""
def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, dev_type: str) -> None:
"""Instantiate an extra meter power sensor."""
<|body_0|>
def get_sensor(self) -> Youless... | stack_v2_sparse_classes_75kplus_train_066371 | 11,812 | permissive | [
{
"docstring": "Instantiate an extra meter power sensor.",
"name": "__init__",
"signature": "def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, dev_type: str) -> None"
},
{
"docstring": "Get the sensor for providing the value.",
"name": "get_sensor",
"signatu... | 2 | stack_v2_sparse_classes_30k_test_001834 | Implement the Python class `ExtraMeterPowerSensor` described below.
Class description:
The Youless extra meter power value sensor (s0).
Method signatures and docstrings:
- def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, dev_type: str) -> None: Instantiate an extra meter power sensor.
-... | Implement the Python class `ExtraMeterPowerSensor` described below.
Class description:
The Youless extra meter power value sensor (s0).
Method signatures and docstrings:
- def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, dev_type: str) -> None: Instantiate an extra meter power sensor.
-... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ExtraMeterPowerSensor:
"""The Youless extra meter power value sensor (s0)."""
def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, dev_type: str) -> None:
"""Instantiate an extra meter power sensor."""
<|body_0|>
def get_sensor(self) -> Youless... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExtraMeterPowerSensor:
"""The Youless extra meter power value sensor (s0)."""
def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, dev_type: str) -> None:
"""Instantiate an extra meter power sensor."""
super().__init__(coordinator, device, 'extra', 'Extra meter'... | the_stack_v2_python_sparse | homeassistant/components/youless/sensor.py | home-assistant/core | train | 35,501 |
d2760002797f79222adf421db8c20444626ffd7a | [
"if len(s) < 2:\n return len(s)\nrecond = dict()\nleft, right = (-1, 0)\nres = 0\nfor right in range(len(s)):\n left = max(left, recond.setdefault(s[right], -1))\n recond[s[right]] = right\n res = max(res, right - left)\nreturn res",
"l = len(s)\nif l < 2:\n return l\ndp = [1 for _ in range(l)]\nma... | <|body_start_0|>
if len(s) < 2:
return len(s)
recond = dict()
left, right = (-1, 0)
res = 0
for right in range(len(s)):
left = max(left, recond.setdefault(s[right], -1))
recond[s[right]] = right
res = max(res, right - left)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
""":param s: :return:"""
<|body_0|>
def lengthOfLongestSubstring1(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(s) < 2:
return len(s)
... | stack_v2_sparse_classes_75kplus_train_066372 | 1,657 | no_license | [
{
"docstring": ":param s: :return:",
"name": "lengthOfLongestSubstring",
"signature": "def lengthOfLongestSubstring(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLongestSubstring1",
"signature": "def lengthOfLongestSubstring1(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_032145 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): :param s: :return:
- def lengthOfLongestSubstring1(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): :param s: :return:
- def lengthOfLongestSubstring1(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def lengthOfLonges... | 70b7a0f031ef4bc1b04ae787ac1fd78f2f25a04d | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
""":param s: :return:"""
<|body_0|>
def lengthOfLongestSubstring1(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def lengthOfLongestSubstring(self, s):
""":param s: :return:"""
if len(s) < 2:
return len(s)
recond = dict()
left, right = (-1, 0)
res = 0
for right in range(len(s)):
left = max(left, recond.setdefault(s[right], -1))
... | the_stack_v2_python_sparse | 1--20/03lengthOfLongestSubstring.py | tzhou2018/LeetCode | train | 6 | |
87ecd5518f3befb9afe7101947964df954e1d40e | [
"checked_choid: Set[ObjectId] = set()\nret: List[ChannelData] = []\nmissing = []\nch_oids = ProfileManager.get_users_exist_channel_dict([root_oid]).get(root_oid)\nif not ch_oids:\n return ret\nfor ch_model in ChannelManager.get_channel_default_name(keyword, hide_private=True):\n ch_oid = ch_model.id\n if c... | <|body_start_0|>
checked_choid: Set[ObjectId] = set()
ret: List[ChannelData] = []
missing = []
ch_oids = ProfileManager.get_users_exist_channel_dict([root_oid]).get(root_oid)
if not ch_oids:
return ret
for ch_model in ChannelManager.get_channel_default_name(ke... | Class to search for any types of identity data. | IdentitySearcher | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IdentitySearcher:
"""Class to search for any types of identity data."""
def search_channel(keyword: str, root_oid: ObjectId) -> List[ChannelData]:
"""Search the channels that the user ``root_oid`` is inside using ``keyword``. This search **hides** all private channels. Returned resul... | stack_v2_sparse_classes_75kplus_train_066373 | 4,634 | permissive | [
{
"docstring": "Search the channels that the user ``root_oid`` is inside using ``keyword``. This search **hides** all private channels. Returned result will be sorted by last message time (DESC) then by its ID (DESC). ----------- ``keyword`` can be: - partial word from the message of a channel - a part of the d... | 2 | stack_v2_sparse_classes_30k_val_001124 | Implement the Python class `IdentitySearcher` described below.
Class description:
Class to search for any types of identity data.
Method signatures and docstrings:
- def search_channel(keyword: str, root_oid: ObjectId) -> List[ChannelData]: Search the channels that the user ``root_oid`` is inside using ``keyword``. T... | Implement the Python class `IdentitySearcher` described below.
Class description:
Class to search for any types of identity data.
Method signatures and docstrings:
- def search_channel(keyword: str, root_oid: ObjectId) -> List[ChannelData]: Search the channels that the user ``root_oid`` is inside using ``keyword``. T... | c7da1e91783dce3a2b71b955b3a22b68db9056cf | <|skeleton|>
class IdentitySearcher:
"""Class to search for any types of identity data."""
def search_channel(keyword: str, root_oid: ObjectId) -> List[ChannelData]:
"""Search the channels that the user ``root_oid`` is inside using ``keyword``. This search **hides** all private channels. Returned resul... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IdentitySearcher:
"""Class to search for any types of identity data."""
def search_channel(keyword: str, root_oid: ObjectId) -> List[ChannelData]:
"""Search the channels that the user ``root_oid`` is inside using ``keyword``. This search **hides** all private channels. Returned result will be sor... | the_stack_v2_python_sparse | mongodb/helper/search.py | RxJellyBot/Jelly-Bot | train | 5 |
8bf71c8b933406fbd71b0667c2a22f60091e7b49 | [
"if self.action in ['create']:\n permission_classes = [PortToPlaylistExists]\nelif self.action in ['destroy']:\n permission_classes = [UserIsAuthenticated & IsPortabilityRequestOwner]\nelif self.action in ['retrieve']:\n permission_classes = [UserIsAuthenticated & (IsPortabilityRequestOwner | IsPlaylistOwn... | <|body_start_0|>
if self.action in ['create']:
permission_classes = [PortToPlaylistExists]
elif self.action in ['destroy']:
permission_classes = [UserIsAuthenticated & IsPortabilityRequestOwner]
elif self.action in ['retrieve']:
permission_classes = [UserIsAut... | Viewset for the API of the portability request object. | PortabilityResourceViewSet | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PortabilityResourceViewSet:
"""Viewset for the API of the portability request object."""
def get_permissions(self):
"""Manage permissions for built-in DRF methods. Default to the ViewSet's default permissions. Only the `create` view is available from LTI."""
<|body_0|>
d... | stack_v2_sparse_classes_75kplus_train_066374 | 6,199 | permissive | [
{
"docstring": "Manage permissions for built-in DRF methods. Default to the ViewSet's default permissions. Only the `create` view is available from LTI.",
"name": "get_permissions",
"signature": "def get_permissions(self)"
},
{
"docstring": "Return the queryset according to the action.",
"na... | 5 | stack_v2_sparse_classes_30k_train_009443 | Implement the Python class `PortabilityResourceViewSet` described below.
Class description:
Viewset for the API of the portability request object.
Method signatures and docstrings:
- def get_permissions(self): Manage permissions for built-in DRF methods. Default to the ViewSet's default permissions. Only the `create`... | Implement the Python class `PortabilityResourceViewSet` described below.
Class description:
Viewset for the API of the portability request object.
Method signatures and docstrings:
- def get_permissions(self): Manage permissions for built-in DRF methods. Default to the ViewSet's default permissions. Only the `create`... | f767f1bdc12c9712f26ea17cb8b19f536389f0ed | <|skeleton|>
class PortabilityResourceViewSet:
"""Viewset for the API of the portability request object."""
def get_permissions(self):
"""Manage permissions for built-in DRF methods. Default to the ViewSet's default permissions. Only the `create` view is available from LTI."""
<|body_0|>
d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PortabilityResourceViewSet:
"""Viewset for the API of the portability request object."""
def get_permissions(self):
"""Manage permissions for built-in DRF methods. Default to the ViewSet's default permissions. Only the `create` view is available from LTI."""
if self.action in ['create']:
... | the_stack_v2_python_sparse | src/backend/marsha/core/api/portability_request.py | openfun/marsha | train | 92 |
f045da5bd573489fde2068648c396371ed07aef0 | [
"myDeck = deck.Deck()\ncard1 = myDeck.deal_card()\ncard2 = myDeck.deal_card()\nmyPerson = person.Person(card1, card2)\nself.assertEqual(len(myPerson), 2)\nself.assertEqual(myPerson.get_total(), card1.get_value() + card2.get_value())",
"myDeck = deck.Deck()\ncard1 = myDeck.deal_card()\ncard2 = myDeck.deal_card()\n... | <|body_start_0|>
myDeck = deck.Deck()
card1 = myDeck.deal_card()
card2 = myDeck.deal_card()
myPerson = person.Person(card1, card2)
self.assertEqual(len(myPerson), 2)
self.assertEqual(myPerson.get_total(), card1.get_value() + card2.get_value())
<|end_body_0|>
<|body_start... | TestPerson | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPerson:
def test_one(self):
"""Testing the constructor, the len, and the total"""
<|body_0|>
def test_two(self):
"""Testing the add card function"""
<|body_1|>
def test_three(self):
"""Testing the num_aces function"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus_train_066375 | 1,998 | no_license | [
{
"docstring": "Testing the constructor, the len, and the total",
"name": "test_one",
"signature": "def test_one(self)"
},
{
"docstring": "Testing the add card function",
"name": "test_two",
"signature": "def test_two(self)"
},
{
"docstring": "Testing the num_aces function",
... | 4 | stack_v2_sparse_classes_30k_train_018811 | Implement the Python class `TestPerson` described below.
Class description:
Implement the TestPerson class.
Method signatures and docstrings:
- def test_one(self): Testing the constructor, the len, and the total
- def test_two(self): Testing the add card function
- def test_three(self): Testing the num_aces function
... | Implement the Python class `TestPerson` described below.
Class description:
Implement the TestPerson class.
Method signatures and docstrings:
- def test_one(self): Testing the constructor, the len, and the total
- def test_two(self): Testing the add card function
- def test_three(self): Testing the num_aces function
... | 86146cf124c21e4d74e1dac561321395e6555ecc | <|skeleton|>
class TestPerson:
def test_one(self):
"""Testing the constructor, the len, and the total"""
<|body_0|>
def test_two(self):
"""Testing the add card function"""
<|body_1|>
def test_three(self):
"""Testing the num_aces function"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestPerson:
def test_one(self):
"""Testing the constructor, the len, and the total"""
myDeck = deck.Deck()
card1 = myDeck.deal_card()
card2 = myDeck.deal_card()
myPerson = person.Person(card1, card2)
self.assertEqual(len(myPerson), 2)
self.assertEqual(my... | the_stack_v2_python_sparse | test_person.py | alexz12948/BlackJack | train | 0 | |
7c9f26b64575908a953b53c21e95299b8a3fc8cd | [
"super().__init__()\nself._fixed_length_left = fixed_length_left\nself._fixed_length_right = fixed_length_right\nself._fixed_length_word = fixed_length_word\nself._left_fixedlength_unit = units.FixedLength(self._fixed_length_left, pad_value='0', pad_mode='post')\nself._right_fixedlength_unit = units.FixedLength(sel... | <|body_start_0|>
super().__init__()
self._fixed_length_left = fixed_length_left
self._fixed_length_right = fixed_length_right
self._fixed_length_word = fixed_length_word
self._left_fixedlength_unit = units.FixedLength(self._fixed_length_left, pad_value='0', pad_mode='post')
... | DIIN Model preprocessor. | DIINPreprocessor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DIINPreprocessor:
"""DIIN Model preprocessor."""
def __init__(self, fixed_length_left: int=10, fixed_length_right: int=10, fixed_length_word: int=5):
"""DIIN Model preprocessor. :param fixed_length_left: Integer, maximize length of :attr:'left' in the data_pack. :param fixed_length_r... | stack_v2_sparse_classes_75kplus_train_066376 | 6,300 | permissive | [
{
"docstring": "DIIN Model preprocessor. :param fixed_length_left: Integer, maximize length of :attr:'left' in the data_pack. :param fixed_length_right: Integer, maximize length of :attr:'right' in the data_pack. :param fixed_length_word: Integer, maximize length of each word. Example: >>> import matchzoo as mz... | 3 | stack_v2_sparse_classes_30k_train_009103 | Implement the Python class `DIINPreprocessor` described below.
Class description:
DIIN Model preprocessor.
Method signatures and docstrings:
- def __init__(self, fixed_length_left: int=10, fixed_length_right: int=10, fixed_length_word: int=5): DIIN Model preprocessor. :param fixed_length_left: Integer, maximize lengt... | Implement the Python class `DIINPreprocessor` described below.
Class description:
DIIN Model preprocessor.
Method signatures and docstrings:
- def __init__(self, fixed_length_left: int=10, fixed_length_right: int=10, fixed_length_word: int=5): DIIN Model preprocessor. :param fixed_length_left: Integer, maximize lengt... | 1f763062c6cc861e93ccdba23d0f1f0171f74145 | <|skeleton|>
class DIINPreprocessor:
"""DIIN Model preprocessor."""
def __init__(self, fixed_length_left: int=10, fixed_length_right: int=10, fixed_length_word: int=5):
"""DIIN Model preprocessor. :param fixed_length_left: Integer, maximize length of :attr:'left' in the data_pack. :param fixed_length_r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DIINPreprocessor:
"""DIIN Model preprocessor."""
def __init__(self, fixed_length_left: int=10, fixed_length_right: int=10, fixed_length_word: int=5):
"""DIIN Model preprocessor. :param fixed_length_left: Integer, maximize length of :attr:'left' in the data_pack. :param fixed_length_right: Integer... | the_stack_v2_python_sparse | matchzoo/preprocessors/diin_preprocessor.py | JRetza/MatchZoo | train | 1 |
bdc9d59c298368ef10233da5a2fa0a0b51ffd7a9 | [
"headers = case.get('headers')\nmethod = case.get('method')\ndata = Context().re_replace(case['data'])\nurl = config.get('api', 'pre_url') + case.get('url')\nlogger.info(f\"用例--{case['title']}请求url:{url}\")\nlogger.info(f\"用例--{case['title']}请求数据:{data}\")\nif not case.get('skip'):\n if method.lower() == 'get':\... | <|body_start_0|>
headers = case.get('headers')
method = case.get('method')
data = Context().re_replace(case['data'])
url = config.get('api', 'pre_url') + case.get('url')
logger.info(f"用例--{case['title']}请求url:{url}")
logger.info(f"用例--{case['title']}请求数据:{data}")
... | HttpCookies | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HttpCookies:
def http_request(case):
"""request请求通用模板,可根据实际项目进行调整。verify写死为true了。"""
<|body_0|>
def actual_json(actual, jsons):
"""actual:列表格式,存放比对的字段key名 jsons:实际的返回值"""
<|body_1|>
def assert_res(self, expected, status_code, case, response, excel, row, ... | stack_v2_sparse_classes_75kplus_train_066377 | 3,591 | no_license | [
{
"docstring": "request请求通用模板,可根据实际项目进行调整。verify写死为true了。",
"name": "http_request",
"signature": "def http_request(case)"
},
{
"docstring": "actual:列表格式,存放比对的字段key名 jsons:实际的返回值",
"name": "actual_json",
"signature": "def actual_json(actual, jsons)"
},
{
"docstring": "断言方法的封装",
... | 3 | null | Implement the Python class `HttpCookies` described below.
Class description:
Implement the HttpCookies class.
Method signatures and docstrings:
- def http_request(case): request请求通用模板,可根据实际项目进行调整。verify写死为true了。
- def actual_json(actual, jsons): actual:列表格式,存放比对的字段key名 jsons:实际的返回值
- def assert_res(self, expected, st... | Implement the Python class `HttpCookies` described below.
Class description:
Implement the HttpCookies class.
Method signatures and docstrings:
- def http_request(case): request请求通用模板,可根据实际项目进行调整。verify写死为true了。
- def actual_json(actual, jsons): actual:列表格式,存放比对的字段key名 jsons:实际的返回值
- def assert_res(self, expected, st... | 683391adf03a4848c53bbe09eab972ad8c702b1b | <|skeleton|>
class HttpCookies:
def http_request(case):
"""request请求通用模板,可根据实际项目进行调整。verify写死为true了。"""
<|body_0|>
def actual_json(actual, jsons):
"""actual:列表格式,存放比对的字段key名 jsons:实际的返回值"""
<|body_1|>
def assert_res(self, expected, status_code, case, response, excel, row, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HttpCookies:
def http_request(case):
"""request请求通用模板,可根据实际项目进行调整。verify写死为true了。"""
headers = case.get('headers')
method = case.get('method')
data = Context().re_replace(case['data'])
url = config.get('api', 'pre_url') + case.get('url')
logger.info(f"用例--{case[... | the_stack_v2_python_sparse | api_pytest/common/do_request.py | gehongming/kuangjia | train | 0 | |
506c9e187e8a68aa4848d9d6899080b388210d83 | [
"if not message:\n message = _l('The email address already is in use.')\nself.message = message",
"email = field.data\nif not email:\n return\nuser = User.load_from_email(email)\nif user and user != current_user:\n raise ValidationError(self.message)"
] | <|body_start_0|>
if not message:
message = _l('The email address already is in use.')
self.message = message
<|end_body_0|>
<|body_start_1|>
email = field.data
if not email:
return
user = User.load_from_email(email)
if user and user != current_use... | A WTForms validator to verify that an entered email address is not yet in use by a user other than the current one. | UniqueEmail | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UniqueEmail:
"""A WTForms validator to verify that an entered email address is not yet in use by a user other than the current one."""
def __init__(self, message: Optional[str]=None) -> None:
""":param message: The error message shown to the user if the validation fails."""
<... | stack_v2_sparse_classes_75kplus_train_066378 | 6,554 | permissive | [
{
"docstring": ":param message: The error message shown to the user if the validation fails.",
"name": "__init__",
"signature": "def __init__(self, message: Optional[str]=None) -> None"
},
{
"docstring": "Execute the validator. :param form: The form to which the field belongs. :param field: The ... | 2 | stack_v2_sparse_classes_30k_train_051668 | Implement the Python class `UniqueEmail` described below.
Class description:
A WTForms validator to verify that an entered email address is not yet in use by a user other than the current one.
Method signatures and docstrings:
- def __init__(self, message: Optional[str]=None) -> None: :param message: The error messag... | Implement the Python class `UniqueEmail` described below.
Class description:
A WTForms validator to verify that an entered email address is not yet in use by a user other than the current one.
Method signatures and docstrings:
- def __init__(self, message: Optional[str]=None) -> None: :param message: The error messag... | 119946cead727ef68b5ecea339990d982c006391 | <|skeleton|>
class UniqueEmail:
"""A WTForms validator to verify that an entered email address is not yet in use by a user other than the current one."""
def __init__(self, message: Optional[str]=None) -> None:
""":param message: The error message shown to the user if the validation fails."""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UniqueEmail:
"""A WTForms validator to verify that an entered email address is not yet in use by a user other than the current one."""
def __init__(self, message: Optional[str]=None) -> None:
""":param message: The error message shown to the user if the validation fails."""
if not message... | the_stack_v2_python_sparse | app/views/userprofile/forms.py | BMeu/Aerarium | train | 0 |
1a227d784207c1553575d2baed1405a128938f53 | [
"if isinstance(cls, six.class_types):\n init = cls.__init__\n\n def wrapped(*args, **kwargs):\n try:\n warp_self = args[0]\n warp_self.df = None\n init(*args, **kwargs)\n symbol = args[1]\n start = args[2]\n self._gen_warp_df(warp_self, ... | <|body_start_0|>
if isinstance(cls, six.class_types):
init = cls.__init__
def wrapped(*args, **kwargs):
try:
warp_self = args[0]
warp_self.df = None
init(*args, **kwargs)
symbol = args[1]
... | 做为类装饰器封装替换解析数据统一操作,装饰替换init | HSDataParseWrap | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HSDataParseWrap:
"""做为类装饰器封装替换解析数据统一操作,装饰替换init"""
def __call__(self, cls):
"""只做为数据源解析类的装饰器,统一封装通用的数据解析规范及流程"""
<|body_0|>
def _gen_warp_df(self, warp_self, symbol, start):
"""封装通用的数据解析规范及流程 :param warp_self: 被封装类init中使用的self对象 :param symbol: 请求的symbol str对象 :re... | stack_v2_sparse_classes_75kplus_train_066379 | 9,678 | permissive | [
{
"docstring": "只做为数据源解析类的装饰器,统一封装通用的数据解析规范及流程",
"name": "__call__",
"signature": "def __call__(self, cls)"
},
{
"docstring": "封装通用的数据解析规范及流程 :param warp_self: 被封装类init中使用的self对象 :param symbol: 请求的symbol str对象 :return:",
"name": "_gen_warp_df",
"signature": "def _gen_warp_df(self, warp_s... | 2 | stack_v2_sparse_classes_30k_train_023295 | Implement the Python class `HSDataParseWrap` described below.
Class description:
做为类装饰器封装替换解析数据统一操作,装饰替换init
Method signatures and docstrings:
- def __call__(self, cls): 只做为数据源解析类的装饰器,统一封装通用的数据解析规范及流程
- def _gen_warp_df(self, warp_self, symbol, start): 封装通用的数据解析规范及流程 :param warp_self: 被封装类init中使用的self对象 :param symbol... | Implement the Python class `HSDataParseWrap` described below.
Class description:
做为类装饰器封装替换解析数据统一操作,装饰替换init
Method signatures and docstrings:
- def __call__(self, cls): 只做为数据源解析类的装饰器,统一封装通用的数据解析规范及流程
- def _gen_warp_df(self, warp_self, symbol, start): 封装通用的数据解析规范及流程 :param warp_self: 被封装类init中使用的self对象 :param symbol... | f8841331022e8844537a5c5b08d047e2cc328856 | <|skeleton|>
class HSDataParseWrap:
"""做为类装饰器封装替换解析数据统一操作,装饰替换init"""
def __call__(self, cls):
"""只做为数据源解析类的装饰器,统一封装通用的数据解析规范及流程"""
<|body_0|>
def _gen_warp_df(self, warp_self, symbol, start):
"""封装通用的数据解析规范及流程 :param warp_self: 被封装类init中使用的self对象 :param symbol: 请求的symbol str对象 :re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HSDataParseWrap:
"""做为类装饰器封装替换解析数据统一操作,装饰替换init"""
def __call__(self, cls):
"""只做为数据源解析类的装饰器,统一封装通用的数据解析规范及流程"""
if isinstance(cls, six.class_types):
init = cls.__init__
def wrapped(*args, **kwargs):
try:
warp_self = args[0]
... | the_stack_v2_python_sparse | hsstock/service/sn_service.py | hsstock/hsstock | train | 2 |
a741dfcd258ff21e4a0b2bc8f2f3db547f731910 | [
"assert 'LYA_EMU_REPO' in os.environ, 'export LYA_EMU_REPO'\nrepo = os.environ['LYA_EMU_REPO']\nbasedir = repo + '/p1d_data//data_files/Chabanier2019/'\nz, k, Pk, cov = self._setup_from_file(basedir, add_syst)\nif zmin or zmax:\n z, k, Pk, cov = base_p1d_data._drop_zbins(z, k, Pk, cov, zmin, zmax)\nbase_p1d_data... | <|body_start_0|>
assert 'LYA_EMU_REPO' in os.environ, 'export LYA_EMU_REPO'
repo = os.environ['LYA_EMU_REPO']
basedir = repo + '/p1d_data//data_files/Chabanier2019/'
z, k, Pk, cov = self._setup_from_file(basedir, add_syst)
if zmin or zmax:
z, k, Pk, cov = base_p1d_dat... | Class containing P1D from Chabanier et al. (2019). | P1D_Chabanier2019 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class P1D_Chabanier2019:
"""Class containing P1D from Chabanier et al. (2019)."""
def __init__(self, zmin=None, zmax=None, add_syst=True):
"""Read measured P1D from Chabanier et al. (2019)."""
<|body_0|>
def _setup_from_file(self, basedir, add_syst):
"""Reconstruct cov... | stack_v2_sparse_classes_75kplus_train_066380 | 2,339 | no_license | [
{
"docstring": "Read measured P1D from Chabanier et al. (2019).",
"name": "__init__",
"signature": "def __init__(self, zmin=None, zmax=None, add_syst=True)"
},
{
"docstring": "Reconstruct covariance matrix from files.",
"name": "_setup_from_file",
"signature": "def _setup_from_file(self,... | 2 | stack_v2_sparse_classes_30k_train_021354 | Implement the Python class `P1D_Chabanier2019` described below.
Class description:
Class containing P1D from Chabanier et al. (2019).
Method signatures and docstrings:
- def __init__(self, zmin=None, zmax=None, add_syst=True): Read measured P1D from Chabanier et al. (2019).
- def _setup_from_file(self, basedir, add_s... | Implement the Python class `P1D_Chabanier2019` described below.
Class description:
Class containing P1D from Chabanier et al. (2019).
Method signatures and docstrings:
- def __init__(self, zmin=None, zmax=None, add_syst=True): Read measured P1D from Chabanier et al. (2019).
- def _setup_from_file(self, basedir, add_s... | 54658ffce6b69005ec2509074d1eafa9e4625372 | <|skeleton|>
class P1D_Chabanier2019:
"""Class containing P1D from Chabanier et al. (2019)."""
def __init__(self, zmin=None, zmax=None, add_syst=True):
"""Read measured P1D from Chabanier et al. (2019)."""
<|body_0|>
def _setup_from_file(self, basedir, add_syst):
"""Reconstruct cov... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class P1D_Chabanier2019:
"""Class containing P1D from Chabanier et al. (2019)."""
def __init__(self, zmin=None, zmax=None, add_syst=True):
"""Read measured P1D from Chabanier et al. (2019)."""
assert 'LYA_EMU_REPO' in os.environ, 'export LYA_EMU_REPO'
repo = os.environ['LYA_EMU_REPO']
... | the_stack_v2_python_sparse | p1d_data/py/data_Chabanier2019.py | diveshjain-phy/LyaCosmoParams | train | 0 |
46c0720e72cbbf17e7ea125624a4616f7652227e | [
"self.osutils = osutils\nif npm_exe is None:\n if osutils.is_windows():\n npm_exe = 'npm.cmd'\n else:\n npm_exe = 'npm'\nself.npm_exe = npm_exe",
"if not isinstance(args, list):\n raise ValueError('args must be a list')\nif not args:\n raise ValueError('requires at least one arg')\ninvok... | <|body_start_0|>
self.osutils = osutils
if npm_exe is None:
if osutils.is_windows():
npm_exe = 'npm.cmd'
else:
npm_exe = 'npm'
self.npm_exe = npm_exe
<|end_body_0|>
<|body_start_1|>
if not isinstance(args, list):
raise ... | Wrapper around the NPM command line utility, making it easy to consume execution results. | SubprocessNpm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubprocessNpm:
"""Wrapper around the NPM command line utility, making it easy to consume execution results."""
def __init__(self, osutils, npm_exe=None):
""":type osutils: aws_lambda_builders.workflows.nodejs_npm.utils.OSUtils :param osutils: An instance of OS Utilities for file mani... | stack_v2_sparse_classes_75kplus_train_066381 | 2,383 | permissive | [
{
"docstring": ":type osutils: aws_lambda_builders.workflows.nodejs_npm.utils.OSUtils :param osutils: An instance of OS Utilities for file manipulation :type npm_exe: str :param npm_exe: Path to the NPM binary. If not set, the default executable path npm will be used",
"name": "__init__",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_040653 | Implement the Python class `SubprocessNpm` described below.
Class description:
Wrapper around the NPM command line utility, making it easy to consume execution results.
Method signatures and docstrings:
- def __init__(self, osutils, npm_exe=None): :type osutils: aws_lambda_builders.workflows.nodejs_npm.utils.OSUtils ... | Implement the Python class `SubprocessNpm` described below.
Class description:
Wrapper around the NPM command line utility, making it easy to consume execution results.
Method signatures and docstrings:
- def __init__(self, osutils, npm_exe=None): :type osutils: aws_lambda_builders.workflows.nodejs_npm.utils.OSUtils ... | c90c9bc8953aa684a23a3b438c7a71cc41cce809 | <|skeleton|>
class SubprocessNpm:
"""Wrapper around the NPM command line utility, making it easy to consume execution results."""
def __init__(self, osutils, npm_exe=None):
""":type osutils: aws_lambda_builders.workflows.nodejs_npm.utils.OSUtils :param osutils: An instance of OS Utilities for file mani... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SubprocessNpm:
"""Wrapper around the NPM command line utility, making it easy to consume execution results."""
def __init__(self, osutils, npm_exe=None):
""":type osutils: aws_lambda_builders.workflows.nodejs_npm.utils.OSUtils :param osutils: An instance of OS Utilities for file manipulation :typ... | the_stack_v2_python_sparse | aws_lambda_builders/workflows/nodejs_npm/npm.py | aws/aws-lambda-builders | train | 144 |
1f1eb53ff2be75d30c1ed9ff5eca038b4785926f | [
"if field_names is None:\n assert not as_array\n return super(DefaultSerialize, cls).object2dict(obj, **kwargs)\nelse:\n out = serialize.list2dict(obj, names=field_names)\nreturn out",
"if as_array:\n assert field_names is not None\n out = serialize.list2numpy(obj, names=field_names)\nelse:\n ou... | <|body_start_0|>
if field_names is None:
assert not as_array
return super(DefaultSerialize, cls).object2dict(obj, **kwargs)
else:
out = serialize.list2dict(obj, names=field_names)
return out
<|end_body_0|>
<|body_start_1|>
if as_array:
ass... | Default class for serializing/deserializing a python object into/from a bytes message. Args: **kwargs: Additional keyword args are passed to the parent class. | DefaultSerialize | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefaultSerialize:
"""Default class for serializing/deserializing a python object into/from a bytes message. Args: **kwargs: Additional keyword args are passed to the parent class."""
def object2dict(cls, obj, as_array=False, field_names=None, **kwargs):
"""Convert a message object in... | stack_v2_sparse_classes_75kplus_train_066382 | 4,911 | permissive | [
{
"docstring": "Convert a message object into a dictionary. Args: obj (object): Object that would be serialized by this class and should be returned in a dictionary form. as_array (bool, optional): If True, the objects in the list are complete columns in a table and as_format is set to True. Defaults to False. ... | 5 | stack_v2_sparse_classes_30k_train_002758 | Implement the Python class `DefaultSerialize` described below.
Class description:
Default class for serializing/deserializing a python object into/from a bytes message. Args: **kwargs: Additional keyword args are passed to the parent class.
Method signatures and docstrings:
- def object2dict(cls, obj, as_array=False,... | Implement the Python class `DefaultSerialize` described below.
Class description:
Default class for serializing/deserializing a python object into/from a bytes message. Args: **kwargs: Additional keyword args are passed to the parent class.
Method signatures and docstrings:
- def object2dict(cls, obj, as_array=False,... | dcc4d75a4d2c6aaa7e50e75095a16df1df6b2b0a | <|skeleton|>
class DefaultSerialize:
"""Default class for serializing/deserializing a python object into/from a bytes message. Args: **kwargs: Additional keyword args are passed to the parent class."""
def object2dict(cls, obj, as_array=False, field_names=None, **kwargs):
"""Convert a message object in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DefaultSerialize:
"""Default class for serializing/deserializing a python object into/from a bytes message. Args: **kwargs: Additional keyword args are passed to the parent class."""
def object2dict(cls, obj, as_array=False, field_names=None, **kwargs):
"""Convert a message object into a dictiona... | the_stack_v2_python_sparse | yggdrasil/serialize/DefaultSerialize.py | leighmatth/yggdrasil | train | 0 |
5c2a3b25b02a161bfab58229dfe2a003b2c9cc3f | [
"inv.LOGGER.info('--- Start Test add_furniture() ---')\nif os.path.exists('rented_items.csv'):\n os.remove('rented_items.csv')\ninv.add_furniture('rented_items.csv', 'Elisa Miles', 'LR04', 'Leather Sofa', 25.0)\ninv.add_furniture('rented_items.csv', 'Edward Data', 'KT78', 'Kitchen Table', 10.0)\ninv.add_furnitur... | <|body_start_0|>
inv.LOGGER.info('--- Start Test add_furniture() ---')
if os.path.exists('rented_items.csv'):
os.remove('rented_items.csv')
inv.add_furniture('rented_items.csv', 'Elisa Miles', 'LR04', 'Leather Sofa', 25.0)
inv.add_furniture('rented_items.csv', 'Edward Data', ... | This class defines unit test fuctions for invetory.py | inventory_Tests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class inventory_Tests:
"""This class defines unit test fuctions for invetory.py"""
def test_add_furniture(self):
"""Test add_furniture function"""
<|body_0|>
def test_single_customer(self):
"""Test single_customer function"""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_75kplus_train_066383 | 1,728 | no_license | [
{
"docstring": "Test add_furniture function",
"name": "test_add_furniture",
"signature": "def test_add_furniture(self)"
},
{
"docstring": "Test single_customer function",
"name": "test_single_customer",
"signature": "def test_single_customer(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_036968 | Implement the Python class `inventory_Tests` described below.
Class description:
This class defines unit test fuctions for invetory.py
Method signatures and docstrings:
- def test_add_furniture(self): Test add_furniture function
- def test_single_customer(self): Test single_customer function | Implement the Python class `inventory_Tests` described below.
Class description:
This class defines unit test fuctions for invetory.py
Method signatures and docstrings:
- def test_add_furniture(self): Test add_furniture function
- def test_single_customer(self): Test single_customer function
<|skeleton|>
class inven... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class inventory_Tests:
"""This class defines unit test fuctions for invetory.py"""
def test_add_furniture(self):
"""Test add_furniture function"""
<|body_0|>
def test_single_customer(self):
"""Test single_customer function"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class inventory_Tests:
"""This class defines unit test fuctions for invetory.py"""
def test_add_furniture(self):
"""Test add_furniture function"""
inv.LOGGER.info('--- Start Test add_furniture() ---')
if os.path.exists('rented_items.csv'):
os.remove('rented_items.csv')
... | the_stack_v2_python_sparse | students/zhen_yang/lesson08/assignment/test_inventory.py | JavaRod/SP_Python220B_2019 | train | 1 |
9b2599cb6e086ba0809a4bbee36bc1e377f7d798 | [
"super().__init__(basis_gates, default_values)\nself._link_parameters = link_parameters\ndur = Parameter('duration')\nsigma = Parameter('σ')\n\ndef _beta(use_drag):\n return Parameter('β') if use_drag else None\nx_amp, x_beta = (Parameter('amp'), _beta(use_drag))\nif self._link_parameters:\n y_amp, y_beta = (... | <|body_start_0|>
super().__init__(basis_gates, default_values)
self._link_parameters = link_parameters
dur = Parameter('duration')
sigma = Parameter('σ')
def _beta(use_drag):
return Parameter('β') if use_drag else None
x_amp, x_beta = (Parameter('amp'), _beta... | A library of gates for fixed-frequency superconducting qubit architectures. Note that for now this library supports single-qubit gates and will be extended in the future. | FixedFrequencyTransmon | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FixedFrequencyTransmon:
"""A library of gates for fixed-frequency superconducting qubit architectures. Note that for now this library supports single-qubit gates and will be extended in the future."""
def __init__(self, basis_gates: Optional[List[str]]=None, default_values: Optional[Dict]=No... | stack_v2_sparse_classes_75kplus_train_066384 | 8,121 | permissive | [
{
"docstring": "Setup the schedules. Args: basis_gates: The basis gates to generate. default_values: Default values for the parameters this dictionary can contain the following keys: \"duration\", \"amp\", \"β\", and \"σ\". If \"σ\" is not provided this library will take one fourth of the pulse duration as defa... | 3 | stack_v2_sparse_classes_30k_train_023646 | Implement the Python class `FixedFrequencyTransmon` described below.
Class description:
A library of gates for fixed-frequency superconducting qubit architectures. Note that for now this library supports single-qubit gates and will be extended in the future.
Method signatures and docstrings:
- def __init__(self, basi... | Implement the Python class `FixedFrequencyTransmon` described below.
Class description:
A library of gates for fixed-frequency superconducting qubit architectures. Note that for now this library supports single-qubit gates and will be extended in the future.
Method signatures and docstrings:
- def __init__(self, basi... | 22b1598b290464e59a12853efa1eb99b1b36513a | <|skeleton|>
class FixedFrequencyTransmon:
"""A library of gates for fixed-frequency superconducting qubit architectures. Note that for now this library supports single-qubit gates and will be extended in the future."""
def __init__(self, basis_gates: Optional[List[str]]=None, default_values: Optional[Dict]=No... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FixedFrequencyTransmon:
"""A library of gates for fixed-frequency superconducting qubit architectures. Note that for now this library supports single-qubit gates and will be extended in the future."""
def __init__(self, basis_gates: Optional[List[str]]=None, default_values: Optional[Dict]=None, use_drag:... | the_stack_v2_python_sparse | qiskit_experiments/calibration_management/basis_gate_library.py | huggingworld/qiskit-experiments | train | 0 |
1df1b56278c425ec874668ae9735f019968614d1 | [
"super(Table, self).__init__(resource_id=table_id, resource_type=resource.ResourceType.TABLE, name=name, display_name=display_name, parent=parent, locations=locations, lifecycle_state=lifecycle_state)\nself.full_name = full_name\nself.data = data",
"table_dict = json.loads(json_string)\ntable_id = table_dict['id'... | <|body_start_0|>
super(Table, self).__init__(resource_id=table_id, resource_type=resource.ResourceType.TABLE, name=name, display_name=display_name, parent=parent, locations=locations, lifecycle_state=lifecycle_state)
self.full_name = full_name
self.data = data
<|end_body_0|>
<|body_start_1|>
... | Table resource. | Table | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Table:
"""Table resource."""
def __init__(self, table_id, full_name=None, data=None, name=None, display_name=None, parent=None, locations=None, lifecycle_state=TableLifecycleState.UNSPECIFIED):
"""Initialize. Args: table_id (int): The table id. full_name (str): The full resource name... | stack_v2_sparse_classes_75kplus_train_066385 | 2,943 | permissive | [
{
"docstring": "Initialize. Args: table_id (int): The table id. full_name (str): The full resource name and ancestry. data (str): Resource representation of the table. name (str): The table's unique GCP name, with the format \"bigquery_tables/{id}\". display_name (str): The table's display name. locations (List... | 2 | null | Implement the Python class `Table` described below.
Class description:
Table resource.
Method signatures and docstrings:
- def __init__(self, table_id, full_name=None, data=None, name=None, display_name=None, parent=None, locations=None, lifecycle_state=TableLifecycleState.UNSPECIFIED): Initialize. Args: table_id (in... | Implement the Python class `Table` described below.
Class description:
Table resource.
Method signatures and docstrings:
- def __init__(self, table_id, full_name=None, data=None, name=None, display_name=None, parent=None, locations=None, lifecycle_state=TableLifecycleState.UNSPECIFIED): Initialize. Args: table_id (in... | d4421afa50a17ed47cbebe942044ebab3720e0f5 | <|skeleton|>
class Table:
"""Table resource."""
def __init__(self, table_id, full_name=None, data=None, name=None, display_name=None, parent=None, locations=None, lifecycle_state=TableLifecycleState.UNSPECIFIED):
"""Initialize. Args: table_id (int): The table id. full_name (str): The full resource name... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Table:
"""Table resource."""
def __init__(self, table_id, full_name=None, data=None, name=None, display_name=None, parent=None, locations=None, lifecycle_state=TableLifecycleState.UNSPECIFIED):
"""Initialize. Args: table_id (int): The table id. full_name (str): The full resource name and ancestry... | the_stack_v2_python_sparse | google/cloud/forseti/common/gcp_type/table.py | kevensen/forseti-security | train | 1 |
9805039ed80b415f06348d2180c36158d26ca0d2 | [
"self.BART_query_rewriter_transform = BART_Query_Rewriter_Transform(checkpoint_path, no_tqdm=True, **kwargs)\nself.query_cleaner_transform = Query_Cleaner_Transform(fields=[('rewritten_query', 'cleaned_rewritten_query')])\nself.cached_generations = {}",
"for sample_obj in tqdm(samples, desc='BART self feeding rew... | <|body_start_0|>
self.BART_query_rewriter_transform = BART_Query_Rewriter_Transform(checkpoint_path, no_tqdm=True, **kwargs)
self.query_cleaner_transform = Query_Cleaner_Transform(fields=[('rewritten_query', 'cleaned_rewritten_query')])
self.cached_generations = {}
<|end_body_0|>
<|body_start_1... | BART_Full_Conversational_Rewriter_Transform | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BART_Full_Conversational_Rewriter_Transform:
def __init__(self, checkpoint_path, **kwargs):
"""This Transform takes a sequence of raw queries and re-writes them to the resolved version fed off itself."""
<|body_0|>
def __call__(self, samples):
"""samples: [dict]: [{'... | stack_v2_sparse_classes_75kplus_train_066386 | 24,876 | no_license | [
{
"docstring": "This Transform takes a sequence of raw queries and re-writes them to the resolved version fed off itself.",
"name": "__init__",
"signature": "def __init__(self, checkpoint_path, **kwargs)"
},
{
"docstring": "samples: [dict]: [{'unresolved_query':\"third raw query\", 'previous_que... | 2 | stack_v2_sparse_classes_30k_train_024754 | Implement the Python class `BART_Full_Conversational_Rewriter_Transform` described below.
Class description:
Implement the BART_Full_Conversational_Rewriter_Transform class.
Method signatures and docstrings:
- def __init__(self, checkpoint_path, **kwargs): This Transform takes a sequence of raw queries and re-writes ... | Implement the Python class `BART_Full_Conversational_Rewriter_Transform` described below.
Class description:
Implement the BART_Full_Conversational_Rewriter_Transform class.
Method signatures and docstrings:
- def __init__(self, checkpoint_path, **kwargs): This Transform takes a sequence of raw queries and re-writes ... | 92dd4d41ad6f2be5b5c4e296e2a355bb14b9a1db | <|skeleton|>
class BART_Full_Conversational_Rewriter_Transform:
def __init__(self, checkpoint_path, **kwargs):
"""This Transform takes a sequence of raw queries and re-writes them to the resolved version fed off itself."""
<|body_0|>
def __call__(self, samples):
"""samples: [dict]: [{'... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BART_Full_Conversational_Rewriter_Transform:
def __init__(self, checkpoint_path, **kwargs):
"""This Transform takes a sequence of raw queries and re-writes them to the resolved version fed off itself."""
self.BART_query_rewriter_transform = BART_Query_Rewriter_Transform(checkpoint_path, no_tqd... | the_stack_v2_python_sparse | notebooks/src/models_and_transforms/complex_transforms.py | carlos-gemmell/Glasgow-NLP | train | 0 | |
e20f5a7bd4ee82fefbd4779b6ba2a5672746357e | [
"res, curr = (0, 0)\nN = len(heights)\nfor i in range(N):\n mini = heights[i]\n curr = mini * 1\n res = max(res, curr)\n for j in range(i + 1, N):\n mini = min(mini, heights[j])\n curr = mini * (j - i + 1)\n res = max(res, curr)\nreturn res",
"res, curr = (0, 0)\nN = len(heights)\... | <|body_start_0|>
res, curr = (0, 0)
N = len(heights)
for i in range(N):
mini = heights[i]
curr = mini * 1
res = max(res, curr)
for j in range(i + 1, N):
mini = min(mini, heights[j])
curr = mini * (j - i + 1)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
"""Primitive solution that iterates over the heights and all possible combinations, returns the maximum size."""
<|body_0|>
def largestRectangleArea2(self, heights: List[int]) -> int:
"""For each ba... | stack_v2_sparse_classes_75kplus_train_066387 | 2,284 | no_license | [
{
"docstring": "Primitive solution that iterates over the heights and all possible combinations, returns the maximum size.",
"name": "largestRectangleArea",
"signature": "def largestRectangleArea(self, heights: List[int]) -> int"
},
{
"docstring": "For each bar, expands from left and right to ge... | 3 | stack_v2_sparse_classes_30k_train_023083 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestRectangleArea(self, heights: List[int]) -> int: Primitive solution that iterates over the heights and all possible combinations, returns the maximum size.
- def larges... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestRectangleArea(self, heights: List[int]) -> int: Primitive solution that iterates over the heights and all possible combinations, returns the maximum size.
- def larges... | 9a0e41d2d718803eb297430995e464fcab472a55 | <|skeleton|>
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
"""Primitive solution that iterates over the heights and all possible combinations, returns the maximum size."""
<|body_0|>
def largestRectangleArea2(self, heights: List[int]) -> int:
"""For each ba... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
"""Primitive solution that iterates over the heights and all possible combinations, returns the maximum size."""
res, curr = (0, 0)
N = len(heights)
for i in range(N):
mini = heights[i]
... | the_stack_v2_python_sparse | leetcode/84.py | evinpinar/competitive_python | train | 0 | |
250a163c8a9b592188c2ceec410c46df7e149746 | [
"I = IngestImages(self.testdir, self.testdir + '../output')\nwith patch('os.rename') as mock:\n I.ingest_image(self.testmeta)",
"I = IngestImages(self.testdir, self.testdir + '../output')\nwith patch('os.rename') as mock:\n I.ingest_all()"
] | <|body_start_0|>
I = IngestImages(self.testdir, self.testdir + '../output')
with patch('os.rename') as mock:
I.ingest_image(self.testmeta)
<|end_body_0|>
<|body_start_1|>
I = IngestImages(self.testdir, self.testdir + '../output')
with patch('os.rename') as mock:
... | Functional tests running the ingestion routines as the user will | FunctionalTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FunctionalTests:
"""Functional tests running the ingestion routines as the user will"""
def test_ingest_single_image(self):
"""Ingest a single image, from the specified metadata file"""
<|body_0|>
def test_ingest_all_images(self):
"""Ingest all the images in the ... | stack_v2_sparse_classes_75kplus_train_066388 | 8,346 | no_license | [
{
"docstring": "Ingest a single image, from the specified metadata file",
"name": "test_ingest_single_image",
"signature": "def test_ingest_single_image(self)"
},
{
"docstring": "Ingest all the images in the input directory",
"name": "test_ingest_all_images",
"signature": "def test_inges... | 2 | stack_v2_sparse_classes_30k_train_024251 | Implement the Python class `FunctionalTests` described below.
Class description:
Functional tests running the ingestion routines as the user will
Method signatures and docstrings:
- def test_ingest_single_image(self): Ingest a single image, from the specified metadata file
- def test_ingest_all_images(self): Ingest a... | Implement the Python class `FunctionalTests` described below.
Class description:
Functional tests running the ingestion routines as the user will
Method signatures and docstrings:
- def test_ingest_single_image(self): Ingest a single image, from the specified metadata file
- def test_ingest_all_images(self): Ingest a... | c39737be682c5f9ee975f3336875a69241582665 | <|skeleton|>
class FunctionalTests:
"""Functional tests running the ingestion routines as the user will"""
def test_ingest_single_image(self):
"""Ingest a single image, from the specified metadata file"""
<|body_0|>
def test_ingest_all_images(self):
"""Ingest all the images in the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FunctionalTests:
"""Functional tests running the ingestion routines as the user will"""
def test_ingest_single_image(self):
"""Ingest a single image, from the specified metadata file"""
I = IngestImages(self.testdir, self.testdir + '../output')
with patch('os.rename') as mock:
... | the_stack_v2_python_sparse | toucan/ingest_data/tests_images.py | tlebras/TOUCAN-1 | train | 0 |
13faae550a4f408fcabffbe45a858c3803a2f863 | [
"title = request.POST['title']\nnew_properties = json.loads(request.POST.get('newProperties', '[]'))\ntemplate = mall_models.ProductPropertyTemplate.objects.create(owner=request.manager, name=title)\nfor property in new_properties:\n if property['id'] < 0:\n mall_models.TemplateProperty.objects.create(own... | <|body_start_0|>
title = request.POST['title']
new_properties = json.loads(request.POST.get('newProperties', '[]'))
template = mall_models.ProductPropertyTemplate.objects.create(owner=request.manager, name=title)
for property in new_properties:
if property['id'] < 0:
... | Property | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Property:
def api_put(request):
"""创建属性模板 Args: title: 属性模板标题 newProperties 属性模板中需要新建的property信息的json字符串 Example: { 'title': 'aaa', 'newProperties':[ { id: -1, //id=-1, 代表需要新建的属性 name: "属性1", value: "属性1的描述" }, ... ] }"""
<|body_0|>
def api_post(request):
"""更新属性模板 A... | stack_v2_sparse_classes_75kplus_train_066389 | 5,912 | no_license | [
{
"docstring": "创建属性模板 Args: title: 属性模板标题 newProperties 属性模板中需要新建的property信息的json字符串 Example: { 'title': 'aaa', 'newProperties':[ { id: -1, //id=-1, 代表需要新建的属性 name: \"属性1\", value: \"属性1的描述\" }, ... ] }",
"name": "api_put",
"signature": "def api_put(request)"
},
{
"docstring": "更新属性模板 Args: id:... | 3 | stack_v2_sparse_classes_30k_test_002407 | Implement the Python class `Property` described below.
Class description:
Implement the Property class.
Method signatures and docstrings:
- def api_put(request): 创建属性模板 Args: title: 属性模板标题 newProperties 属性模板中需要新建的property信息的json字符串 Example: { 'title': 'aaa', 'newProperties':[ { id: -1, //id=-1, 代表需要新建的属性 name: "属性1",... | Implement the Python class `Property` described below.
Class description:
Implement the Property class.
Method signatures and docstrings:
- def api_put(request): 创建属性模板 Args: title: 属性模板标题 newProperties 属性模板中需要新建的property信息的json字符串 Example: { 'title': 'aaa', 'newProperties':[ { id: -1, //id=-1, 代表需要新建的属性 name: "属性1",... | 8b2f7befe92841bcc35e0e60cac5958ef3f3af54 | <|skeleton|>
class Property:
def api_put(request):
"""创建属性模板 Args: title: 属性模板标题 newProperties 属性模板中需要新建的property信息的json字符串 Example: { 'title': 'aaa', 'newProperties':[ { id: -1, //id=-1, 代表需要新建的属性 name: "属性1", value: "属性1的描述" }, ... ] }"""
<|body_0|>
def api_post(request):
"""更新属性模板 A... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Property:
def api_put(request):
"""创建属性模板 Args: title: 属性模板标题 newProperties 属性模板中需要新建的property信息的json字符串 Example: { 'title': 'aaa', 'newProperties':[ { id: -1, //id=-1, 代表需要新建的属性 name: "属性1", value: "属性1的描述" }, ... ] }"""
title = request.POST['title']
new_properties = json.loads(reques... | the_stack_v2_python_sparse | weapp/mall/product/properties.py | chengdg/weizoom | train | 1 | |
9d9f42a567cb83f1038af58073ec26e95dbd330b | [
"validated_data = super().to_internal_value(data)\nvalidated_data, non_existing = parse_item_args(validated_data)\nfor k, v in non_existing.items():\n validated_data[f'{k}__name'] = v\n if f'{k}_id' in validated_data:\n del validated_data[f'{k}_id']\nreturn validated_data",
"params_to_create = {}\nre... | <|body_start_0|>
validated_data = super().to_internal_value(data)
validated_data, non_existing = parse_item_args(validated_data)
for k, v in non_existing.items():
validated_data[f'{k}__name'] = v
if f'{k}_id' in validated_data:
del validated_data[f'{k}_id'... | ItemSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ItemSerializer:
def to_internal_value(self, data):
"""Parse item args to get additional plugin, scenario and test_id values non-existing plugin and scenario stored as "*__name" fields, existing will have fk ids such naming makes possible common django queryset filtering (see create_entit... | stack_v2_sparse_classes_75kplus_train_066390 | 13,972 | no_license | [
{
"docstring": "Parse item args to get additional plugin, scenario and test_id values non-existing plugin and scenario stored as \"*__name\" fields, existing will have fk ids such naming makes possible common django queryset filtering (see create_entities in api/collate/import_api.py)",
"name": "to_internal... | 2 | stack_v2_sparse_classes_30k_train_023791 | Implement the Python class `ItemSerializer` described below.
Class description:
Implement the ItemSerializer class.
Method signatures and docstrings:
- def to_internal_value(self, data): Parse item args to get additional plugin, scenario and test_id values non-existing plugin and scenario stored as "*__name" fields, ... | Implement the Python class `ItemSerializer` described below.
Class description:
Implement the ItemSerializer class.
Method signatures and docstrings:
- def to_internal_value(self, data): Parse item args to get additional plugin, scenario and test_id values non-existing plugin and scenario stored as "*__name" fields, ... | f9177abf4fd235ad0aef5bd70ebe6150f1fce7be | <|skeleton|>
class ItemSerializer:
def to_internal_value(self, data):
"""Parse item args to get additional plugin, scenario and test_id values non-existing plugin and scenario stored as "*__name" fields, existing will have fk ids such naming makes possible common django queryset filtering (see create_entit... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ItemSerializer:
def to_internal_value(self, data):
"""Parse item args to get additional plugin, scenario and test_id values non-existing plugin and scenario stored as "*__name" fields, existing will have fk ids such naming makes possible common django queryset filtering (see create_entities in api/col... | the_stack_v2_python_sparse | backend/reporting/api/serializers.py | ChangyuHE/justForTestRespository | train | 0 | |
d38f751649297e87e50c48040e06d148c337cf63 | [
"self._logger_log = logger_log\nself._logger_error = logger_error\nself._waagent_event_adder = waagent_event_adder\nself._status_reporter = status_reporter\nself._ext_name = ext_name\nself._ext_ver = ext_ver",
"memory_leak_msg = 'Suspected mdsd memory leak (Virtual memory usage: {0}MB). Recycling mdsd to self-mit... | <|body_start_0|>
self._logger_log = logger_log
self._logger_error = logger_error
self._waagent_event_adder = waagent_event_adder
self._status_reporter = status_reporter
self._ext_name = ext_name
self._ext_ver = ext_ver
<|end_body_0|>
<|body_start_1|>
memory_leak_... | Various LAD log helper functions encapsulated here, so that we don't have to tag along all the parameters. | LadLogHelper | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LadLogHelper:
"""Various LAD log helper functions encapsulated here, so that we don't have to tag along all the parameters."""
def __init__(self, logger_log, logger_error, waagent_event_adder, status_reporter, ext_name, ext_ver):
"""Constructor :param logger_log: Normal logging funct... | stack_v2_sparse_classes_75kplus_train_066391 | 16,633 | permissive | [
{
"docstring": "Constructor :param logger_log: Normal logging function (e.g., hutil.log) :param logger_error: Error logging function (e.g., hutil.error) :param waagent_event_adder: waagent event add function (waagent.AddExtensionEvent) :param status_reporter: waagent/extension status report function (hutil.do_s... | 5 | null | Implement the Python class `LadLogHelper` described below.
Class description:
Various LAD log helper functions encapsulated here, so that we don't have to tag along all the parameters.
Method signatures and docstrings:
- def __init__(self, logger_log, logger_error, waagent_event_adder, status_reporter, ext_name, ext_... | Implement the Python class `LadLogHelper` described below.
Class description:
Various LAD log helper functions encapsulated here, so that we don't have to tag along all the parameters.
Method signatures and docstrings:
- def __init__(self, logger_log, logger_error, waagent_event_adder, status_reporter, ext_name, ext_... | 3cea1567fc4f4eb5beea9884153e92d70610394d | <|skeleton|>
class LadLogHelper:
"""Various LAD log helper functions encapsulated here, so that we don't have to tag along all the parameters."""
def __init__(self, logger_log, logger_error, waagent_event_adder, status_reporter, ext_name, ext_ver):
"""Constructor :param logger_log: Normal logging funct... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LadLogHelper:
"""Various LAD log helper functions encapsulated here, so that we don't have to tag along all the parameters."""
def __init__(self, logger_log, logger_error, waagent_event_adder, status_reporter, ext_name, ext_ver):
"""Constructor :param logger_log: Normal logging function (e.g., hu... | the_stack_v2_python_sparse | Diagnostic/Utils/misc_helpers.py | Azure/azure-linux-extensions | train | 300 |
420945a4c3cba2392aee29c5ab86004d5506ddb5 | [
"self.models = models\nfor model in self.models:\n del model.cluster_helper",
"predictions = np.stack([model.labelled_predict(x) for model in self.models], axis=1)\n\ndef get_vote(row):\n \"\"\"\n Gets the vote from a row of prediction.\n In case of ties, returns a random choice.\n\n ... | <|body_start_0|>
self.models = models
for model in self.models:
del model.cluster_helper
<|end_body_0|>
<|body_start_1|>
predictions = np.stack([model.labelled_predict(x) for model in self.models], axis=1)
def get_vote(row):
"""
Gets the vote... | MajorityVote | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MajorityVote:
def __init__(self, models):
"""Args: models (list of ClusterModels): Pre-trained ClusterModel objects."""
<|body_0|>
def labelled_predict(self, x):
"""Returns a majority vote for each row of x. Args: x (np.array): Array of embeddings. Returns: predictio... | stack_v2_sparse_classes_75kplus_train_066392 | 9,706 | no_license | [
{
"docstring": "Args: models (list of ClusterModels): Pre-trained ClusterModel objects.",
"name": "__init__",
"signature": "def __init__(self, models)"
},
{
"docstring": "Returns a majority vote for each row of x. Args: x (np.array): Array of embeddings. Returns: prediction (np.array): 1D array ... | 2 | null | Implement the Python class `MajorityVote` described below.
Class description:
Implement the MajorityVote class.
Method signatures and docstrings:
- def __init__(self, models): Args: models (list of ClusterModels): Pre-trained ClusterModel objects.
- def labelled_predict(self, x): Returns a majority vote for each row ... | Implement the Python class `MajorityVote` described below.
Class description:
Implement the MajorityVote class.
Method signatures and docstrings:
- def __init__(self, models): Args: models (list of ClusterModels): Pre-trained ClusterModel objects.
- def labelled_predict(self, x): Returns a majority vote for each row ... | 7979099152f6d509bac4aa0dab1660988b6388ac | <|skeleton|>
class MajorityVote:
def __init__(self, models):
"""Args: models (list of ClusterModels): Pre-trained ClusterModel objects."""
<|body_0|>
def labelled_predict(self, x):
"""Returns a majority vote for each row of x. Args: x (np.array): Array of embeddings. Returns: predictio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MajorityVote:
def __init__(self, models):
"""Args: models (list of ClusterModels): Pre-trained ClusterModel objects."""
self.models = models
for model in self.models:
del model.cluster_helper
def labelled_predict(self, x):
"""Returns a majority vote for each ro... | the_stack_v2_python_sparse | utils/clusters.py | josephdviviano/horoma | train | 1 | |
73e1e7fa4a6290287b17585ada3e94059a997101 | [
"self.capacity = capacity\nself.head = None\nself.tail = None\nself.val_hash = {}",
"try:\n node = self.val_hash[key]\n if node.next is not None:\n if node.prev is None:\n self.head = node.next\n node.next.prev = None\n else:\n node.next.prev = node.prev\n ... | <|body_start_0|>
self.capacity = capacity
self.head = None
self.tail = None
self.val_hash = {}
<|end_body_0|>
<|body_start_1|>
try:
node = self.val_hash[key]
if node.next is not None:
if node.prev is None:
self.head = n... | Hash table + double linked list Time: O(1) | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
"""Hash table + double linked list Time: O(1)"""
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type v... | stack_v2_sparse_classes_75kplus_train_066393 | 2,051 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | null | Implement the Python class `LRUCache` described below.
Class description:
Hash table + double linked list Time: O(1)
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtyp... | Implement the Python class `LRUCache` described below.
Class description:
Hash table + double linked list Time: O(1)
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtyp... | c2b26e8f078aadf23f3f1440cfa7578913bd4a8d | <|skeleton|>
class LRUCache:
"""Hash table + double linked list Time: O(1)"""
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type v... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LRUCache:
"""Hash table + double linked list Time: O(1)"""
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.head = None
self.tail = None
self.val_hash = {}
def get(self, key):
""":type key: int :rtype: int"""
... | the_stack_v2_python_sparse | leetcode/python/lru_cache.py | cshuo/algs | train | 0 |
7718700a9768745065130f72d9971e0e786bd11a | [
"password = data['password']\npassword_conf = data['passwordConfirmation']\nif password != password_conf:\n raise serializers.ValidationError(\"Passwords don't match\")\npassword_validation.validate_password(password)\nreturn data",
"data.pop('passwordConfirmation')\nuser = Users.objects.create_user(**data, is... | <|body_start_0|>
password = data['password']
password_conf = data['passwordConfirmation']
if password != password_conf:
raise serializers.ValidationError("Passwords don't match")
password_validation.validate_password(password)
return data
<|end_body_0|>
<|body_start_... | usersignupserializer tiene los datos de registro y crea un usuario/perfil Args: serializers ([type]): [description] Raises: serializers.ValidationError: [description] Returns: [type]: [description] | UserSignupSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserSignupSerializer:
"""usersignupserializer tiene los datos de registro y crea un usuario/perfil Args: serializers ([type]): [description] Raises: serializers.ValidationError: [description] Returns: [type]: [description]"""
def validate(self, data):
"""Valida los campos Args: data ... | stack_v2_sparse_classes_75kplus_train_066394 | 5,399 | permissive | [
{
"docstring": "Valida los campos Args: data ([type]): [description] Raises: serializers.ValidationError: [description] Returns: [type]: [description]",
"name": "validate",
"signature": "def validate(self, data)"
},
{
"docstring": "Crea usuario y perfil Args: data ([type]): [description] Raises:... | 2 | null | Implement the Python class `UserSignupSerializer` described below.
Class description:
usersignupserializer tiene los datos de registro y crea un usuario/perfil Args: serializers ([type]): [description] Raises: serializers.ValidationError: [description] Returns: [type]: [description]
Method signatures and docstrings:
... | Implement the Python class `UserSignupSerializer` described below.
Class description:
usersignupserializer tiene los datos de registro y crea un usuario/perfil Args: serializers ([type]): [description] Raises: serializers.ValidationError: [description] Returns: [type]: [description]
Method signatures and docstrings:
... | 6652ee7bd0d1f84bed288e83d745d5f7b72666e8 | <|skeleton|>
class UserSignupSerializer:
"""usersignupserializer tiene los datos de registro y crea un usuario/perfil Args: serializers ([type]): [description] Raises: serializers.ValidationError: [description] Returns: [type]: [description]"""
def validate(self, data):
"""Valida los campos Args: data ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserSignupSerializer:
"""usersignupserializer tiene los datos de registro y crea un usuario/perfil Args: serializers ([type]): [description] Raises: serializers.ValidationError: [description] Returns: [type]: [description]"""
def validate(self, data):
"""Valida los campos Args: data ([type]): [de... | the_stack_v2_python_sparse | cride/users/serializers/users.py | JaviMiot/Cride_page | train | 0 |
1d2cd9bd9615ce46726039047b1a32fbbf4011cb | [
"self.sentences = sentences\nself.frequency_elements = frequency_elements\nself.split_train_test = split_train_test\nself.max_speakers = max_speakers\nself.speaker_list = speaker_list\nself.max_audio_length = max_audio_length\nif output_name is None:\n self.output_name = speaker_list\nelse:\n self.output_name... | <|body_start_0|>
self.sentences = sentences
self.frequency_elements = frequency_elements
self.split_train_test = split_train_test
self.max_speakers = max_speakers
self.speaker_list = speaker_list
self.max_audio_length = max_audio_length
if output_name is None:
... | Speaker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Speaker:
def __init__(self, split_train_test, max_speakers, speaker_list, output_name=None, sentences=10, frequency_elements=128, max_audio_length=800):
"""Represents a fully defined speaker in the Speaker clustering suite. :param frequency_elements: How many frequency elements should be... | stack_v2_sparse_classes_75kplus_train_066395 | 4,024 | no_license | [
{
"docstring": "Represents a fully defined speaker in the Speaker clustering suite. :param frequency_elements: How many frequency elements should be in a spectrogram :param split_train_test: Whether or not to split the test and training data :param max_speakers: The maximum amount of speakers to fetch from TIMI... | 3 | stack_v2_sparse_classes_30k_train_048318 | Implement the Python class `Speaker` described below.
Class description:
Implement the Speaker class.
Method signatures and docstrings:
- def __init__(self, split_train_test, max_speakers, speaker_list, output_name=None, sentences=10, frequency_elements=128, max_audio_length=800): Represents a fully defined speaker i... | Implement the Python class `Speaker` described below.
Class description:
Implement the Speaker class.
Method signatures and docstrings:
- def __init__(self, split_train_test, max_speakers, speaker_list, output_name=None, sentences=10, frequency_elements=128, max_audio_length=800): Represents a fully defined speaker i... | baf97bd4815a92c769276b84224d9f9f6c3fc59a | <|skeleton|>
class Speaker:
def __init__(self, split_train_test, max_speakers, speaker_list, output_name=None, sentences=10, frequency_elements=128, max_audio_length=800):
"""Represents a fully defined speaker in the Speaker clustering suite. :param frequency_elements: How many frequency elements should be... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Speaker:
def __init__(self, split_train_test, max_speakers, speaker_list, output_name=None, sentences=10, frequency_elements=128, max_audio_length=800):
"""Represents a fully defined speaker in the Speaker clustering suite. :param frequency_elements: How many frequency elements should be in a spectrog... | the_stack_v2_python_sparse | ext_clust/common/extrapolation/speaker.py | kutoga/learning2cluster | train | 12 | |
901f186b3f1e72c9cff7f350bdf0ed0c9a62beb6 | [
"rmgpy_path = os.path.normpath(os.path.join(get_path(), '..'))\nqm = QMCalculator(software='mopac', method='pm3', fileStore=os.path.join(rmgpy_path, 'testing', 'qm', 'QMfiles'), scratchDirectory=os.path.join(rmgpy_path, 'testing', 'qm', 'QMscratch'))\nif not os.path.exists(qm.settings.fileStore):\n os.makedirs(q... | <|body_start_0|>
rmgpy_path = os.path.normpath(os.path.join(get_path(), '..'))
qm = QMCalculator(software='mopac', method='pm3', fileStore=os.path.join(rmgpy_path, 'testing', 'qm', 'QMfiles'), scratchDirectory=os.path.join(rmgpy_path, 'testing', 'qm', 'QMscratch'))
if not os.path.exists(qm.setti... | Contains unit tests for the Geometry class. | TestMopacMolPM3 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMopacMolPM3:
"""Contains unit tests for the Geometry class."""
def setUp(self):
"""A function run before each unit test in this class."""
<|body_0|>
def test_generate_thermo_data(self):
"""Test that generate_thermo_data() works correctly for MOPAC PM3"""
... | stack_v2_sparse_classes_75kplus_train_066396 | 11,517 | permissive | [
{
"docstring": "A function run before each unit test in this class.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test that generate_thermo_data() works correctly for MOPAC PM3",
"name": "test_generate_thermo_data",
"signature": "def test_generate_thermo_data(self)... | 3 | stack_v2_sparse_classes_30k_val_002108 | Implement the Python class `TestMopacMolPM3` described below.
Class description:
Contains unit tests for the Geometry class.
Method signatures and docstrings:
- def setUp(self): A function run before each unit test in this class.
- def test_generate_thermo_data(self): Test that generate_thermo_data() works correctly ... | Implement the Python class `TestMopacMolPM3` described below.
Class description:
Contains unit tests for the Geometry class.
Method signatures and docstrings:
- def setUp(self): A function run before each unit test in this class.
- def test_generate_thermo_data(self): Test that generate_thermo_data() works correctly ... | 349a4af759cf8877197772cd7eaca1e51d46eff5 | <|skeleton|>
class TestMopacMolPM3:
"""Contains unit tests for the Geometry class."""
def setUp(self):
"""A function run before each unit test in this class."""
<|body_0|>
def test_generate_thermo_data(self):
"""Test that generate_thermo_data() works correctly for MOPAC PM3"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestMopacMolPM3:
"""Contains unit tests for the Geometry class."""
def setUp(self):
"""A function run before each unit test in this class."""
rmgpy_path = os.path.normpath(os.path.join(get_path(), '..'))
qm = QMCalculator(software='mopac', method='pm3', fileStore=os.path.join(rmgp... | the_stack_v2_python_sparse | rmgpy/qm/mopacTest.py | CanePan-cc/CanePanWorkshop | train | 2 |
c897a6eb1bc88a63047e7afbc1a349e53973ec1d | [
"self.parent_can_read = Event()\nself.comm_queue = Queue()\nself.child_can_read = Event()\nself.x0 = x0.copy()\nself.f0 = f0.copy()\nif grad0 is not None:\n self.grad0 = grad0.copy()\nelse:\n self.grad0 = None\nif user_specs['localopt_method'] in ['LN_SBPLX', 'LN_BOBYQA', 'LN_COBYLA', 'LN_NEWUOA', 'LN_NELDERM... | <|body_start_0|>
self.parent_can_read = Event()
self.comm_queue = Queue()
self.child_can_read = Event()
self.x0 = x0.copy()
self.f0 = f0.copy()
if grad0 is not None:
self.grad0 = grad0.copy()
else:
self.grad0 = None
if user_specs['l... | This class defines the APOSMM interface to various local optimization routines. Currently supported routines are - NLopt routines ['LN_SBPLX', 'LN_BOBYQA', 'LN_COBYLA', 'LN_NEWUOA', 'LN_NELDERMEAD', 'LD_MMA'] - PETSc/TAO routines ['pounders', 'blmvm', 'nm'] - SciPy routines ['scipy_Nelder-Mead', 'scipy_COBYLA', 'scipy_... | LocalOptInterfacer | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocalOptInterfacer:
"""This class defines the APOSMM interface to various local optimization routines. Currently supported routines are - NLopt routines ['LN_SBPLX', 'LN_BOBYQA', 'LN_COBYLA', 'LN_NEWUOA', 'LN_NELDERMEAD', 'LD_MMA'] - PETSc/TAO routines ['pounders', 'blmvm', 'nm'] - SciPy routines... | stack_v2_sparse_classes_75kplus_train_066397 | 22,231 | permissive | [
{
"docstring": ":param x0: A numpy array of the initial guess solution. This guess should be scaled to a unit cube. :param f0: A numpy array of the initial function value. .. warning:: In order to have correct functioning of the local optimization child processes. ~self.iterate~ should be called immediately aft... | 4 | stack_v2_sparse_classes_30k_train_030372 | Implement the Python class `LocalOptInterfacer` described below.
Class description:
This class defines the APOSMM interface to various local optimization routines. Currently supported routines are - NLopt routines ['LN_SBPLX', 'LN_BOBYQA', 'LN_COBYLA', 'LN_NEWUOA', 'LN_NELDERMEAD', 'LD_MMA'] - PETSc/TAO routines ['pou... | Implement the Python class `LocalOptInterfacer` described below.
Class description:
This class defines the APOSMM interface to various local optimization routines. Currently supported routines are - NLopt routines ['LN_SBPLX', 'LN_BOBYQA', 'LN_COBYLA', 'LN_NEWUOA', 'LN_NELDERMEAD', 'LD_MMA'] - PETSc/TAO routines ['pou... | 0ffcc5f88f693ebf60ba125a7cae6a44d2c98c6f | <|skeleton|>
class LocalOptInterfacer:
"""This class defines the APOSMM interface to various local optimization routines. Currently supported routines are - NLopt routines ['LN_SBPLX', 'LN_BOBYQA', 'LN_COBYLA', 'LN_NEWUOA', 'LN_NELDERMEAD', 'LD_MMA'] - PETSc/TAO routines ['pounders', 'blmvm', 'nm'] - SciPy routines... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LocalOptInterfacer:
"""This class defines the APOSMM interface to various local optimization routines. Currently supported routines are - NLopt routines ['LN_SBPLX', 'LN_BOBYQA', 'LN_COBYLA', 'LN_NEWUOA', 'LN_NELDERMEAD', 'LD_MMA'] - PETSc/TAO routines ['pounders', 'blmvm', 'nm'] - SciPy routines ['scipy_Neld... | the_stack_v2_python_sparse | libensemble/gen_funcs/aposmm_localopt_support.py | Libensemble/libensemble | train | 69 |
dade8670a6538df136ed6fbb61c6487cf4454292 | [
"self.pump = Pump('127.0.0.1', 8000)\nself.sensor = Sensor('127.0.0.1', 8000)\nself.decider = Decider(100, 0.05)\nself.controller = Controller(self.sensor, self.pump, self.decider)",
"self.sensor.measure = MagicMock(return_value=90)\nself.pump.get_state = MagicMock(return_value=Pump.PUMP_OFF)\nself.decider.decide... | <|body_start_0|>
self.pump = Pump('127.0.0.1', 8000)
self.sensor = Sensor('127.0.0.1', 8000)
self.decider = Decider(100, 0.05)
self.controller = Controller(self.sensor, self.pump, self.decider)
<|end_body_0|>
<|body_start_1|>
self.sensor.measure = MagicMock(return_value=90)
... | Unit tests for the Controller class | ControllerTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""setUp method for Controller tests"""
<|body_0|>
def test_tick(self):
"""Test for the tick function"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.pump = Pump('1... | stack_v2_sparse_classes_75kplus_train_066398 | 2,522 | no_license | [
{
"docstring": "setUp method for Controller tests",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test for the tick function",
"name": "test_tick",
"signature": "def test_tick(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000659 | Implement the Python class `ControllerTests` described below.
Class description:
Unit tests for the Controller class
Method signatures and docstrings:
- def setUp(self): setUp method for Controller tests
- def test_tick(self): Test for the tick function | Implement the Python class `ControllerTests` described below.
Class description:
Unit tests for the Controller class
Method signatures and docstrings:
- def setUp(self): setUp method for Controller tests
- def test_tick(self): Test for the tick function
<|skeleton|>
class ControllerTests:
"""Unit tests for the C... | b1fea0309b3495b3e1dc167d7029bc9e4b6f00f1 | <|skeleton|>
class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""setUp method for Controller tests"""
<|body_0|>
def test_tick(self):
"""Test for the tick function"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""setUp method for Controller tests"""
self.pump = Pump('127.0.0.1', 8000)
self.sensor = Sensor('127.0.0.1', 8000)
self.decider = Decider(100, 0.05)
self.controller = Controller(self.senso... | the_stack_v2_python_sparse | students/wwhite/Lesson06/water-regulation/waterregulation/test.py | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | train | 4 |
4924dfc0bd70d24198126be8eaa0209b859a2696 | [
"from mitre.securingai.restapi.models import Experiment\n\ndef slugify(text: str) -> str:\n return text.lower().strip().replace(' ', '-')\nstandardized_name: str = slugify(field.data)\nif Experiment.query.filter_by(name=standardized_name, is_deleted=False).first() is None:\n raise ValidationError(f'Bad Reques... | <|body_start_0|>
from mitre.securingai.restapi.models import Experiment
def slugify(text: str) -> str:
return text.lower().strip().replace(' ', '-')
standardized_name: str = slugify(field.data)
if Experiment.query.filter_by(name=standardized_name, is_deleted=False).first() i... | The job submission form. Attributes: experiment_name: The name of a registered experiment. queue: The name of an active queue. timeout: The maximum alloted time for a job before it times out and is stopped. If omitted, the job timeout will default to 24 hours. entry_point: The name of the entry point in the MLproject f... | JobForm | [
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JobForm:
"""The job submission form. Attributes: experiment_name: The name of a registered experiment. queue: The name of an active queue. timeout: The maximum alloted time for a job before it times out and is stopped. If omitted, the job timeout will default to 24 hours. entry_point: The name of... | stack_v2_sparse_classes_75kplus_train_066399 | 10,183 | permissive | [
{
"docstring": "Validates that the experiment is registered and not deleted. Args: field: The form field for `experiment_name`.",
"name": "validate_experiment_name",
"signature": "def validate_experiment_name(self, field)"
},
{
"docstring": "Validates that the queue is registered, active and not... | 2 | stack_v2_sparse_classes_30k_train_020400 | Implement the Python class `JobForm` described below.
Class description:
The job submission form. Attributes: experiment_name: The name of a registered experiment. queue: The name of an active queue. timeout: The maximum alloted time for a job before it times out and is stopped. If omitted, the job timeout will defaul... | Implement the Python class `JobForm` described below.
Class description:
The job submission form. Attributes: experiment_name: The name of a registered experiment. queue: The name of an active queue. timeout: The maximum alloted time for a job before it times out and is stopped. If omitted, the job timeout will defaul... | 639940e64e0a92fbcb7ec7f6588d0dfaaf9f0b1d | <|skeleton|>
class JobForm:
"""The job submission form. Attributes: experiment_name: The name of a registered experiment. queue: The name of an active queue. timeout: The maximum alloted time for a job before it times out and is stopped. If omitted, the job timeout will default to 24 hours. entry_point: The name of... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JobForm:
"""The job submission form. Attributes: experiment_name: The name of a registered experiment. queue: The name of an active queue. timeout: The maximum alloted time for a job before it times out and is stopped. If omitted, the job timeout will default to 24 hours. entry_point: The name of the entry po... | the_stack_v2_python_sparse | src/mitre/securingai/restapi/job/model.py | hhuangMITRE/dioptra | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.