blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
6.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
438
7.52k
id
stringlengths
40
40
length_bytes
int64
506
50k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
153
4.25k
prompted_full_text
stringlengths
645
10.7k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
4.34k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
solution
stringlengths
302
7.33k
source
stringclasses
1 value
source_path
stringlengths
4
177
source_repo
stringlengths
6
110
split
stringclasses
1 value
star_events_count
int64
0
209k
9a5ac4809aa729949070f15cd48cf35504bf9c6f
[ "with codecs.open(file_name, 'r', encoding='utf8') as f:\n recs = json.load(f)\nself.recs = recs", "if query == None:\n fc = FakeCursor(self.recs)\nelse:\n retur = []\n k = query.keys()[0]\n v = query.values()[0]\n for rec in self.recs:\n if rec[k] == v:\n retur.append(rec)\n ...
<|body_start_0|> with codecs.open(file_name, 'r', encoding='utf8') as f: recs = json.load(f) self.recs = recs <|end_body_0|> <|body_start_1|> if query == None: fc = FakeCursor(self.recs) else: retur = [] k = query.keys()[0] v =...
Mock Object interface for MongoDB client
FakeMongo
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FakeMongo: """Mock Object interface for MongoDB client""" def __init__(self, file_name): """Make a FakeMongo Args: file_name (str): name of json file to draw queries from""" <|body_0|> def find(self, query=None): """perform query on file using mongodb query synta...
stack_v2_sparse_classes_36k_train_028300
1,965
no_license
[ { "docstring": "Make a FakeMongo Args: file_name (str): name of json file to draw queries from", "name": "__init__", "signature": "def __init__(self, file_name)" }, { "docstring": "perform query on file using mongodb query syntax (Only partially functional) Kwargs: query (dict): MongoDB style qu...
2
stack_v2_sparse_classes_30k_test_000833
Implement the Python class `FakeMongo` described below. Class description: Mock Object interface for MongoDB client Method signatures and docstrings: - def __init__(self, file_name): Make a FakeMongo Args: file_name (str): name of json file to draw queries from - def find(self, query=None): perform query on file usin...
Implement the Python class `FakeMongo` described below. Class description: Mock Object interface for MongoDB client Method signatures and docstrings: - def __init__(self, file_name): Make a FakeMongo Args: file_name (str): name of json file to draw queries from - def find(self, query=None): perform query on file usin...
1da48eba195a6452dee71fa085ee2ffc55d19777
<|skeleton|> class FakeMongo: """Mock Object interface for MongoDB client""" def __init__(self, file_name): """Make a FakeMongo Args: file_name (str): name of json file to draw queries from""" <|body_0|> def find(self, query=None): """perform query on file using mongodb query synta...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FakeMongo: """Mock Object interface for MongoDB client""" def __init__(self, file_name): """Make a FakeMongo Args: file_name (str): name of json file to draw queries from""" with codecs.open(file_name, 'r', encoding='utf8') as f: recs = json.load(f) self.recs = recs ...
the_stack_v2_python_sparse
fruitbowl/cherry/fake_mongo.py
patrick-s-h-lewis/fruitbowl
train
1
a09465adfa5927cc209244e1db8fa01f76b18081
[ "company = self.env.company\nfor user in self:\n if user.branch_id and user.branch_id.company_id != company:\n raise exceptions.UserError(_(\"Sorry! The selected Branch does not belong to the current Company '%s'\", company.name))", "if self.property_warehouse_id:\n return self.property_warehouse_id\...
<|body_start_0|> company = self.env.company for user in self: if user.branch_id and user.branch_id.company_id != company: raise exceptions.UserError(_("Sorry! The selected Branch does not belong to the current Company '%s'", company.name)) <|end_body_0|> <|body_start_1|> ...
inherited res users
ResUsers
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResUsers: """inherited res users""" def branch_constrains(self): """branch constrains""" <|body_0|> def _get_default_warehouse_id(self): """methode to get default warehouse id""" <|body_1|> <|end_skeleton|> <|body_start_0|> company = self.env.co...
stack_v2_sparse_classes_36k_train_028301
2,986
no_license
[ { "docstring": "branch constrains", "name": "branch_constrains", "signature": "def branch_constrains(self)" }, { "docstring": "methode to get default warehouse id", "name": "_get_default_warehouse_id", "signature": "def _get_default_warehouse_id(self)" } ]
2
stack_v2_sparse_classes_30k_train_019241
Implement the Python class `ResUsers` described below. Class description: inherited res users Method signatures and docstrings: - def branch_constrains(self): branch constrains - def _get_default_warehouse_id(self): methode to get default warehouse id
Implement the Python class `ResUsers` described below. Class description: inherited res users Method signatures and docstrings: - def branch_constrains(self): branch constrains - def _get_default_warehouse_id(self): methode to get default warehouse id <|skeleton|> class ResUsers: """inherited res users""" d...
4b1bcb8f17aad44fe9c80a8180eb0128e6bb2c14
<|skeleton|> class ResUsers: """inherited res users""" def branch_constrains(self): """branch constrains""" <|body_0|> def _get_default_warehouse_id(self): """methode to get default warehouse id""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ResUsers: """inherited res users""" def branch_constrains(self): """branch constrains""" company = self.env.company for user in self: if user.branch_id and user.branch_id.company_id != company: raise exceptions.UserError(_("Sorry! The selected Branch do...
the_stack_v2_python_sparse
multi_branch_base/models/branch_res_users.py
CybroOdoo/CybroAddons
train
209
3ff3a964099cfd0b9c9b9377663e1619e428690b
[ "group_map = {}\nitem_groups = self.item.item_groups\nfor group in item_groups:\n if group.id in group_map:\n msg = \"menu item '%s' has duplicate group '%s'\"\n raise ValueError(msg % (self.path, group.id))\n group_map[group.id] = group\nif u'' not in group_map:\n group = ItemGroup()\n gr...
<|body_start_0|> group_map = {} item_groups = self.item.item_groups for group in item_groups: if group.id in group_map: msg = "menu item '%s' has duplicate group '%s'" raise ValueError(msg % (self.path, group.id)) group_map[group.id] = grou...
A path node representing a menu item. This class is an implementation detail and should not be consumed by code outside of this module.
MenuNode
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MenuNode: """A path node representing a menu item. This class is an implementation detail and should not be consumed by code outside of this module.""" def group_data(self): """The group map and list of group items for the node. Returns ------- result : tuple A tuple of (dict, list) ...
stack_v2_sparse_classes_36k_train_028302
10,191
permissive
[ { "docstring": "The group map and list of group items for the node. Returns ------- result : tuple A tuple of (dict, list) which holds the mapping of group id to ItemGroup object, and the flat list of ordered groups.", "name": "group_data", "signature": "def group_data(self)" }, { "docstring": "...
5
stack_v2_sparse_classes_30k_train_010287
Implement the Python class `MenuNode` described below. Class description: A path node representing a menu item. This class is an implementation detail and should not be consumed by code outside of this module. Method signatures and docstrings: - def group_data(self): The group map and list of group items for the node...
Implement the Python class `MenuNode` described below. Class description: A path node representing a menu item. This class is an implementation detail and should not be consumed by code outside of this module. Method signatures and docstrings: - def group_data(self): The group map and list of group items for the node...
1544e7fb371b8f941cfa2fde682795e479380284
<|skeleton|> class MenuNode: """A path node representing a menu item. This class is an implementation detail and should not be consumed by code outside of this module.""" def group_data(self): """The group map and list of group items for the node. Returns ------- result : tuple A tuple of (dict, list) ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MenuNode: """A path node representing a menu item. This class is an implementation detail and should not be consumed by code outside of this module.""" def group_data(self): """The group map and list of group items for the node. Returns ------- result : tuple A tuple of (dict, list) which holds t...
the_stack_v2_python_sparse
enaml/workbench/ui/menu_helper.py
MatthieuDartiailh/enaml
train
26
19bf51b9b899aeae3c676e7bc4e292e8a482a107
[ "c = Counter()\nfor ch in string:\n c[ch] += 1\nfor key in c.keys():\n if key > 1:\n return True\nreturn False", "if len(string) == 1:\n return True\nfor i in range(len(string)):\n temp = string[i]\n substring = string[:i] + string[i + 1:]\n for temp_ch in substring:\n if temp == t...
<|body_start_0|> c = Counter() for ch in string: c[ch] += 1 for key in c.keys(): if key > 1: return True return False <|end_body_0|> <|body_start_1|> if len(string) == 1: return True for i in range(len(string)): ...
isUnique
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class isUnique: def check_hashmap(self, string): """Solution uses additional Counter (hashmap) datastructure""" <|body_0|> def check_no_ds(self, string): """Solution without using any additional datastructures""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_028303
798
no_license
[ { "docstring": "Solution uses additional Counter (hashmap) datastructure", "name": "check_hashmap", "signature": "def check_hashmap(self, string)" }, { "docstring": "Solution without using any additional datastructures", "name": "check_no_ds", "signature": "def check_no_ds(self, string)"...
2
stack_v2_sparse_classes_30k_train_009753
Implement the Python class `isUnique` described below. Class description: Implement the isUnique class. Method signatures and docstrings: - def check_hashmap(self, string): Solution uses additional Counter (hashmap) datastructure - def check_no_ds(self, string): Solution without using any additional datastructures
Implement the Python class `isUnique` described below. Class description: Implement the isUnique class. Method signatures and docstrings: - def check_hashmap(self, string): Solution uses additional Counter (hashmap) datastructure - def check_no_ds(self, string): Solution without using any additional datastructures <...
09d75e3ec63308d3b8be0b07748043cde79a62a1
<|skeleton|> class isUnique: def check_hashmap(self, string): """Solution uses additional Counter (hashmap) datastructure""" <|body_0|> def check_no_ds(self, string): """Solution without using any additional datastructures""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class isUnique: def check_hashmap(self, string): """Solution uses additional Counter (hashmap) datastructure""" c = Counter() for ch in string: c[ch] += 1 for key in c.keys(): if key > 1: return True return False def check_no_ds(se...
the_stack_v2_python_sparse
ctc/ch01-arrays/1-is-unique.py
skailasa/practice
train
5
a7596482fd636fb08ad508e926899fd4c82e1eaa
[ "super().__init__(settings, ui_id, job_id)\nself.local_template = 'settings/bilby_local.sh'\nself.job_parameter_file = os.path.join(self.get_working_directory(), 'json_params.json')\nself.job_output_directory = os.path.join(self.get_working_directory(), 'output')", "params = super().generate_template_dict()\npara...
<|body_start_0|> super().__init__(settings, ui_id, job_id) self.local_template = 'settings/bilby_local.sh' self.job_parameter_file = os.path.join(self.get_working_directory(), 'json_params.json') self.job_output_directory = os.path.join(self.get_working_directory(), 'output') <|end_body_...
Bilby
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Bilby: def __init__(self, settings, ui_id, job_id): """Initialises the local scheduler class for Bilby :param settings: The settings from settings.py :param ui_id: The UI id of the job :param job_id: The Slurm id of the Job""" <|body_0|> def generate_template_dict(self): ...
stack_v2_sparse_classes_36k_train_028304
2,162
permissive
[ { "docstring": "Initialises the local scheduler class for Bilby :param settings: The settings from settings.py :param ui_id: The UI id of the job :param job_id: The Slurm id of the Job", "name": "__init__", "signature": "def __init__(self, settings, ui_id, job_id)" }, { "docstring": "Called befo...
3
stack_v2_sparse_classes_30k_test_000187
Implement the Python class `Bilby` described below. Class description: Implement the Bilby class. Method signatures and docstrings: - def __init__(self, settings, ui_id, job_id): Initialises the local scheduler class for Bilby :param settings: The settings from settings.py :param ui_id: The UI id of the job :param jo...
Implement the Python class `Bilby` described below. Class description: Implement the Bilby class. Method signatures and docstrings: - def __init__(self, settings, ui_id, job_id): Initialises the local scheduler class for Bilby :param settings: The settings from settings.py :param ui_id: The UI id of the job :param jo...
68ebdec8dd2fe7a4d1c6ad07783e86ea2056ae67
<|skeleton|> class Bilby: def __init__(self, settings, ui_id, job_id): """Initialises the local scheduler class for Bilby :param settings: The settings from settings.py :param ui_id: The UI id of the job :param job_id: The Slurm id of the Job""" <|body_0|> def generate_template_dict(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Bilby: def __init__(self, settings, ui_id, job_id): """Initialises the local scheduler class for Bilby :param settings: The settings from settings.py :param ui_id: The UI id of the job :param job_id: The Slurm id of the Job""" super().__init__(settings, ui_id, job_id) self.local_templa...
the_stack_v2_python_sparse
misc/job_controller_scripts/local/bilby_local.py
ADACS-Australia/SS18B-PLasky
train
1
6c2f8302b3ecea41ee2db945bacfdfb31bdf3573
[ "if len(self.variant.alleles) > 2:\n raise ValueError('Additive encoding can only be used with one allele')\nallele_sum = self.allele_idxs.sum(axis=1).astype('float')\nallele_sum[(self.allele_idxs == MISSING_IDX).any(axis=1)] = np.nan\nresult = pd.array(data=allele_sum, dtype='UInt8')\nreturn result", "if len(...
<|body_start_0|> if len(self.variant.alleles) > 2: raise ValueError('Additive encoding can only be used with one allele') allele_sum = self.allele_idxs.sum(axis=1).astype('float') allele_sum[(self.allele_idxs == MISSING_IDX).any(axis=1)] = np.nan result = pd.array(data=allele...
Genotype Mixin containing functions for performing encoding
EncodingMixin
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EncodingMixin: """Genotype Mixin containing functions for performing encoding""" def encode_additive(self) -> pd.arrays.IntegerArray: """Returns ------- pd.arrays.IntegerArray Number of copies of the minor allele pd.NA when any alleles are missing Raises ValueError if there is more t...
stack_v2_sparse_classes_36k_train_028305
3,710
permissive
[ { "docstring": "Returns ------- pd.arrays.IntegerArray Number of copies of the minor allele pd.NA when any alleles are missing Raises ValueError if there is more than 1 alternate allele", "name": "encode_additive", "signature": "def encode_additive(self) -> pd.arrays.IntegerArray" }, { "docstrin...
4
stack_v2_sparse_classes_30k_train_013639
Implement the Python class `EncodingMixin` described below. Class description: Genotype Mixin containing functions for performing encoding Method signatures and docstrings: - def encode_additive(self) -> pd.arrays.IntegerArray: Returns ------- pd.arrays.IntegerArray Number of copies of the minor allele pd.NA when any...
Implement the Python class `EncodingMixin` described below. Class description: Genotype Mixin containing functions for performing encoding Method signatures and docstrings: - def encode_additive(self) -> pd.arrays.IntegerArray: Returns ------- pd.arrays.IntegerArray Number of copies of the minor allele pd.NA when any...
a4419a5c491567ddfca7fdb2234a1c0d7e396719
<|skeleton|> class EncodingMixin: """Genotype Mixin containing functions for performing encoding""" def encode_additive(self) -> pd.arrays.IntegerArray: """Returns ------- pd.arrays.IntegerArray Number of copies of the minor allele pd.NA when any alleles are missing Raises ValueError if there is more t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EncodingMixin: """Genotype Mixin containing functions for performing encoding""" def encode_additive(self) -> pd.arrays.IntegerArray: """Returns ------- pd.arrays.IntegerArray Number of copies of the minor allele pd.NA when any alleles are missing Raises ValueError if there is more than 1 alterna...
the_stack_v2_python_sparse
pandas_genomics/arrays/encoding_mixin.py
adbmd/pandas-genomics
train
0
c73e3b8a572c638085919b3aefd202c99b489de8
[ "try:\n return cls._CODE_MAP[code]\nexcept KeyError as err:\n raise ValueError(f\"Cannot find a region for the code '{code}'\") from err", "if cls._current_region is None:\n raise ValueError('You must set the active region with `set_region()` before it can be accessed')\nreturn cls._current_region", "t...
<|body_start_0|> try: return cls._CODE_MAP[code] except KeyError as err: raise ValueError(f"Cannot find a region for the code '{code}'") from err <|end_body_0|> <|body_start_1|> if cls._current_region is None: raise ValueError('You must set the active region ...
A collection of all the regions as an enum like object.
Regions
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Regions: """A collection of all the regions as an enum like object.""" def from_code(cls, code: str) -> Region: """Get a region object based on its code. :raises ValueError: If no valid region can be found.""" <|body_0|> def get_region(cls) -> Region: """Get the ...
stack_v2_sparse_classes_36k_train_028306
2,395
permissive
[ { "docstring": "Get a region object based on its code. :raises ValueError: If no valid region can be found.", "name": "from_code", "signature": "def from_code(cls, code: str) -> Region" }, { "docstring": "Get the region this app is running in. :raises ValueError: If the active region has not bee...
3
stack_v2_sparse_classes_30k_train_002729
Implement the Python class `Regions` described below. Class description: A collection of all the regions as an enum like object. Method signatures and docstrings: - def from_code(cls, code: str) -> Region: Get a region object based on its code. :raises ValueError: If no valid region can be found. - def get_region(cls...
Implement the Python class `Regions` described below. Class description: A collection of all the regions as an enum like object. Method signatures and docstrings: - def from_code(cls, code: str) -> Region: Get a region object based on its code. :raises ValueError: If no valid region can be found. - def get_region(cls...
86614d8fe690ca52516fef87bfffe9e61dd2c21f
<|skeleton|> class Regions: """A collection of all the regions as an enum like object.""" def from_code(cls, code: str) -> Region: """Get a region object based on its code. :raises ValueError: If no valid region can be found.""" <|body_0|> def get_region(cls) -> Region: """Get the ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Regions: """A collection of all the regions as an enum like object.""" def from_code(cls, code: str) -> Region: """Get a region object based on its code. :raises ValueError: If no valid region can be found.""" try: return cls._CODE_MAP[code] except KeyError as err: ...
the_stack_v2_python_sparse
lms/models/region.py
hypothesis/lms
train
44
800e89db03c0091e696d9ee58a97ffd90de94cbb
[ "if isinstance(key, int):\n return TransType(key)\nif key not in TransType._member_map_:\n extend_enum(TransType, key, default)\nreturn TransType[key]", "if not (isinstance(value, int) and 0 <= value <= 255):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nif 144 <= value <= 252:\n ...
<|body_start_0|> if isinstance(key, int): return TransType(key) if key not in TransType._member_map_: extend_enum(TransType, key, default) return TransType[key] <|end_body_0|> <|body_start_1|> if not (isinstance(value, int) and 0 <= value <= 255): rai...
[TransType] Transport Layer Protocol Numbers
TransType
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TransType: """[TransType] Transport Layer Protocol Numbers""" def get(key, default=-1): """Backport support for original codes.""" <|body_0|> def _missing_(cls, value): """Lookup function used when value is not found.""" <|body_1|> <|end_skeleton|> <|bo...
stack_v2_sparse_classes_36k_train_028307
13,924
permissive
[ { "docstring": "Backport support for original codes.", "name": "get", "signature": "def get(key, default=-1)" }, { "docstring": "Lookup function used when value is not found.", "name": "_missing_", "signature": "def _missing_(cls, value)" } ]
2
stack_v2_sparse_classes_30k_train_001483
Implement the Python class `TransType` described below. Class description: [TransType] Transport Layer Protocol Numbers Method signatures and docstrings: - def get(key, default=-1): Backport support for original codes. - def _missing_(cls, value): Lookup function used when value is not found.
Implement the Python class `TransType` described below. Class description: [TransType] Transport Layer Protocol Numbers Method signatures and docstrings: - def get(key, default=-1): Backport support for original codes. - def _missing_(cls, value): Lookup function used when value is not found. <|skeleton|> class Tran...
71363d7948003fec88cedcf5bc80b6befa2ba244
<|skeleton|> class TransType: """[TransType] Transport Layer Protocol Numbers""" def get(key, default=-1): """Backport support for original codes.""" <|body_0|> def _missing_(cls, value): """Lookup function used when value is not found.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TransType: """[TransType] Transport Layer Protocol Numbers""" def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return TransType(key) if key not in TransType._member_map_: extend_enum(TransType, key, default) ...
the_stack_v2_python_sparse
pcapkit/const/reg/transtype.py
hiok2000/PyPCAPKit
train
0
0066c5bdefb2b716e3202f0c1b809dbbd2eebe69
[ "self.name = name\nself.time_zone = time_zone\nself.tags = tags\nself.disable_my_meraki_com = disable_my_meraki_com\nself.disable_remote_status_page = disable_remote_status_page\nself.enrollment_string = enrollment_string", "if dictionary is None:\n return None\nname = dictionary.get('name')\ntime_zone = dicti...
<|body_start_0|> self.name = name self.time_zone = time_zone self.tags = tags self.disable_my_meraki_com = disable_my_meraki_com self.disable_remote_status_page = disable_remote_status_page self.enrollment_string = enrollment_string <|end_body_0|> <|body_start_1|> ...
Implementation of the 'updateNetwork' model. TODO: type model description here. Attributes: name (string): The name of the network time_zone (string): The timezone of the network. For a list of allowed timezones, please see the 'TZ' column in the table in <a target='_blank' href='https://en.wikipedia.org/wiki/List_of_t...
UpdateNetworkModel
[ "MIT", "Python-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UpdateNetworkModel: """Implementation of the 'updateNetwork' model. TODO: type model description here. Attributes: name (string): The name of the network time_zone (string): The timezone of the network. For a list of allowed timezones, please see the 'TZ' column in the table in <a target='_blank'...
stack_v2_sparse_classes_36k_train_028308
3,938
permissive
[ { "docstring": "Constructor for the UpdateNetworkModel class", "name": "__init__", "signature": "def __init__(self, name=None, time_zone=None, tags=None, disable_my_meraki_com=None, disable_remote_status_page=None, enrollment_string=None)" }, { "docstring": "Creates an instance of this model fro...
2
stack_v2_sparse_classes_30k_train_012876
Implement the Python class `UpdateNetworkModel` described below. Class description: Implementation of the 'updateNetwork' model. TODO: type model description here. Attributes: name (string): The name of the network time_zone (string): The timezone of the network. For a list of allowed timezones, please see the 'TZ' co...
Implement the Python class `UpdateNetworkModel` described below. Class description: Implementation of the 'updateNetwork' model. TODO: type model description here. Attributes: name (string): The name of the network time_zone (string): The timezone of the network. For a list of allowed timezones, please see the 'TZ' co...
9894089eb013318243ae48869cc5130eb37f80c0
<|skeleton|> class UpdateNetworkModel: """Implementation of the 'updateNetwork' model. TODO: type model description here. Attributes: name (string): The name of the network time_zone (string): The timezone of the network. For a list of allowed timezones, please see the 'TZ' column in the table in <a target='_blank'...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UpdateNetworkModel: """Implementation of the 'updateNetwork' model. TODO: type model description here. Attributes: name (string): The name of the network time_zone (string): The timezone of the network. For a list of allowed timezones, please see the 'TZ' column in the table in <a target='_blank' href='https:...
the_stack_v2_python_sparse
meraki_sdk/models/update_network_model.py
RaulCatalano/meraki-python-sdk
train
1
1303bd42bcca07856cde5011e0d5af7d052a9990
[ "if n <= 0:\n return False\nfrom math import log10\nreturn log10(n) / log10(3) % 1 == 0", "if n <= 0:\n return False\nwhile n % 3 == 0:\n n /= 3\nreturn n == 1" ]
<|body_start_0|> if n <= 0: return False from math import log10 return log10(n) / log10(3) % 1 == 0 <|end_body_0|> <|body_start_1|> if n <= 0: return False while n % 3 == 0: n /= 3 return n == 1 <|end_body_1|>
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isPowerOfThree(self, n): """:type n: int :rtype: bool""" <|body_0|> def isPowerOfThreeLoop(self, n): """:type n: int :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> if n <= 0: return False from math imp...
stack_v2_sparse_classes_36k_train_028309
581
no_license
[ { "docstring": ":type n: int :rtype: bool", "name": "isPowerOfThree", "signature": "def isPowerOfThree(self, n)" }, { "docstring": ":type n: int :rtype: bool", "name": "isPowerOfThreeLoop", "signature": "def isPowerOfThreeLoop(self, n)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPowerOfThree(self, n): :type n: int :rtype: bool - def isPowerOfThreeLoop(self, n): :type n: int :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPowerOfThree(self, n): :type n: int :rtype: bool - def isPowerOfThreeLoop(self, n): :type n: int :rtype: bool <|skeleton|> class Solution: def isPowerOfThree(self, n)...
ac53dd9bf2c4c9d17c9dc5f7fdda32e386658fdd
<|skeleton|> class Solution: def isPowerOfThree(self, n): """:type n: int :rtype: bool""" <|body_0|> def isPowerOfThreeLoop(self, n): """:type n: int :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def isPowerOfThree(self, n): """:type n: int :rtype: bool""" if n <= 0: return False from math import log10 return log10(n) / log10(3) % 1 == 0 def isPowerOfThreeLoop(self, n): """:type n: int :rtype: bool""" if n <= 0: ret...
the_stack_v2_python_sparse
top_interview_questions/easy_collection/math/power_of_three.py
hwc1824/LeetCodeSolution
train
0
0ed90a57827aad9dfb9f88ec422ed420451b0db5
[ "cwd = os.path.join(os.path.dirname(__file__), config.vosk_model_dir)\nself.model = Model(cwd)\nlogger.info(f'Loaded speech recognition model from {cwd}')", "logger.info(f'Recognising speech for {file_name}')\nwf = wave.open(file_name, 'rb')\nif wf.getnchannels() != 1 or wf.getsampwidth() != 2 or wf.getcomptype()...
<|body_start_0|> cwd = os.path.join(os.path.dirname(__file__), config.vosk_model_dir) self.model = Model(cwd) logger.info(f'Loaded speech recognition model from {cwd}') <|end_body_0|> <|body_start_1|> logger.info(f'Recognising speech for {file_name}') wf = wave.open(file_name, '...
Simple class that uses Vosk to process a file for speech recognition
SpeechRecogniser
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SpeechRecogniser: """Simple class that uses Vosk to process a file for speech recognition""" def __init__(self): """Set the log level and load the Vosk model""" <|body_0|> def process_file(self, file_name): """Run the Vosk model on the input file :param file_name...
stack_v2_sparse_classes_36k_train_028310
2,478
permissive
[ { "docstring": "Set the log level and load the Vosk model", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Run the Vosk model on the input file :param file_name: Input wav or mp3 file :return: List of dictionaries containing: confidence, start time, end time and the pre...
2
stack_v2_sparse_classes_30k_train_005970
Implement the Python class `SpeechRecogniser` described below. Class description: Simple class that uses Vosk to process a file for speech recognition Method signatures and docstrings: - def __init__(self): Set the log level and load the Vosk model - def process_file(self, file_name): Run the Vosk model on the input ...
Implement the Python class `SpeechRecogniser` described below. Class description: Simple class that uses Vosk to process a file for speech recognition Method signatures and docstrings: - def __init__(self): Set the log level and load the Vosk model - def process_file(self, file_name): Run the Vosk model on the input ...
4252835bc69ecb54e6d0e0af49f2e77c76fd78ad
<|skeleton|> class SpeechRecogniser: """Simple class that uses Vosk to process a file for speech recognition""" def __init__(self): """Set the log level and load the Vosk model""" <|body_0|> def process_file(self, file_name): """Run the Vosk model on the input file :param file_name...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SpeechRecogniser: """Simple class that uses Vosk to process a file for speech recognition""" def __init__(self): """Set the log level and load the Vosk model""" cwd = os.path.join(os.path.dirname(__file__), config.vosk_model_dir) self.model = Model(cwd) logger.info(f'Loade...
the_stack_v2_python_sparse
audio_pipeline/audio_speech/speech_recogniser.py
AlexWimpory/video-caption
train
0
4ebf219bc008ea2b78be25e85304eed2c65ba740
[ "x = tf.expand_dims(x, axis=0)\ny = tf.expand_dims(y, axis=0)\nself.assertEqual(tf.size(tf.sets.difference(x, y)), 0, msg='Input sets are not equal.')\nself.assertEqual(tf.size(tf.sets.difference(y, x)), 0, msg='Input sets are not equal.')", "histogram_x = dict(zip(x_keys.numpy(), x_values.numpy()))\nhistogram_y ...
<|body_start_0|> x = tf.expand_dims(x, axis=0) y = tf.expand_dims(y, axis=0) self.assertEqual(tf.size(tf.sets.difference(x, y)), 0, msg='Input sets are not equal.') self.assertEqual(tf.size(tf.sets.difference(y, x)), 0, msg='Input sets are not equal.') <|end_body_0|> <|body_start_1|> ...
TestCase for Heavy Hitters.
HeavyHittersTest
[ "BSD-3-Clause", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HeavyHittersTest: """TestCase for Heavy Hitters.""" def assertSetAllEqual(self, x, y): """Assert two tensor lists contain the same set of items. Allow items to be in different order in these two lists. Args: x: A 1D tf.string y: A 1D tf.string Raises: ValueError: If x and y are diffe...
stack_v2_sparse_classes_36k_train_028311
2,180
permissive
[ { "docstring": "Assert two tensor lists contain the same set of items. Allow items to be in different order in these two lists. Args: x: A 1D tf.string y: A 1D tf.string Raises: ValueError: If x and y are different sets.", "name": "assertSetAllEqual", "signature": "def assertSetAllEqual(self, x, y)" }...
2
null
Implement the Python class `HeavyHittersTest` described below. Class description: TestCase for Heavy Hitters. Method signatures and docstrings: - def assertSetAllEqual(self, x, y): Assert two tensor lists contain the same set of items. Allow items to be in different order in these two lists. Args: x: A 1D tf.string y...
Implement the Python class `HeavyHittersTest` described below. Class description: TestCase for Heavy Hitters. Method signatures and docstrings: - def assertSetAllEqual(self, x, y): Assert two tensor lists contain the same set of items. Allow items to be in different order in these two lists. Args: x: A 1D tf.string y...
329e60fa56b87f691303638ceb9dfa1fc5083953
<|skeleton|> class HeavyHittersTest: """TestCase for Heavy Hitters.""" def assertSetAllEqual(self, x, y): """Assert two tensor lists contain the same set of items. Allow items to be in different order in these two lists. Args: x: A 1D tf.string y: A 1D tf.string Raises: ValueError: If x and y are diffe...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HeavyHittersTest: """TestCase for Heavy Hitters.""" def assertSetAllEqual(self, x, y): """Assert two tensor lists contain the same set of items. Allow items to be in different order in these two lists. Args: x: A 1D tf.string y: A 1D tf.string Raises: ValueError: If x and y are different sets."""...
the_stack_v2_python_sparse
analytics/heavy_hitters/heavy_hitters_testcase.py
google-research/federated
train
595
ace67e84967a2df346a06ca8869c0ee1e0261187
[ "super().__init__()\nself.set_XY = set_XY\nself.set_H = set_H\nself.set_D = set_D", "ovars = []\nif self.set_XY:\n ovars.append(FV.X)\n ovars.append(FV.Y)\nif self.set_H:\n ovars.append(FV.H)\nif self.set_D:\n ovars.append(FV.D)\nreturn ovars", "n_states = mdata.n_states\nn_turbines = algo.n_turbine...
<|body_start_0|> super().__init__() self.set_XY = set_XY self.set_H = set_H self.set_D = set_D <|end_body_0|> <|body_start_1|> ovars = [] if self.set_XY: ovars.append(FV.X) ovars.append(FV.Y) if self.set_H: ovars.append(FV.H) ...
Sets basic turbine data, from turbine object to farm data. Attributes ---------- set_XY: bool Flag for (x,y) data set_H: bool Flag for height data set_D: bool Flag for rotor diameter data :group: models.turbine_models
SetXYHD
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SetXYHD: """Sets basic turbine data, from turbine object to farm data. Attributes ---------- set_XY: bool Flag for (x,y) data set_H: bool Flag for height data set_D: bool Flag for rotor diameter data :group: models.turbine_models""" def __init__(self, set_XY=True, set_H=True, set_D=True): ...
stack_v2_sparse_classes_36k_train_028312
3,492
permissive
[ { "docstring": "Constructor. Parameters ---------- set_XY: bool Flag for (x,y) data set_H: bool Flag for height data set_D: bool Flag for rotor diameter data", "name": "__init__", "signature": "def __init__(self, set_XY=True, set_H=True, set_D=True)" }, { "docstring": "The variables which are be...
3
stack_v2_sparse_classes_30k_train_005883
Implement the Python class `SetXYHD` described below. Class description: Sets basic turbine data, from turbine object to farm data. Attributes ---------- set_XY: bool Flag for (x,y) data set_H: bool Flag for height data set_D: bool Flag for rotor diameter data :group: models.turbine_models Method signatures and docst...
Implement the Python class `SetXYHD` described below. Class description: Sets basic turbine data, from turbine object to farm data. Attributes ---------- set_XY: bool Flag for (x,y) data set_H: bool Flag for height data set_D: bool Flag for rotor diameter data :group: models.turbine_models Method signatures and docst...
65b01a4d33c40065d1b19900d8238b173700653c
<|skeleton|> class SetXYHD: """Sets basic turbine data, from turbine object to farm data. Attributes ---------- set_XY: bool Flag for (x,y) data set_H: bool Flag for height data set_D: bool Flag for rotor diameter data :group: models.turbine_models""" def __init__(self, set_XY=True, set_H=True, set_D=True): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SetXYHD: """Sets basic turbine data, from turbine object to farm data. Attributes ---------- set_XY: bool Flag for (x,y) data set_H: bool Flag for height data set_D: bool Flag for rotor diameter data :group: models.turbine_models""" def __init__(self, set_XY=True, set_H=True, set_D=True): """Cons...
the_stack_v2_python_sparse
foxes/models/turbine_models/set_XYHD.py
FraunhoferIWES/foxes
train
14
d499169c3009524d5e7b99176cbdbdeb6839757b
[ "if not metric_name:\n raise KeyError(\"'metric_name' parameter is required\")\nreturn super(Metadata, cls).get(metric_name)", "if not metric_name:\n raise KeyError(\"'metric_name' parameter is required\")\nreturn super(Metadata, cls).update(id=metric_name, **params)" ]
<|body_start_0|> if not metric_name: raise KeyError("'metric_name' parameter is required") return super(Metadata, cls).get(metric_name) <|end_body_0|> <|body_start_1|> if not metric_name: raise KeyError("'metric_name' parameter is required") return super(Metadata...
A wrapper around Metric Metadata HTTP API
Metadata
[ "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Metadata: """A wrapper around Metric Metadata HTTP API""" def get(cls, metric_name): """Get metadata information on an existing Datadog metric param metric_name: metric name (ex. system.cpu.idle) :returns: Dictionary representing the API's JSON response""" <|body_0|> def...
stack_v2_sparse_classes_36k_train_028313
2,290
permissive
[ { "docstring": "Get metadata information on an existing Datadog metric param metric_name: metric name (ex. system.cpu.idle) :returns: Dictionary representing the API's JSON response", "name": "get", "signature": "def get(cls, metric_name)" }, { "docstring": "Update metadata fields for an existin...
2
null
Implement the Python class `Metadata` described below. Class description: A wrapper around Metric Metadata HTTP API Method signatures and docstrings: - def get(cls, metric_name): Get metadata information on an existing Datadog metric param metric_name: metric name (ex. system.cpu.idle) :returns: Dictionary representi...
Implement the Python class `Metadata` described below. Class description: A wrapper around Metric Metadata HTTP API Method signatures and docstrings: - def get(cls, metric_name): Get metadata information on an existing Datadog metric param metric_name: metric name (ex. system.cpu.idle) :returns: Dictionary representi...
11a38d0c8d6b156758e7500500d706b7159d18ed
<|skeleton|> class Metadata: """A wrapper around Metric Metadata HTTP API""" def get(cls, metric_name): """Get metadata information on an existing Datadog metric param metric_name: metric name (ex. system.cpu.idle) :returns: Dictionary representing the API's JSON response""" <|body_0|> def...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Metadata: """A wrapper around Metric Metadata HTTP API""" def get(cls, metric_name): """Get metadata information on an existing Datadog metric param metric_name: metric name (ex. system.cpu.idle) :returns: Dictionary representing the API's JSON response""" if not metric_name: ...
the_stack_v2_python_sparse
datadog/api/metadata.py
DataDog/datadogpy
train
602
4a486f329c9014947d1ac47a6f97bb47e9b11bf8
[ "from pytz import timezone\nfrom os import environ\nconfig = TraderBase.get_config()\ntry:\n return timezone(config['autotrader']['time_zone'])\nexcept (configparser.NoSectionError, configparser.NoOptionError, KeyError, TypeError):\n if environ.get('TZ') is not None:\n return timezone(os.environ['TZ'])...
<|body_start_0|> from pytz import timezone from os import environ config = TraderBase.get_config() try: return timezone(config['autotrader']['time_zone']) except (configparser.NoSectionError, configparser.NoOptionError, KeyError, TypeError): if environ.get...
Helper class for logging and config parsing
TraderBase
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TraderBase: """Helper class for logging and config parsing""" def get_timezone(): """Return configured timezone or europe berlin as default :return:""" <|body_0|> def setup_logger(name: str): """Setup the autotrader standard logger :param name: name of logger :re...
stack_v2_sparse_classes_36k_train_028314
2,924
no_license
[ { "docstring": "Return configured timezone or europe berlin as default :return:", "name": "get_timezone", "signature": "def get_timezone()" }, { "docstring": "Setup the autotrader standard logger :param name: name of logger :return: instance of logger", "name": "setup_logger", "signature...
3
null
Implement the Python class `TraderBase` described below. Class description: Helper class for logging and config parsing Method signatures and docstrings: - def get_timezone(): Return configured timezone or europe berlin as default :return: - def setup_logger(name: str): Setup the autotrader standard logger :param nam...
Implement the Python class `TraderBase` described below. Class description: Helper class for logging and config parsing Method signatures and docstrings: - def get_timezone(): Return configured timezone or europe berlin as default :return: - def setup_logger(name: str): Setup the autotrader standard logger :param nam...
a2b486d5941dbee01272c49e6e63e289edcf9966
<|skeleton|> class TraderBase: """Helper class for logging and config parsing""" def get_timezone(): """Return configured timezone or europe berlin as default :return:""" <|body_0|> def setup_logger(name: str): """Setup the autotrader standard logger :param name: name of logger :re...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TraderBase: """Helper class for logging and config parsing""" def get_timezone(): """Return configured timezone or europe berlin as default :return:""" from pytz import timezone from os import environ config = TraderBase.get_config() try: return timezon...
the_stack_v2_python_sparse
autotrader/base/trader_base.py
SlashGordon/autotrader
train
1
93150c9d103e72dec26b3936ef4bb6ac93591dac
[ "self.regularization = regularization\nself.clip_margin = clip_margin\nself.pano_pad = pano_pad\nself.spline_degree = spline_degree", "aligned_results = bspline_warp(thetas, image, self.spline_degree, regularization=self.regularization, pano_pad=self.pano_pad)\nif self.pano_pad:\n clipped_results = aligned_res...
<|body_start_0|> self.regularization = regularization self.clip_margin = clip_margin self.pano_pad = pano_pad self.spline_degree = spline_degree <|end_body_0|> <|body_start_1|> aligned_results = bspline_warp(thetas, image, self.spline_degree, regularization=self.regularization, ...
A class for aligning a set of images using bspline warps.
ImageAlignment
[ "Apache-2.0", "CC-BY-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ImageAlignment: """A class for aligning a set of images using bspline warps.""" def __init__(self, regularization=0.3, clip_margin=32, pano_pad=True, spline_degree=3): """Initializes a layer that warp images based on alignment parameters. Args: regularization: (float): A regularizati...
stack_v2_sparse_classes_36k_train_028315
10,152
permissive
[ { "docstring": "Initializes a layer that warp images based on alignment parameters. Args: regularization: (float): A regularization, ranging from [0, 1], for alignment control points clip_margin (int): For non-panoramic padding dimensions, controls how many edge pixels to crop. Useful for removing warping artif...
2
null
Implement the Python class `ImageAlignment` described below. Class description: A class for aligning a set of images using bspline warps. Method signatures and docstrings: - def __init__(self, regularization=0.3, clip_margin=32, pano_pad=True, spline_degree=3): Initializes a layer that warp images based on alignment ...
Implement the Python class `ImageAlignment` described below. Class description: A class for aligning a set of images using bspline warps. Method signatures and docstrings: - def __init__(self, regularization=0.3, clip_margin=32, pano_pad=True, spline_degree=3): Initializes a layer that warp images based on alignment ...
5573d9c5822f4e866b6692769963ae819cb3f10d
<|skeleton|> class ImageAlignment: """A class for aligning a set of images using bspline warps.""" def __init__(self, regularization=0.3, clip_margin=32, pano_pad=True, spline_degree=3): """Initializes a layer that warp images based on alignment parameters. Args: regularization: (float): A regularizati...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ImageAlignment: """A class for aligning a set of images using bspline warps.""" def __init__(self, regularization=0.3, clip_margin=32, pano_pad=True, spline_degree=3): """Initializes a layer that warp images based on alignment parameters. Args: regularization: (float): A regularization, ranging f...
the_stack_v2_python_sparse
factorize_a_city/libs/image_alignment.py
Jimmy-INL/google-research
train
1
57051fc750b20da7b5ba99135a2ae2881bc00d26
[ "filepath = cls._convert_filepath(filepath)\nif filepath.suffix == '.pdb':\n return cls._from_pdb_file(filepath)\nelse:\n raise ValueError(f'The {format} format is not supported or invalid.')", "parser = PDBParser()\nstructure = parser.get_structure('', pdb_file)\nreturn structure" ]
<|body_start_0|> filepath = cls._convert_filepath(filepath) if filepath.suffix == '.pdb': return cls._from_pdb_file(filepath) else: raise ValueError(f'The {format} format is not supported or invalid.') <|end_body_0|> <|body_start_1|> parser = PDBParser() ...
Parse a structure as a biopython structure object.
Biopython
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Biopython: """Parse a structure as a biopython structure object.""" def from_file(cls, filepath): """Load structures as biopython structure object from file. Parameters ---------- filepath : str or pathlib.Path Path to structure file: pdb files only. Returns ------- Bio.PDB.Structure...
stack_v2_sparse_classes_36k_train_028316
1,330
permissive
[ { "docstring": "Load structures as biopython structure object from file. Parameters ---------- filepath : str or pathlib.Path Path to structure file: pdb files only. Returns ------- Bio.PDB.Structure.Structure Structure as biopython structure object.", "name": "from_file", "signature": "def from_file(cl...
2
stack_v2_sparse_classes_30k_train_003733
Implement the Python class `Biopython` described below. Class description: Parse a structure as a biopython structure object. Method signatures and docstrings: - def from_file(cls, filepath): Load structures as biopython structure object from file. Parameters ---------- filepath : str or pathlib.Path Path to structur...
Implement the Python class `Biopython` described below. Class description: Parse a structure as a biopython structure object. Method signatures and docstrings: - def from_file(cls, filepath): Load structures as biopython structure object from file. Parameters ---------- filepath : str or pathlib.Path Path to structur...
c76e87c4fdcb822dfc025e6cb87c34c9e17505d2
<|skeleton|> class Biopython: """Parse a structure as a biopython structure object.""" def from_file(cls, filepath): """Load structures as biopython structure object from file. Parameters ---------- filepath : str or pathlib.Path Path to structure file: pdb files only. Returns ------- Bio.PDB.Structure...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Biopython: """Parse a structure as a biopython structure object.""" def from_file(cls, filepath): """Load structures as biopython structure object from file. Parameters ---------- filepath : str or pathlib.Path Path to structure file: pdb files only. Returns ------- Bio.PDB.Structure.Structure St...
the_stack_v2_python_sparse
opencadd/io/biopython.py
volkamerlab/opencadd
train
62
23050faaaaca4daad88eb1029b3ac34fd2f90920
[ "attribution_key = metrics_for_slice_pb2.AttributionsKey()\nif self.name:\n attribution_key.name = self.name\nif self.model_name:\n attribution_key.model_name = self.model_name\nif self.output_name:\n attribution_key.output_name = self.output_name\nif self.sub_key:\n attribution_key.sub_key.CopyFrom(sel...
<|body_start_0|> attribution_key = metrics_for_slice_pb2.AttributionsKey() if self.name: attribution_key.name = self.name if self.model_name: attribution_key.model_name = self.model_name if self.output_name: attribution_key.output_name = self.output_na...
An AttributionsKey is a metric key uniquely identifying attributions.
AttributionsKey
[ "BSD-3-Clause", "MIT", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AttributionsKey: """An AttributionsKey is a metric key uniquely identifying attributions.""" def to_proto(self) -> metrics_for_slice_pb2.AttributionsKey: """Converts key to proto.""" <|body_0|> def from_proto(pb: metrics_for_slice_pb2.AttributionsKey) -> 'AttributionsKey...
stack_v2_sparse_classes_36k_train_028317
44,385
permissive
[ { "docstring": "Converts key to proto.", "name": "to_proto", "signature": "def to_proto(self) -> metrics_for_slice_pb2.AttributionsKey" }, { "docstring": "Configures class from proto.", "name": "from_proto", "signature": "def from_proto(pb: metrics_for_slice_pb2.AttributionsKey) -> 'Attr...
2
stack_v2_sparse_classes_30k_train_000533
Implement the Python class `AttributionsKey` described below. Class description: An AttributionsKey is a metric key uniquely identifying attributions. Method signatures and docstrings: - def to_proto(self) -> metrics_for_slice_pb2.AttributionsKey: Converts key to proto. - def from_proto(pb: metrics_for_slice_pb2.Attr...
Implement the Python class `AttributionsKey` described below. Class description: An AttributionsKey is a metric key uniquely identifying attributions. Method signatures and docstrings: - def to_proto(self) -> metrics_for_slice_pb2.AttributionsKey: Converts key to proto. - def from_proto(pb: metrics_for_slice_pb2.Attr...
ee0d8eff562bfe068a3ffdc4da0472cc90adaf41
<|skeleton|> class AttributionsKey: """An AttributionsKey is a metric key uniquely identifying attributions.""" def to_proto(self) -> metrics_for_slice_pb2.AttributionsKey: """Converts key to proto.""" <|body_0|> def from_proto(pb: metrics_for_slice_pb2.AttributionsKey) -> 'AttributionsKey...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AttributionsKey: """An AttributionsKey is a metric key uniquely identifying attributions.""" def to_proto(self) -> metrics_for_slice_pb2.AttributionsKey: """Converts key to proto.""" attribution_key = metrics_for_slice_pb2.AttributionsKey() if self.name: attribution_ke...
the_stack_v2_python_sparse
tensorflow_model_analysis/metrics/metric_types.py
tensorflow/model-analysis
train
1,200
18fbd2fd25c60e0dcfcf90fcab7a2a0d7434493b
[ "self.name = None\nself.training_data = None\nself.test_data = None\nself.entities = None\nself.features_dim = features_dim\nself.feat_normalize = normalize\nself.target_transform = target_transform", "if self.feat_normalize:\n for i in range(len(self.entities)):\n if isspmatrix_csr(self.entities[i]):\n...
<|body_start_0|> self.name = None self.training_data = None self.test_data = None self.entities = None self.features_dim = features_dim self.feat_normalize = normalize self.target_transform = target_transform <|end_body_0|> <|body_start_1|> if self.feat_n...
Base class that holds necessary (minimal) information needed
Dataset
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Dataset: """Base class that holds necessary (minimal) information needed""" def __init__(self, name, features_dim=0, normalize=False, target_transform=''): """Initialize parameters Args: name (str): Name of the dataset features_dim (uint): Dimension of the features. If not 0, PCA is ...
stack_v2_sparse_classes_36k_train_028318
8,650
permissive
[ { "docstring": "Initialize parameters Args: name (str): Name of the dataset features_dim (uint): Dimension of the features. If not 0, PCA is performed on the features as the dimensionality reduction technique normalize (bool): Normalize the features target_transform (str): Transform the target values. Current o...
4
stack_v2_sparse_classes_30k_train_016496
Implement the Python class `Dataset` described below. Class description: Base class that holds necessary (minimal) information needed Method signatures and docstrings: - def __init__(self, name, features_dim=0, normalize=False, target_transform=''): Initialize parameters Args: name (str): Name of the dataset features...
Implement the Python class `Dataset` described below. Class description: Base class that holds necessary (minimal) information needed Method signatures and docstrings: - def __init__(self, name, features_dim=0, normalize=False, target_transform=''): Initialize parameters Args: name (str): Name of the dataset features...
787ae309ec78a9b2b1f58931931cb117affc4ea9
<|skeleton|> class Dataset: """Base class that holds necessary (minimal) information needed""" def __init__(self, name, features_dim=0, normalize=False, target_transform=''): """Initialize parameters Args: name (str): Name of the dataset features_dim (uint): Dimension of the features. If not 0, PCA is ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Dataset: """Base class that holds necessary (minimal) information needed""" def __init__(self, name, features_dim=0, normalize=False, target_transform=''): """Initialize parameters Args: name (str): Name of the dataset features_dim (uint): Dimension of the features. If not 0, PCA is performed on ...
the_stack_v2_python_sparse
recommenders/models/geoimc/geoimc_data.py
DaniBunny/recommenders
train
1
e0c3d7ae4f53489584f7a75333680534438cc5c1
[ "self.grid_r = r - 1\nself.grid_c = c - 1\nself.stop_cells = set(stop_cells)", "path = [(0, 0)]\nwent_right: set = set()\nwent_down: set = set()\nr = 0\nc = 0\nwhile (r, c) != (self.grid_r, self.grid_c):\n if c < self.grid_c and (r, c) not in went_right and ((r, c + 1) not in self.stop_cells):\n went_ri...
<|body_start_0|> self.grid_r = r - 1 self.grid_c = c - 1 self.stop_cells = set(stop_cells) <|end_body_0|> <|body_start_1|> path = [(0, 0)] went_right: set = set() went_down: set = set() r = 0 c = 0 while (r, c) != (self.grid_r, self.grid_c): ...
8.2 Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns. The robot can only move in two directions, right and down, but certain cells are "off limits" such that the robot cannot step on them. Design an algorithm to find a path for the robot from the top left to the bottom...
RobotInAGrid
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RobotInAGrid: """8.2 Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns. The robot can only move in two directions, right and down, but certain cells are "off limits" such that the robot cannot step on them. Design an algorithm to find a path for t...
stack_v2_sparse_classes_36k_train_028319
1,849
no_license
[ { "docstring": ":param r: rows in a grid :param c: cells in a grid", "name": "__init__", "signature": "def __init__(self, stop_cells, r, c)" }, { "docstring": "Algorithm to find a path for the robot from the top left to the bottom right. Algo: step right, if not possible, step left, if not possi...
2
null
Implement the Python class `RobotInAGrid` described below. Class description: 8.2 Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns. The robot can only move in two directions, right and down, but certain cells are "off limits" such that the robot cannot step on them. D...
Implement the Python class `RobotInAGrid` described below. Class description: 8.2 Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns. The robot can only move in two directions, right and down, but certain cells are "off limits" such that the robot cannot step on them. D...
8ae84f276cd07ffdb9b742569a5e32809ecc6b29
<|skeleton|> class RobotInAGrid: """8.2 Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns. The robot can only move in two directions, right and down, but certain cells are "off limits" such that the robot cannot step on them. Design an algorithm to find a path for t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RobotInAGrid: """8.2 Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns. The robot can only move in two directions, right and down, but certain cells are "off limits" such that the robot cannot step on them. Design an algorithm to find a path for the robot from...
the_stack_v2_python_sparse
pyquiz/ctci/dynamic/RobotInAGrid.py
DmitryPukhov/pyquiz
train
0
461d39a26047af0f700a58e6cd1c317e7ce41d00
[ "header = json.dumps({'typ': 'JWT', 'alg': 'BLK2B'}).encode('utf-8')\nhenc = base58.b58encode_check(header).decode()\npayload = json.dumps(data).encode('utf-8')\npenc = base58.b58encode_check(payload).decode()\nhdata = henc + '.' + penc\nd = hmac.new(key, hdata.encode('utf-8'), digestmod=hashlib.blake2b)\ndig = d.d...
<|body_start_0|> header = json.dumps({'typ': 'JWT', 'alg': 'BLK2B'}).encode('utf-8') henc = base58.b58encode_check(header).decode() payload = json.dumps(data).encode('utf-8') penc = base58.b58encode_check(payload).decode() hdata = henc + '.' + penc d = hmac.new(key, hdata...
JWT
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JWT: def create_signed_token(cls, key, data): """Create a complete JWT token. Exclusively uses blake2b HMAC.""" <|body_0|> def verify_signed_token(cls, key, token): """Decodes the payload in the token and returns a tuple whose first value is a boolean indicating whet...
stack_v2_sparse_classes_36k_train_028320
2,771
permissive
[ { "docstring": "Create a complete JWT token. Exclusively uses blake2b HMAC.", "name": "create_signed_token", "signature": "def create_signed_token(cls, key, data)" }, { "docstring": "Decodes the payload in the token and returns a tuple whose first value is a boolean indicating whether the signat...
2
stack_v2_sparse_classes_30k_train_002679
Implement the Python class `JWT` described below. Class description: Implement the JWT class. Method signatures and docstrings: - def create_signed_token(cls, key, data): Create a complete JWT token. Exclusively uses blake2b HMAC. - def verify_signed_token(cls, key, token): Decodes the payload in the token and return...
Implement the Python class `JWT` described below. Class description: Implement the JWT class. Method signatures and docstrings: - def create_signed_token(cls, key, data): Create a complete JWT token. Exclusively uses blake2b HMAC. - def verify_signed_token(cls, key, token): Decodes the payload in the token and return...
94597af5ab5736bdb995a97b3bc65182ca38ee51
<|skeleton|> class JWT: def create_signed_token(cls, key, data): """Create a complete JWT token. Exclusively uses blake2b HMAC.""" <|body_0|> def verify_signed_token(cls, key, token): """Decodes the payload in the token and returns a tuple whose first value is a boolean indicating whet...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class JWT: def create_signed_token(cls, key, data): """Create a complete JWT token. Exclusively uses blake2b HMAC.""" header = json.dumps({'typ': 'JWT', 'alg': 'BLK2B'}).encode('utf-8') henc = base58.b58encode_check(header).decode() payload = json.dumps(data).encode('utf-8') ...
the_stack_v2_python_sparse
hikka/auth.py
obasys/hikka
train
0
eddb444106c21e612a6e829d685c52c95d96f67b
[ "super(BinaryRealIndividual, self).__init__(genes, parent, statistic)\nself._phenome = None\nif isinstance(parent, BinaryRealIndividual):\n self.bits_per_value = parent.bits_per_value\n self.lowest = parent.lowest\n self.highest = parent.highest\n self.encoding = parent.encoding\nelse:\n self.bits_pe...
<|body_start_0|> super(BinaryRealIndividual, self).__init__(genes, parent, statistic) self._phenome = None if isinstance(parent, BinaryRealIndividual): self.bits_per_value = parent.bits_per_value self.lowest = parent.lowest self.highest = parent.highest ...
An `Individual` for binary-valued genomes and real-valued phenomes. Binary values are grouped into real-valued parameters, summed and scaled.
BinaryRealIndividual
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BinaryRealIndividual: """An `Individual` for binary-valued genomes and real-valued phenomes. Binary values are grouped into real-valued parameters, summed and scaled.""" def __init__(self, genes, parent, bits_per_value=None, lowest=0.0, highest=1.0, encoding=None, statistic=None): ""...
stack_v2_sparse_classes_36k_train_028321
14,844
permissive
[ { "docstring": "Initialises a new individual. :Parameters: genes : iterable The sequence of genes that make up the new individual. parent : `BinaryRealIndividual` or `BinarySpecies` Either the `BinaryRealIndividual` that was used to generate the new individual, or the `BinarySpecies` descriptor that defines the...
3
stack_v2_sparse_classes_30k_train_019187
Implement the Python class `BinaryRealIndividual` described below. Class description: An `Individual` for binary-valued genomes and real-valued phenomes. Binary values are grouped into real-valued parameters, summed and scaled. Method signatures and docstrings: - def __init__(self, genes, parent, bits_per_value=None,...
Implement the Python class `BinaryRealIndividual` described below. Class description: An `Individual` for binary-valued genomes and real-valued phenomes. Binary values are grouped into real-valued parameters, summed and scaled. Method signatures and docstrings: - def __init__(self, genes, parent, bits_per_value=None,...
c1c64237697115ea3137bc854c0dfdf8b456b0dd
<|skeleton|> class BinaryRealIndividual: """An `Individual` for binary-valued genomes and real-valued phenomes. Binary values are grouped into real-valued parameters, summed and scaled.""" def __init__(self, genes, parent, bits_per_value=None, lowest=0.0, highest=1.0, encoding=None, statistic=None): ""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BinaryRealIndividual: """An `Individual` for binary-valued genomes and real-valued phenomes. Binary values are grouped into real-valued parameters, summed and scaled.""" def __init__(self, genes, parent, bits_per_value=None, lowest=0.0, highest=1.0, encoding=None, statistic=None): """Initialises ...
the_stack_v2_python_sparse
esec/esec/species/binary_real.py
zooba/esec
train
1
2dfffcb5c5ea916feaf1a1825dba6e8e4ca68d37
[ "self.assertTrue(utils.IsSubclass(int, int))\nself.assertTrue(utils.IsSubclass(bool, int))\nself.assertTrue(utils.IsSubclass(str, (str, basestring)))\nself.assertFalse(utils.IsSubclass(int, bool))\nself.assertFalse(utils.IsSubclass(int, None))", "self.assertRaises(AttributeError, utils._DictToTuple, None)\n\nclas...
<|body_start_0|> self.assertTrue(utils.IsSubclass(int, int)) self.assertTrue(utils.IsSubclass(bool, int)) self.assertTrue(utils.IsSubclass(str, (str, basestring))) self.assertFalse(utils.IsSubclass(int, bool)) self.assertFalse(utils.IsSubclass(int, None)) <|end_body_0|> <|body_s...
Comprehensive test for the endpoints_proto_datastore.utils module.
UtilsTests
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UtilsTests: """Comprehensive test for the endpoints_proto_datastore.utils module.""" def testIsSubclass(self): """Tests the utils.IsSubclass method.""" <|body_0|> def testDictToTuple(self): """Tests the utils._DictToTuple method.""" <|body_1|> def te...
stack_v2_sparse_classes_36k_train_028322
2,058
permissive
[ { "docstring": "Tests the utils.IsSubclass method.", "name": "testIsSubclass", "signature": "def testIsSubclass(self)" }, { "docstring": "Tests the utils._DictToTuple method.", "name": "testDictToTuple", "signature": "def testDictToTuple(self)" }, { "docstring": "Tests the utils....
3
stack_v2_sparse_classes_30k_train_008351
Implement the Python class `UtilsTests` described below. Class description: Comprehensive test for the endpoints_proto_datastore.utils module. Method signatures and docstrings: - def testIsSubclass(self): Tests the utils.IsSubclass method. - def testDictToTuple(self): Tests the utils._DictToTuple method. - def testGe...
Implement the Python class `UtilsTests` described below. Class description: Comprehensive test for the endpoints_proto_datastore.utils module. Method signatures and docstrings: - def testIsSubclass(self): Tests the utils.IsSubclass method. - def testDictToTuple(self): Tests the utils._DictToTuple method. - def testGe...
37e0136ab61a99a8cd25ef264c2d5f8f024e8f6f
<|skeleton|> class UtilsTests: """Comprehensive test for the endpoints_proto_datastore.utils module.""" def testIsSubclass(self): """Tests the utils.IsSubclass method.""" <|body_0|> def testDictToTuple(self): """Tests the utils._DictToTuple method.""" <|body_1|> def te...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UtilsTests: """Comprehensive test for the endpoints_proto_datastore.utils module.""" def testIsSubclass(self): """Tests the utils.IsSubclass method.""" self.assertTrue(utils.IsSubclass(int, int)) self.assertTrue(utils.IsSubclass(bool, int)) self.assertTrue(utils.IsSubclass...
the_stack_v2_python_sparse
lib/endpoints_proto_datastore/utils_test.py
uetopia/metagame
train
2
091df8021a7aefc4e82ee59844e89e232a859dac
[ "if k <= 1:\n return 0\nprod = 1\nans = left = 0\nfor right, val in enumerate(nums):\n prod *= val\n while prod >= k:\n prod /= nums[left]\n left += 1\n ans += right - left + 1\nreturn ans", "count = 0\nlast = 0\nfor i in range(len(nums)):\n if nums[i] >= k:\n last = i\n ...
<|body_start_0|> if k <= 1: return 0 prod = 1 ans = left = 0 for right, val in enumerate(nums): prod *= val while prod >= k: prod /= nums[left] left += 1 ans += right - left + 1 return ans <|end_body_...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def numSubarrayProductLessThanK(self, nums, k): """:type nums: List[int] :type k: int :rtype: int""" <|body_0|> def numSubarrayProductLessThanK0(self, nums, k): """:type nums: List[int] :type k: int :rtype: int""" <|body_1|> <|end_skeleton|> <|bod...
stack_v2_sparse_classes_36k_train_028323
1,743
no_license
[ { "docstring": ":type nums: List[int] :type k: int :rtype: int", "name": "numSubarrayProductLessThanK", "signature": "def numSubarrayProductLessThanK(self, nums, k)" }, { "docstring": ":type nums: List[int] :type k: int :rtype: int", "name": "numSubarrayProductLessThanK0", "signature": "...
2
stack_v2_sparse_classes_30k_train_011647
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numSubarrayProductLessThanK(self, nums, k): :type nums: List[int] :type k: int :rtype: int - def numSubarrayProductLessThanK0(self, nums, k): :type nums: List[int] :type k: i...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numSubarrayProductLessThanK(self, nums, k): :type nums: List[int] :type k: int :rtype: int - def numSubarrayProductLessThanK0(self, nums, k): :type nums: List[int] :type k: i...
6e18c5d257840489cc3fb1079ae3804c743982a4
<|skeleton|> class Solution: def numSubarrayProductLessThanK(self, nums, k): """:type nums: List[int] :type k: int :rtype: int""" <|body_0|> def numSubarrayProductLessThanK0(self, nums, k): """:type nums: List[int] :type k: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def numSubarrayProductLessThanK(self, nums, k): """:type nums: List[int] :type k: int :rtype: int""" if k <= 1: return 0 prod = 1 ans = left = 0 for right, val in enumerate(nums): prod *= val while prod >= k: ...
the_stack_v2_python_sparse
剑指 Offer II 009. 乘积小于 K 的子数组.py
yangyuxiang1996/leetcode
train
0
575b7c659222099eae5f4e14803230830ac607d1
[ "attribute_list = ['task_type', 'api_id', 'db_host', 'db_port', 'genapi_version', 'log_level', 'entities', 'api_key']\nself.config = config\nsuper(DeployTask, self).__init__(message, attribute_list, config)", "self.task_type = self.get_task_type()\nself.api_id = self.message['api_id']\nself.db_host = self.message...
<|body_start_0|> attribute_list = ['task_type', 'api_id', 'db_host', 'db_port', 'genapi_version', 'log_level', 'entities', 'api_key'] self.config = config super(DeployTask, self).__init__(message, attribute_list, config) <|end_body_0|> <|body_start_1|> self.task_type = self.get_task_typ...
Deploy task definition
DeployTask
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DeployTask: """Deploy task definition""" def __init__(self, message, config): """Initialize the Deploy task""" <|body_0|> def parse_parameters(self): """Read out all parameters needed to run the deploy task { “task_type”: ”DEPLOY”, “api_id”: “88sdhv98shdvlh123”, ...
stack_v2_sparse_classes_36k_train_028324
3,395
no_license
[ { "docstring": "Initialize the Deploy task", "name": "__init__", "signature": "def __init__(self, message, config)" }, { "docstring": "Read out all parameters needed to run the deploy task { “task_type”: ”DEPLOY”, “api_id”: “88sdhv98shdvlh123”, “db_host”: “db1.apitrary.net”, “db_port”: 8098, “ge...
4
stack_v2_sparse_classes_30k_train_008302
Implement the Python class `DeployTask` described below. Class description: Deploy task definition Method signatures and docstrings: - def __init__(self, message, config): Initialize the Deploy task - def parse_parameters(self): Read out all parameters needed to run the deploy task { “task_type”: ”DEPLOY”, “api_id”: ...
Implement the Python class `DeployTask` described below. Class description: Deploy task definition Method signatures and docstrings: - def __init__(self, message, config): Initialize the Deploy task - def parse_parameters(self): Read out all parameters needed to run the deploy task { “task_type”: ”DEPLOY”, “api_id”: ...
5f45763782a68d1ed755166c4f6bb2e62e7735b6
<|skeleton|> class DeployTask: """Deploy task definition""" def __init__(self, message, config): """Initialize the Deploy task""" <|body_0|> def parse_parameters(self): """Read out all parameters needed to run the deploy task { “task_type”: ”DEPLOY”, “api_id”: “88sdhv98shdvlh123”, ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DeployTask: """Deploy task definition""" def __init__(self, message, config): """Initialize the Deploy task""" attribute_list = ['task_type', 'api_id', 'db_host', 'db_port', 'genapi_version', 'log_level', 'entities', 'api_key'] self.config = config super(DeployTask, self)....
the_stack_v2_python_sparse
deployr/app_deployr/models/deploy_task.py
otype/deployr
train
0
6263c5241b349ad0bdb2c225fa8c3f058aa31070
[ "response = self.client.get('/products/')\nself.assertEqual(response.status_code, 302)\nself.assertEqual(response.url, '/accounts/login/?next=/products/')", "response = self.client.get('/products/Pints/')\nself.assertEqual(response.status_code, 302)\nself.assertEqual(response.url, '/accounts/login/?next=/products...
<|body_start_0|> response = self.client.get('/products/') self.assertEqual(response.status_code, 302) self.assertEqual(response.url, '/accounts/login/?next=/products/') <|end_body_0|> <|body_start_1|> response = self.client.get('/products/Pints/') self.assertEqual(response.statu...
Test for cart view when user is logged out
TestProductViewsLoggedOut
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestProductViewsLoggedOut: """Test for cart view when user is logged out""" def test_all_products_view_logged_out(self): """Check that the all products view redirects to login page when logged out""" <|body_0|> def test_filtered_products_view_logged_out(self): ""...
stack_v2_sparse_classes_36k_train_028325
2,945
no_license
[ { "docstring": "Check that the all products view redirects to login page when logged out", "name": "test_all_products_view_logged_out", "signature": "def test_all_products_view_logged_out(self)" }, { "docstring": "Check that the filter products views redirects to login page when logged out", ...
3
null
Implement the Python class `TestProductViewsLoggedOut` described below. Class description: Test for cart view when user is logged out Method signatures and docstrings: - def test_all_products_view_logged_out(self): Check that the all products view redirects to login page when logged out - def test_filtered_products_v...
Implement the Python class `TestProductViewsLoggedOut` described below. Class description: Test for cart view when user is logged out Method signatures and docstrings: - def test_all_products_view_logged_out(self): Check that the all products view redirects to login page when logged out - def test_filtered_products_v...
e052a6f95566322b95cc41a3dfd730e382a6863e
<|skeleton|> class TestProductViewsLoggedOut: """Test for cart view when user is logged out""" def test_all_products_view_logged_out(self): """Check that the all products view redirects to login page when logged out""" <|body_0|> def test_filtered_products_view_logged_out(self): ""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestProductViewsLoggedOut: """Test for cart view when user is logged out""" def test_all_products_view_logged_out(self): """Check that the all products view redirects to login page when logged out""" response = self.client.get('/products/') self.assertEqual(response.status_code, 3...
the_stack_v2_python_sparse
products/test_views.py
Code-Institute-Submissions/milestone-project-84
train
0
641545540bcfb7496d5a8ce06bae2ef61738eee0
[ "tp = type(e)\ntb = e.__traceback__\ntraceback_str = 'Traceback (most recent call last):\\n' + ''.join(traceback.format_tb(tb))\ntry:\n attributes = e.get_attributes()\nexcept AttributeError:\n attributes = {}\nreturn (tp.__name__, traceback_str, sy.serde.msgpack.serde._simplify(worker, attributes))", "erro...
<|body_start_0|> tp = type(e) tb = e.__traceback__ traceback_str = 'Traceback (most recent call last):\n' + ''.join(traceback.format_tb(tb)) try: attributes = e.get_attributes() except AttributeError: attributes = {} return (tp.__name__, traceback_...
Raised when calling send on a tensor which does not allow send to be called on it. This can happen do to sensitivity being too high
SendNotPermittedError
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SendNotPermittedError: """Raised when calling send on a tensor which does not allow send to be called on it. This can happen do to sensitivity being too high""" def simplify(worker: 'sy.workers.AbstractWorker', e): """Serialize information about an Exception which was raised to forwa...
stack_v2_sparse_classes_36k_train_028326
15,166
permissive
[ { "docstring": "Serialize information about an Exception which was raised to forward it", "name": "simplify", "signature": "def simplify(worker: 'sy.workers.AbstractWorker', e)" }, { "docstring": "Detail and re-raise an Exception forwarded by another worker", "name": "detail", "signature...
2
stack_v2_sparse_classes_30k_train_018627
Implement the Python class `SendNotPermittedError` described below. Class description: Raised when calling send on a tensor which does not allow send to be called on it. This can happen do to sensitivity being too high Method signatures and docstrings: - def simplify(worker: 'sy.workers.AbstractWorker', e): Serialize...
Implement the Python class `SendNotPermittedError` described below. Class description: Raised when calling send on a tensor which does not allow send to be called on it. This can happen do to sensitivity being too high Method signatures and docstrings: - def simplify(worker: 'sy.workers.AbstractWorker', e): Serialize...
cc4765bed880ad38a02505834f63df39e0815328
<|skeleton|> class SendNotPermittedError: """Raised when calling send on a tensor which does not allow send to be called on it. This can happen do to sensitivity being too high""" def simplify(worker: 'sy.workers.AbstractWorker', e): """Serialize information about an Exception which was raised to forwa...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SendNotPermittedError: """Raised when calling send on a tensor which does not allow send to be called on it. This can happen do to sensitivity being too high""" def simplify(worker: 'sy.workers.AbstractWorker', e): """Serialize information about an Exception which was raised to forward it""" ...
the_stack_v2_python_sparse
syft/exceptions.py
tudorcebere/PySyft
train
2
c67919208ded41ded5abcfa37a400f4eef24a42f
[ "language_list = lq.get_languages()\nif not language_list:\n logging.debug('Empty language list')\n return self.bad_response('Internal error')\nres = [{'id': language.id, 'language': language.name} for language in language_list]\nreturn self.success_response({'languages': res})", "data = request.get_json()\...
<|body_start_0|> language_list = lq.get_languages() if not language_list: logging.debug('Empty language list') return self.bad_response('Internal error') res = [{'id': language.id, 'language': language.name} for language in language_list] return self.success_respo...
LanguageHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LanguageHandler: def get(self): """Get language list.""" <|body_0|> def post(self): """{ 'name': str }""" <|body_1|> <|end_skeleton|> <|body_start_0|> language_list = lq.get_languages() if not language_list: logging.debug('Empty ...
stack_v2_sparse_classes_36k_train_028327
1,015
no_license
[ { "docstring": "Get language list.", "name": "get", "signature": "def get(self)" }, { "docstring": "{ 'name': str }", "name": "post", "signature": "def post(self)" } ]
2
stack_v2_sparse_classes_30k_test_000709
Implement the Python class `LanguageHandler` described below. Class description: Implement the LanguageHandler class. Method signatures and docstrings: - def get(self): Get language list. - def post(self): { 'name': str }
Implement the Python class `LanguageHandler` described below. Class description: Implement the LanguageHandler class. Method signatures and docstrings: - def get(self): Get language list. - def post(self): { 'name': str } <|skeleton|> class LanguageHandler: def get(self): """Get language list.""" ...
8d3dfc06e0738e3e9547604d421788b4145fd971
<|skeleton|> class LanguageHandler: def get(self): """Get language list.""" <|body_0|> def post(self): """{ 'name': str }""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LanguageHandler: def get(self): """Get language list.""" language_list = lq.get_languages() if not language_list: logging.debug('Empty language list') return self.bad_response('Internal error') res = [{'id': language.id, 'language': language.name} for la...
the_stack_v2_python_sparse
app/handlers/language.py
AleksandrFrolov/BackofficeSS
train
0
ca33239d16e723674ac0b47248a63a19bb204b7c
[ "self.redshift = redshift\nself.light_profile_list = light_profile_list\nself.mass_profile_list = mass_profile_list", "if self.light_profile_list is not None:\n return sum(map(lambda p: p.image_from_grid(grid=grid), self.light_profile_list))\nreturn np.zeros((grid.shape[0],))", "if self.mass_profile_list is ...
<|body_start_0|> self.redshift = redshift self.light_profile_list = light_profile_list self.mass_profile_list = mass_profile_list <|end_body_0|> <|body_start_1|> if self.light_profile_list is not None: return sum(map(lambda p: p.image_from_grid(grid=grid), self.light_profile...
Galaxy
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Galaxy: def __init__(self, redshift: float, light_profile_list: Optional[List]=None, mass_profile_list: Optional[List]=None): """A galaxy, which contains light and mass profiles at a specified redshift. Parameters ---------- redshift The redshift of the galaxy. light_profile_list A list ...
stack_v2_sparse_classes_36k_train_028328
2,345
no_license
[ { "docstring": "A galaxy, which contains light and mass profiles at a specified redshift. Parameters ---------- redshift The redshift of the galaxy. light_profile_list A list of the galaxy's light profiles. mass_profile_list A list of the galaxy's mass profiles.", "name": "__init__", "signature": "def _...
3
null
Implement the Python class `Galaxy` described below. Class description: Implement the Galaxy class. Method signatures and docstrings: - def __init__(self, redshift: float, light_profile_list: Optional[List]=None, mass_profile_list: Optional[List]=None): A galaxy, which contains light and mass profiles at a specified ...
Implement the Python class `Galaxy` described below. Class description: Implement the Galaxy class. Method signatures and docstrings: - def __init__(self, redshift: float, light_profile_list: Optional[List]=None, mass_profile_list: Optional[List]=None): A galaxy, which contains light and mass profiles at a specified ...
ac76dfef4643189a130ce18d23070bb81272a93c
<|skeleton|> class Galaxy: def __init__(self, redshift: float, light_profile_list: Optional[List]=None, mass_profile_list: Optional[List]=None): """A galaxy, which contains light and mass profiles at a specified redshift. Parameters ---------- redshift The redshift of the galaxy. light_profile_list A list ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Galaxy: def __init__(self, redshift: float, light_profile_list: Optional[List]=None, mass_profile_list: Optional[List]=None): """A galaxy, which contains light and mass profiles at a specified redshift. Parameters ---------- redshift The redshift of the galaxy. light_profile_list A list of the galaxy'...
the_stack_v2_python_sparse
projects/cosmology/src/galaxy.py
Jammy2211/autofit_workspace
train
6
2f7970d4837197811056d4adc87a2ee3ed1fe5af
[ "try:\n wiki = Wiki.objects.get(slug=slug)\nexcept Wiki.DoesNotExist:\n error_msg = 'Wiki not found.'\n return api_error(status.HTTP_404_NOT_FOUND, error_msg)\nif not wiki.has_read_perm(request.user):\n error_msg = 'Permission denied.'\n return api_error(status.HTTP_403_FORBIDDEN, error_msg)\npage_na...
<|body_start_0|> try: wiki = Wiki.objects.get(slug=slug) except Wiki.DoesNotExist: error_msg = 'Wiki not found.' return api_error(status.HTTP_404_NOT_FOUND, error_msg) if not wiki.has_read_perm(request.user): error_msg = 'Permission denied.' ...
WikiPageView
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WikiPageView: def get(self, request, slug, page_name='home'): """Get content of a wiki""" <|body_0|> def delete(self, request, slug, page_name): """Delete a page in a wiki""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: wiki = Wiki....
stack_v2_sparse_classes_36k_train_028329
12,107
permissive
[ { "docstring": "Get content of a wiki", "name": "get", "signature": "def get(self, request, slug, page_name='home')" }, { "docstring": "Delete a page in a wiki", "name": "delete", "signature": "def delete(self, request, slug, page_name)" } ]
2
stack_v2_sparse_classes_30k_train_015225
Implement the Python class `WikiPageView` described below. Class description: Implement the WikiPageView class. Method signatures and docstrings: - def get(self, request, slug, page_name='home'): Get content of a wiki - def delete(self, request, slug, page_name): Delete a page in a wiki
Implement the Python class `WikiPageView` described below. Class description: Implement the WikiPageView class. Method signatures and docstrings: - def get(self, request, slug, page_name='home'): Get content of a wiki - def delete(self, request, slug, page_name): Delete a page in a wiki <|skeleton|> class WikiPageVi...
13b3ed26a04248211ef91ca70dccc617be27a3c3
<|skeleton|> class WikiPageView: def get(self, request, slug, page_name='home'): """Get content of a wiki""" <|body_0|> def delete(self, request, slug, page_name): """Delete a page in a wiki""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WikiPageView: def get(self, request, slug, page_name='home'): """Get content of a wiki""" try: wiki = Wiki.objects.get(slug=slug) except Wiki.DoesNotExist: error_msg = 'Wiki not found.' return api_error(status.HTTP_404_NOT_FOUND, error_msg) i...
the_stack_v2_python_sparse
fhs/usr/share/python/syncwerk/restapi/restapi/api2/endpoints/wiki_pages.py
syncwerk/syncwerk-server-restapi
train
0
d3a431c151d605c82207c6d0c44b1be4ae25cd0d
[ "super(CreateAdcNodeObjects, self).__init__(*args, **kwargs)\nself.node_count = node_count\nself.bigip = bigip\nself.object_counter = 0\nself.context = ContextHelper(__name__)\nself.cfgifc = self.context.get_config()\nself.ip_gen = ipv4_address_generator()", "LOG.info('Creating {0} node(s) in the BigIQ working co...
<|body_start_0|> super(CreateAdcNodeObjects, self).__init__(*args, **kwargs) self.node_count = node_count self.bigip = bigip self.object_counter = 0 self.context = ContextHelper(__name__) self.cfgifc = self.context.get_config() self.ip_gen = ipv4_address_generator...
Create the specified number of ADC Node objects on the BIG-IQ for the specified BIG-IP. Works for BIG-IQ 4.6.0 and later. You must deploy the ADC objects from the BIG-IQ to the BIG-IP(s) with a separate call.
CreateAdcNodeObjects
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CreateAdcNodeObjects: """Create the specified number of ADC Node objects on the BIG-IQ for the specified BIG-IP. Works for BIG-IQ 4.6.0 and later. You must deploy the ADC objects from the BIG-IQ to the BIG-IP(s) with a separate call.""" def __init__(self, node_count, bigip, *args, **kwargs):...
stack_v2_sparse_classes_36k_train_028330
15,401
permissive
[ { "docstring": "Object initialization. @param node_count: The number of ADC nodes to create. @param bigip: BIG-IP device, as returned by MachineIdResolver.", "name": "__init__", "signature": "def __init__(self, node_count, bigip, *args, **kwargs)" }, { "docstring": "Generate the specified number...
2
null
Implement the Python class `CreateAdcNodeObjects` described below. Class description: Create the specified number of ADC Node objects on the BIG-IQ for the specified BIG-IP. Works for BIG-IQ 4.6.0 and later. You must deploy the ADC objects from the BIG-IQ to the BIG-IP(s) with a separate call. Method signatures and d...
Implement the Python class `CreateAdcNodeObjects` described below. Class description: Create the specified number of ADC Node objects on the BIG-IQ for the specified BIG-IP. Works for BIG-IQ 4.6.0 and later. You must deploy the ADC objects from the BIG-IQ to the BIG-IP(s) with a separate call. Method signatures and d...
40264ac83b3f1d2a30ebc1107927044f42c86f8a
<|skeleton|> class CreateAdcNodeObjects: """Create the specified number of ADC Node objects on the BIG-IQ for the specified BIG-IP. Works for BIG-IQ 4.6.0 and later. You must deploy the ADC objects from the BIG-IQ to the BIG-IP(s) with a separate call.""" def __init__(self, node_count, bigip, *args, **kwargs):...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CreateAdcNodeObjects: """Create the specified number of ADC Node objects on the BIG-IQ for the specified BIG-IP. Works for BIG-IQ 4.6.0 and later. You must deploy the ADC objects from the BIG-IQ to the BIG-IP(s) with a separate call.""" def __init__(self, node_count, bigip, *args, **kwargs): """O...
the_stack_v2_python_sparse
f5test/commands/rest/adc.py
jonozzz/nosest
train
1
ab95cd39abb438207791303ed82eea174967422e
[ "self.master = master\nself.model = HomeModel()\nisReady = self.model.doesScaleExist()\nself.view = HomeView(master, self, isReady, ImageTk.PhotoImage(file='LogoImg.png'))\nself.view.pack(expand=YES, fill=BOTH)", "self.view.destroy()\nfrom contoursController import ContoursController\nContoursController(self.mast...
<|body_start_0|> self.master = master self.model = HomeModel() isReady = self.model.doesScaleExist() self.view = HomeView(master, self, isReady, ImageTk.PhotoImage(file='LogoImg.png')) self.view.pack(expand=YES, fill=BOTH) <|end_body_0|> <|body_start_1|> self.view.destro...
HomeController
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HomeController: def __init__(self, master): """The HomeController if there is no config file will not allow the user to start export, but only to calibrate the various models Args: master(Tk object): The toplevel widget of Tk which is the main window of an application""" <|body_0...
stack_v2_sparse_classes_36k_train_028331
1,161
no_license
[ { "docstring": "The HomeController if there is no config file will not allow the user to start export, but only to calibrate the various models Args: master(Tk object): The toplevel widget of Tk which is the main window of an application", "name": "__init__", "signature": "def __init__(self, master)" ...
3
stack_v2_sparse_classes_30k_train_013533
Implement the Python class `HomeController` described below. Class description: Implement the HomeController class. Method signatures and docstrings: - def __init__(self, master): The HomeController if there is no config file will not allow the user to start export, but only to calibrate the various models Args: mast...
Implement the Python class `HomeController` described below. Class description: Implement the HomeController class. Method signatures and docstrings: - def __init__(self, master): The HomeController if there is no config file will not allow the user to start export, but only to calibrate the various models Args: mast...
e448c450f6792dbc96e61d7ae4869d27e9e82632
<|skeleton|> class HomeController: def __init__(self, master): """The HomeController if there is no config file will not allow the user to start export, but only to calibrate the various models Args: master(Tk object): The toplevel widget of Tk which is the main window of an application""" <|body_0...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HomeController: def __init__(self, master): """The HomeController if there is no config file will not allow the user to start export, but only to calibrate the various models Args: master(Tk object): The toplevel widget of Tk which is the main window of an application""" self.master = master ...
the_stack_v2_python_sparse
src/GUI/homeController.py
LaserSaver/LaserSaver
train
0
7e2642811b17392adf07f375f495fd57aeb24639
[ "super().__init__()\nself.name: str = name\nself.params: dict = data", "if self.params == {}:\n return {self.name: None}\nreturn {self.name: self.params}" ]
<|body_start_0|> super().__init__() self.name: str = name self.params: dict = data <|end_body_0|> <|body_start_1|> if self.params == {}: return {self.name: None} return {self.name: self.params} <|end_body_1|>
Configuration Dataset class.
Dataset
[ "MIT", "Intel", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Dataset: """Configuration Dataset class.""" def __init__(self, name: str, data: Dict[str, Any]={}) -> None: """Initialize Configuration Dataset class.""" <|body_0|> def serialize(self, serialization_type: str='default') -> Dict[str, Any]: """Serialize Dataset cla...
stack_v2_sparse_classes_36k_train_028332
4,560
permissive
[ { "docstring": "Initialize Configuration Dataset class.", "name": "__init__", "signature": "def __init__(self, name: str, data: Dict[str, Any]={}) -> None" }, { "docstring": "Serialize Dataset class.", "name": "serialize", "signature": "def serialize(self, serialization_type: str='defaul...
2
stack_v2_sparse_classes_30k_train_013923
Implement the Python class `Dataset` described below. Class description: Configuration Dataset class. Method signatures and docstrings: - def __init__(self, name: str, data: Dict[str, Any]={}) -> None: Initialize Configuration Dataset class. - def serialize(self, serialization_type: str='default') -> Dict[str, Any]: ...
Implement the Python class `Dataset` described below. Class description: Configuration Dataset class. Method signatures and docstrings: - def __init__(self, name: str, data: Dict[str, Any]={}) -> None: Initialize Configuration Dataset class. - def serialize(self, serialization_type: str='default') -> Dict[str, Any]: ...
3976edc4215398e69ce0213f87ec295f5dc96e0e
<|skeleton|> class Dataset: """Configuration Dataset class.""" def __init__(self, name: str, data: Dict[str, Any]={}) -> None: """Initialize Configuration Dataset class.""" <|body_0|> def serialize(self, serialization_type: str='default') -> Dict[str, Any]: """Serialize Dataset cla...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Dataset: """Configuration Dataset class.""" def __init__(self, name: str, data: Dict[str, Any]={}) -> None: """Initialize Configuration Dataset class.""" super().__init__() self.name: str = name self.params: dict = data def serialize(self, serialization_type: str='def...
the_stack_v2_python_sparse
neural_compressor/ux/utils/workload/dataloader.py
Skp80/neural-compressor
train
0
79ea7de4905de49fc1800aec10e44906f9dd73de
[ "for i in range(n_of_tests):\n result = rb.random_color(300)\n self.assertEqual((300, 300, 3), np.shape(result))\n for color in result:\n for line in color:\n for value in line:\n self.assertTrue(value >= 0 and value <= 1.0)", "for i in range(n_of_tests):\n result = rb...
<|body_start_0|> for i in range(n_of_tests): result = rb.random_color(300) self.assertEqual((300, 300, 3), np.shape(result)) for color in result: for line in color: for value in line: self.assertTrue(value >= 0 and v...
TestResizeImages
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestResizeImages: def test_random_color(self): """Tests that returns a L*L*3 array of values between 0 and1""" <|body_0|> def test_random_image(self): """Test random_image by checking that the resultant image is size*size*3 array of values between 0 and 2? for now, O...
stack_v2_sparse_classes_36k_train_028333
4,020
permissive
[ { "docstring": "Tests that returns a L*L*3 array of values between 0 and1", "name": "test_random_color", "signature": "def test_random_color(self)" }, { "docstring": "Test random_image by checking that the resultant image is size*size*3 array of values between 0 and 2? for now, Ong will solve th...
5
null
Implement the Python class `TestResizeImages` described below. Class description: Implement the TestResizeImages class. Method signatures and docstrings: - def test_random_color(self): Tests that returns a L*L*3 array of values between 0 and1 - def test_random_image(self): Test random_image by checking that the resul...
Implement the Python class `TestResizeImages` described below. Class description: Implement the TestResizeImages class. Method signatures and docstrings: - def test_random_color(self): Tests that returns a L*L*3 array of values between 0 and1 - def test_random_image(self): Test random_image by checking that the resul...
73bd44509da3442f0538968fd6f012e14bd2b2c8
<|skeleton|> class TestResizeImages: def test_random_color(self): """Tests that returns a L*L*3 array of values between 0 and1""" <|body_0|> def test_random_image(self): """Test random_image by checking that the resultant image is size*size*3 array of values between 0 and 2? for now, O...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestResizeImages: def test_random_color(self): """Tests that returns a L*L*3 array of values between 0 and1""" for i in range(n_of_tests): result = rb.random_color(300) self.assertEqual((300, 300, 3), np.shape(result)) for color in result: fo...
the_stack_v2_python_sparse
src/rendering/TestRandomLib/TestRandBack.py
mforcexvi/3D-DL
train
3
99d4ca8e0e3a1e13e230611864ef6a98dac4c1a6
[ "inSpec = super(SampleSelector, cls).getInputSpecification()\ninSpec.addSub(InputData.parameterInputFactory('target', contentType=InputTypes.StringType))\ncriterion = InputData.parameterInputFactory('criterion', contentType=InputTypes.StringType, strictMode=True)\ncriterion.addParam('value', InputTypes.IntegerType)...
<|body_start_0|> inSpec = super(SampleSelector, cls).getInputSpecification() inSpec.addSub(InputData.parameterInputFactory('target', contentType=InputTypes.StringType)) criterion = InputData.parameterInputFactory('criterion', contentType=InputTypes.StringType, strictMode=True) criterion....
This postprocessor selects the row in which the minimum or the maximum of a target is found.The postprocessor can act on DataObject, and generates a DataObject in return.
SampleSelector
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SampleSelector: """This postprocessor selects the row in which the minimum or the maximum of a target is found.The postprocessor can act on DataObject, and generates a DataObject in return.""" def getInputSpecification(cls): """Method to get a reference to a class that specifies the ...
stack_v2_sparse_classes_36k_train_028334
5,362
permissive
[ { "docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for which we are retrieving the specification @ Out, inputSpecification, InputData.ParameterInput, class to use for specifying input of cls.", "name": "getInputSpecification", "signatur...
6
stack_v2_sparse_classes_30k_train_003526
Implement the Python class `SampleSelector` described below. Class description: This postprocessor selects the row in which the minimum or the maximum of a target is found.The postprocessor can act on DataObject, and generates a DataObject in return. Method signatures and docstrings: - def getInputSpecification(cls):...
Implement the Python class `SampleSelector` described below. Class description: This postprocessor selects the row in which the minimum or the maximum of a target is found.The postprocessor can act on DataObject, and generates a DataObject in return. Method signatures and docstrings: - def getInputSpecification(cls):...
2b16e7aa3325fe84cab2477947a951414c635381
<|skeleton|> class SampleSelector: """This postprocessor selects the row in which the minimum or the maximum of a target is found.The postprocessor can act on DataObject, and generates a DataObject in return.""" def getInputSpecification(cls): """Method to get a reference to a class that specifies the ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SampleSelector: """This postprocessor selects the row in which the minimum or the maximum of a target is found.The postprocessor can act on DataObject, and generates a DataObject in return.""" def getInputSpecification(cls): """Method to get a reference to a class that specifies the input data fo...
the_stack_v2_python_sparse
ravenframework/Models/PostProcessors/SampleSelector.py
idaholab/raven
train
201
2bf09c4b10b379fe92623329e28a49ef56a739cb
[ "if verbose:\n print(base_object_query)\nrecord_index = start_record\nresult = run_object_query(self.client, base_object_query, record_index, limit_to, verbose)\nobj_search_result = result['body']['ExecuteMSQLResult']['ResultValue']['ObjectSearchResult']\nif obj_search_result is not None:\n search_results = o...
<|body_start_0|> if verbose: print(base_object_query) record_index = start_record result = run_object_query(self.client, base_object_query, record_index, limit_to, verbose) obj_search_result = result['body']['ExecuteMSQLResult']['ResultValue']['ObjectSearchResult'] if...
A mixin for API client service classes that makes it easy to consistently request multiple queries from a MemberSuite endpoint. Membersuite will often time out on big queries, so this allows us to break it up into smaller requests.
ChunkQueryMixin
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChunkQueryMixin: """A mixin for API client service classes that makes it easy to consistently request multiple queries from a MemberSuite endpoint. Membersuite will often time out on big queries, so this allows us to break it up into smaller requests.""" def get_long_query(self, base_object_...
stack_v2_sparse_classes_36k_train_028335
4,089
permissive
[ { "docstring": "Takes a base query for all objects and recursively requests them :param str base_object_query: the base query to be executed :param int limit_to: how many rows to query for in each chunk :param int max_calls: the max calls(chunks to request) None is infinite :param int start_record: the first re...
2
stack_v2_sparse_classes_30k_train_016823
Implement the Python class `ChunkQueryMixin` described below. Class description: A mixin for API client service classes that makes it easy to consistently request multiple queries from a MemberSuite endpoint. Membersuite will often time out on big queries, so this allows us to break it up into smaller requests. Metho...
Implement the Python class `ChunkQueryMixin` described below. Class description: A mixin for API client service classes that makes it easy to consistently request multiple queries from a MemberSuite endpoint. Membersuite will often time out on big queries, so this allows us to break it up into smaller requests. Metho...
221f5ed8bc7d4424237a4669c5af9edc11819ee9
<|skeleton|> class ChunkQueryMixin: """A mixin for API client service classes that makes it easy to consistently request multiple queries from a MemberSuite endpoint. Membersuite will often time out on big queries, so this allows us to break it up into smaller requests.""" def get_long_query(self, base_object_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ChunkQueryMixin: """A mixin for API client service classes that makes it easy to consistently request multiple queries from a MemberSuite endpoint. Membersuite will often time out on big queries, so this allows us to break it up into smaller requests.""" def get_long_query(self, base_object_query, limit_...
the_stack_v2_python_sparse
membersuite_api_client/mixins.py
rerb/python-membersuite-api-client
train
0
a3fbdbbd0a271444bc64277451b26f429a8aa77b
[ "if not isinstance(args[0], PolarDiagram):\n super().plot(*args, **kwargs)\n return\npd = args[0]\nlabels, slices, info = pd.get_slices(ws, n_steps, full_info=True)\n_configure_axes(self, labels, colors, show_legend, legend_kw, **kwargs)\n_plot(self, slices, info, False, use_convex_hull, **kwargs)", "if not...
<|body_start_0|> if not isinstance(args[0], PolarDiagram): super().plot(*args, **kwargs) return pd = args[0] labels, slices, info = pd.get_slices(ws, n_steps, full_info=True) _configure_axes(self, labels, colors, show_legend, legend_kw, **kwargs) _plot(sel...
Projection to plot given data in a rectilinear plot.
HROFlat
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HROFlat: """Projection to plot given data in a rectilinear plot.""" def plot(self, *args, ws=None, n_steps=None, colors=('green', 'red'), show_legend=False, legend_kw=None, use_convex_hull=False, **kwargs): """Plots the given data in a rectilinear plot. Otherwise, it works identical ...
stack_v2_sparse_classes_36k_train_028336
23,221
permissive
[ { "docstring": "Plots the given data in a rectilinear plot. Otherwise, it works identical to `HROPolar.plot`. See also ---------- `HROPolar.plot`", "name": "plot", "signature": "def plot(self, *args, ws=None, n_steps=None, colors=('green', 'red'), show_legend=False, legend_kw=None, use_convex_hull=False...
2
stack_v2_sparse_classes_30k_train_001477
Implement the Python class `HROFlat` described below. Class description: Projection to plot given data in a rectilinear plot. Method signatures and docstrings: - def plot(self, *args, ws=None, n_steps=None, colors=('green', 'red'), show_legend=False, legend_kw=None, use_convex_hull=False, **kwargs): Plots the given d...
Implement the Python class `HROFlat` described below. Class description: Projection to plot given data in a rectilinear plot. Method signatures and docstrings: - def plot(self, *args, ws=None, n_steps=None, colors=('green', 'red'), show_legend=False, legend_kw=None, use_convex_hull=False, **kwargs): Plots the given d...
921536e2db7a9635c539a8dc2a97d1411e58c2a1
<|skeleton|> class HROFlat: """Projection to plot given data in a rectilinear plot.""" def plot(self, *args, ws=None, n_steps=None, colors=('green', 'red'), show_legend=False, legend_kw=None, use_convex_hull=False, **kwargs): """Plots the given data in a rectilinear plot. Otherwise, it works identical ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HROFlat: """Projection to plot given data in a rectilinear plot.""" def plot(self, *args, ws=None, n_steps=None, colors=('green', 'red'), show_legend=False, legend_kw=None, use_convex_hull=False, **kwargs): """Plots the given data in a rectilinear plot. Otherwise, it works identical to `HROPolar....
the_stack_v2_python_sparse
hrosailing/plotting/projections.py
hrosailing/hrosailing
train
17
6451bfd1032ed71f60c4806b847ec5462c0ddcb4
[ "\"\"\"\n Recall \"count smaller number after self\" where we encountered the problem\n\n count[i] = count of nums[j] - nums[i] < 0 with j > i\n \n Here, after we preprocessed the array, we need to solve the problem\n\n count[i] = count of a <= S[j] - S[i] <= b with j > i\n ...
<|body_start_0|> """ Recall "count smaller number after self" where we encountered the problem count[i] = count of nums[j] - nums[i] < 0 with j > i Here, after we preprocessed the array, we need to solve the problem count[i] = count of a <= S[j]...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def countRangeSum(self, nums, lower, upper): """:type nums: List[int] :type lower: int :type upper: int :rtype: int""" <|body_0|> def countRangeSumBIT(self, nums, lower, upper): """:type nums: List[int] :type lower: int :type upper: int :rtype: int""" ...
stack_v2_sparse_classes_36k_train_028337
3,778
no_license
[ { "docstring": ":type nums: List[int] :type lower: int :type upper: int :rtype: int", "name": "countRangeSum", "signature": "def countRangeSum(self, nums, lower, upper)" }, { "docstring": ":type nums: List[int] :type lower: int :type upper: int :rtype: int", "name": "countRangeSumBIT", "...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countRangeSum(self, nums, lower, upper): :type nums: List[int] :type lower: int :type upper: int :rtype: int - def countRangeSumBIT(self, nums, lower, upper): :type nums: Lis...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countRangeSum(self, nums, lower, upper): :type nums: List[int] :type lower: int :type upper: int :rtype: int - def countRangeSumBIT(self, nums, lower, upper): :type nums: Lis...
810575368ecffa97677bdb51744d1f716140bbb1
<|skeleton|> class Solution: def countRangeSum(self, nums, lower, upper): """:type nums: List[int] :type lower: int :type upper: int :rtype: int""" <|body_0|> def countRangeSumBIT(self, nums, lower, upper): """:type nums: List[int] :type lower: int :type upper: int :rtype: int""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def countRangeSum(self, nums, lower, upper): """:type nums: List[int] :type lower: int :type upper: int :rtype: int""" """ Recall "count smaller number after self" where we encountered the problem count[i] = count of nums[j] - nums[i] < 0 with j > i ...
the_stack_v2_python_sparse
C/CountofRangeSum.py
bssrdf/pyleet
train
2
13a2825e1dba546a69beb6a2cda328345ef71920
[ "n = len(nums)\nif n * k == 0:\n return []\nreturn [max(nums[i:i + k]) for i in range(n - k + 1)]", "size = len(nums)\nif size * k == 0:\n return []\nif size == 1:\n return nums\nqueue, output, max_idx = (deque(), [], 0)\n\ndef clean_up(index: int):\n if queue and queue[0] == index - k:\n queue...
<|body_start_0|> n = len(nums) if n * k == 0: return [] return [max(nums[i:i + k]) for i in range(n - k + 1)] <|end_body_0|> <|body_start_1|> size = len(nums) if size * k == 0: return [] if size == 1: return nums queue, output,...
SlidingWindow
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SlidingWindow: def get_max_in_window__(self, nums: List[int], k: int) -> List[int]: """Approach: Brute Force Time Complexity: O(NK) Space Complexity: O(N - k + 1) :param nums: :return:""" <|body_0|> def get_max_in_window_(self, nums: List[int], k: int) -> List[int]: ...
stack_v2_sparse_classes_36k_train_028338
2,981
no_license
[ { "docstring": "Approach: Brute Force Time Complexity: O(NK) Space Complexity: O(N - k + 1) :param nums: :return:", "name": "get_max_in_window__", "signature": "def get_max_in_window__(self, nums: List[int], k: int) -> List[int]" }, { "docstring": "Approach: Using Deque Time Complexity: O(N) Spa...
3
stack_v2_sparse_classes_30k_train_018054
Implement the Python class `SlidingWindow` described below. Class description: Implement the SlidingWindow class. Method signatures and docstrings: - def get_max_in_window__(self, nums: List[int], k: int) -> List[int]: Approach: Brute Force Time Complexity: O(NK) Space Complexity: O(N - k + 1) :param nums: :return: -...
Implement the Python class `SlidingWindow` described below. Class description: Implement the SlidingWindow class. Method signatures and docstrings: - def get_max_in_window__(self, nums: List[int], k: int) -> List[int]: Approach: Brute Force Time Complexity: O(NK) Space Complexity: O(N - k + 1) :param nums: :return: -...
65cc78b5afa0db064f9fe8f06597e3e120f7363d
<|skeleton|> class SlidingWindow: def get_max_in_window__(self, nums: List[int], k: int) -> List[int]: """Approach: Brute Force Time Complexity: O(NK) Space Complexity: O(N - k + 1) :param nums: :return:""" <|body_0|> def get_max_in_window_(self, nums: List[int], k: int) -> List[int]: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SlidingWindow: def get_max_in_window__(self, nums: List[int], k: int) -> List[int]: """Approach: Brute Force Time Complexity: O(NK) Space Complexity: O(N - k + 1) :param nums: :return:""" n = len(nums) if n * k == 0: return [] return [max(nums[i:i + k]) for i in ran...
the_stack_v2_python_sparse
revisited/arrays/sliding_window.py
Shiv2157k/leet_code
train
1
af38cf309f51c557e607a85e57ec13d720223470
[ "super().__init__(env)\nself._time_delta = 0.1\nself._speed_max = 22.22\nself._dist_max = self._speed_max * self._time_delta", "limited_actions: Dict[str, np.ndarray] = {}\nfor agent_name, agent_action in action.items():\n limited_actions[agent_name] = self._limit(name=agent_name, action=agent_action)\nout = s...
<|body_start_0|> super().__init__(env) self._time_delta = 0.1 self._speed_max = 22.22 self._dist_max = self._speed_max * self._time_delta <|end_body_0|> <|body_start_1|> limited_actions: Dict[str, np.ndarray] = {} for agent_name, agent_action in action.items(): ...
Limits the delta-x and delta-y in the RelativeTargetPose action space.
LimitRelativeTargetPose
[ "LGPL-3.0-only", "LicenseRef-scancode-warranty-disclaimer", "CC-BY-NC-4.0", "GPL-1.0-or-later", "LicenseRef-scancode-generic-exception", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.0-or-later", "GPL-3.0-or-later", "BSD-3-Clause", "MIT", "LGPL-...
stack_v2_sparse_python_classes_v1
<|skeleton|> class LimitRelativeTargetPose: """Limits the delta-x and delta-y in the RelativeTargetPose action space.""" def __init__(self, env: gym.Env): """Args: env (gym.Env): Environment to be wrapped.""" <|body_0|> def step(self, action: Dict[str, np.ndarray]) -> Tuple[Dict[str, Any],...
stack_v2_sparse_classes_36k_train_028339
3,732
permissive
[ { "docstring": "Args: env (gym.Env): Environment to be wrapped.", "name": "__init__", "signature": "def __init__(self, env: gym.Env)" }, { "docstring": "Steps the environment. Args: action (Dict[str, np.ndarray]): Action for each agent. Returns: Tuple[ Dict[str, Any], Dict[str, float], Dict[str,...
3
stack_v2_sparse_classes_30k_train_001563
Implement the Python class `LimitRelativeTargetPose` described below. Class description: Limits the delta-x and delta-y in the RelativeTargetPose action space. Method signatures and docstrings: - def __init__(self, env: gym.Env): Args: env (gym.Env): Environment to be wrapped. - def step(self, action: Dict[str, np.nd...
Implement the Python class `LimitRelativeTargetPose` described below. Class description: Limits the delta-x and delta-y in the RelativeTargetPose action space. Method signatures and docstrings: - def __init__(self, env: gym.Env): Args: env (gym.Env): Environment to be wrapped. - def step(self, action: Dict[str, np.nd...
2ae8bd76a0b6e4da5699629cec0fefa5aa47ce67
<|skeleton|> class LimitRelativeTargetPose: """Limits the delta-x and delta-y in the RelativeTargetPose action space.""" def __init__(self, env: gym.Env): """Args: env (gym.Env): Environment to be wrapped.""" <|body_0|> def step(self, action: Dict[str, np.ndarray]) -> Tuple[Dict[str, Any],...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LimitRelativeTargetPose: """Limits the delta-x and delta-y in the RelativeTargetPose action space.""" def __init__(self, env: gym.Env): """Args: env (gym.Env): Environment to be wrapped.""" super().__init__(env) self._time_delta = 0.1 self._speed_max = 22.22 self._...
the_stack_v2_python_sparse
smarts/env/gymnasium/wrappers/limit_relative_target_pose.py
huawei-noah/SMARTS
train
824
859c02e964d85374daf80a08961b1e9e38f0cd72
[ "self.target = target\nif config is not None:\n self.config = config\nelse:\n self.config = get_default_session_config()\nself.graph = graph", "sess = tf.Session(target=self.target, graph=self.graph, config=self.config)\nsess.run(tf.global_variables_initializer())\nsess.run(tf.local_variables_initializer())...
<|body_start_0|> self.target = target if config is not None: self.config = config else: self.config = get_default_session_config() self.graph = graph <|end_body_0|> <|body_start_1|> sess = tf.Session(target=self.target, graph=self.graph, config=self.confi...
tf.train.SessionCreator for a new session
NewSessionCreator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NewSessionCreator: """tf.train.SessionCreator for a new session""" def __init__(self, target='', graph=None, config=None): """Inits NewSessionCreator with targe, graph and config. Args: target: same as :meth:`tf.Session.__init__()`. graph: same as :meth:`tf.Session.__init__()`. confi...
stack_v2_sparse_classes_36k_train_028340
2,209
permissive
[ { "docstring": "Inits NewSessionCreator with targe, graph and config. Args: target: same as :meth:`tf.Session.__init__()`. graph: same as :meth:`tf.Session.__init__()`. config: same as :meth:`tf.Session.__init__()`. Default to :func:`utils.default.get_default_session_config()`.", "name": "__init__", "si...
2
stack_v2_sparse_classes_30k_train_018629
Implement the Python class `NewSessionCreator` described below. Class description: tf.train.SessionCreator for a new session Method signatures and docstrings: - def __init__(self, target='', graph=None, config=None): Inits NewSessionCreator with targe, graph and config. Args: target: same as :meth:`tf.Session.__init_...
Implement the Python class `NewSessionCreator` described below. Class description: tf.train.SessionCreator for a new session Method signatures and docstrings: - def __init__(self, target='', graph=None, config=None): Inits NewSessionCreator with targe, graph and config. Args: target: same as :meth:`tf.Session.__init_...
0ffc81a62eccf021077019fb59b0e9e7615e8222
<|skeleton|> class NewSessionCreator: """tf.train.SessionCreator for a new session""" def __init__(self, target='', graph=None, config=None): """Inits NewSessionCreator with targe, graph and config. Args: target: same as :meth:`tf.Session.__init__()`. graph: same as :meth:`tf.Session.__init__()`. confi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NewSessionCreator: """tf.train.SessionCreator for a new session""" def __init__(self, target='', graph=None, config=None): """Inits NewSessionCreator with targe, graph and config. Args: target: same as :meth:`tf.Session.__init__()`. graph: same as :meth:`tf.Session.__init__()`. config: same as :m...
the_stack_v2_python_sparse
tensorcv/utils/sesscreate.py
conan7882/DeepVision-tensorflow
train
12
fdb9af6308e60b7f913135329713a002b28acc66
[ "elem = deepcopy(elem)\nyld = elem.find('./YIELD')\nif yld is not None:\n yld.tag = 'YLD'\nreturn super(STOCKINFO, STOCKINFO).groom(elem)", "elem = deepcopy(elem)\nyld = elem.find('./YLD')\nif yld is not None:\n yld.tag = 'YIELD'\nreturn super(STOCKINFO, STOCKINFO).ungroom(elem)" ]
<|body_start_0|> elem = deepcopy(elem) yld = elem.find('./YIELD') if yld is not None: yld.tag = 'YLD' return super(STOCKINFO, STOCKINFO).groom(elem) <|end_body_0|> <|body_start_1|> elem = deepcopy(elem) yld = elem.find('./YLD') if yld is not None: ...
OFX Section 13.8.5.6
STOCKINFO
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class STOCKINFO: """OFX Section 13.8.5.6""" def groom(elem): """Rename all Elements tagged YIELD (reserved Python keyword) to YLD""" <|body_0|> def ungroom(elem): """Rename YLD back to YLD""" <|body_1|> <|end_skeleton|> <|body_start_0|> elem = deepcop...
stack_v2_sparse_classes_36k_train_028341
6,031
no_license
[ { "docstring": "Rename all Elements tagged YIELD (reserved Python keyword) to YLD", "name": "groom", "signature": "def groom(elem)" }, { "docstring": "Rename YLD back to YLD", "name": "ungroom", "signature": "def ungroom(elem)" } ]
2
stack_v2_sparse_classes_30k_train_009682
Implement the Python class `STOCKINFO` described below. Class description: OFX Section 13.8.5.6 Method signatures and docstrings: - def groom(elem): Rename all Elements tagged YIELD (reserved Python keyword) to YLD - def ungroom(elem): Rename YLD back to YLD
Implement the Python class `STOCKINFO` described below. Class description: OFX Section 13.8.5.6 Method signatures and docstrings: - def groom(elem): Rename all Elements tagged YIELD (reserved Python keyword) to YLD - def ungroom(elem): Rename YLD back to YLD <|skeleton|> class STOCKINFO: """OFX Section 13.8.5.6"...
67e688ea6510853657736c3804969d029c672c5c
<|skeleton|> class STOCKINFO: """OFX Section 13.8.5.6""" def groom(elem): """Rename all Elements tagged YIELD (reserved Python keyword) to YLD""" <|body_0|> def ungroom(elem): """Rename YLD back to YLD""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class STOCKINFO: """OFX Section 13.8.5.6""" def groom(elem): """Rename all Elements tagged YIELD (reserved Python keyword) to YLD""" elem = deepcopy(elem) yld = elem.find('./YIELD') if yld is not None: yld.tag = 'YLD' return super(STOCKINFO, STOCKINFO).groom(...
the_stack_v2_python_sparse
env/lib/python3.6/site-packages/ofxtools/models/invest/securities.py
yetaai/batchaccounting
train
0
08469cb65e3316eca0c1ed79ab17d1948690c970
[ "user = req.context.get('user')\nuser_id = str(user.id)\nuser_dto = user_to_dto(user)\nuser_dto.posts = [post_to_dto(post, href=PostResource.url_to(req.netloc, post_id=post.id)) for post in get_user_posts(user_id)]\nuser_dto.comments = [comment_to_dto(comment, href=CommentResource.url_to(req.netloc, comment_id=comm...
<|body_start_0|> user = req.context.get('user') user_id = str(user.id) user_dto = user_to_dto(user) user_dto.posts = [post_to_dto(post, href=PostResource.url_to(req.netloc, post_id=post.id)) for post in get_user_posts(user_id)] user_dto.comments = [comment_to_dto(comment, href=Co...
UserResource
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserResource: def on_get(self, req, resp): """Fetch user information for current session.""" <|body_0|> def on_put(self, req, resp): """Updates user resource for current session.""" <|body_1|> <|end_skeleton|> <|body_start_0|> user = req.context.get...
stack_v2_sparse_classes_36k_train_028342
7,736
permissive
[ { "docstring": "Fetch user information for current session.", "name": "on_get", "signature": "def on_get(self, req, resp)" }, { "docstring": "Updates user resource for current session.", "name": "on_put", "signature": "def on_put(self, req, resp)" } ]
2
stack_v2_sparse_classes_30k_train_014015
Implement the Python class `UserResource` described below. Class description: Implement the UserResource class. Method signatures and docstrings: - def on_get(self, req, resp): Fetch user information for current session. - def on_put(self, req, resp): Updates user resource for current session.
Implement the Python class `UserResource` described below. Class description: Implement the UserResource class. Method signatures and docstrings: - def on_get(self, req, resp): Fetch user information for current session. - def on_put(self, req, resp): Updates user resource for current session. <|skeleton|> class Use...
e507fe0307d1a7ea29d6c3e20be62fa82a8f109f
<|skeleton|> class UserResource: def on_get(self, req, resp): """Fetch user information for current session.""" <|body_0|> def on_put(self, req, resp): """Updates user resource for current session.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserResource: def on_get(self, req, resp): """Fetch user information for current session.""" user = req.context.get('user') user_id = str(user.id) user_dto = user_to_dto(user) user_dto.posts = [post_to_dto(post, href=PostResource.url_to(req.netloc, post_id=post.id)) for...
the_stack_v2_python_sparse
blog/resources/users.py
neetjn/py-blog
train
0
f278139af34c96ad50ca8e9008ec1b033ff65147
[ "res = []\nif not root:\n return res\nfrom collections import deque\nqueue = deque()\nqueue.append(root)\nres.append(root.val)\nwhile queue:\n for _ in range(len(queue)):\n node = queue.popleft()\n if node.left:\n queue.append(node.left)\n res.append(node.left.val)\n ...
<|body_start_0|> res = [] if not root: return res from collections import deque queue = deque() queue.append(root) res.append(root.val) while queue: for _ in range(len(queue)): node = queue.popleft() if node....
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_028343
1,761
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
2329898b3653802de287434b5facd09636cc92cf
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" res = [] if not root: return res from collections import deque queue = deque() queue.append(root) res.append(root.val) while q...
the_stack_v2_python_sparse
leetcode/二叉树的序列化与反序列化.py
Bubbleskye/2019summer
train
0
6e830ccb79c876615cbe075dce5643ff4c5ecd96
[ "budget_line = []\nline_obj = self.env['crossovered.budget.lines']\nfor confirmation in self:\n position = self.env['account.budget.post']._get_budget_position(confirmation.account_id.id)\n if not position:\n raise UserError(_('Confirmation Has no Budget Position!'))\n else:\n budget_line = l...
<|body_start_0|> budget_line = [] line_obj = self.env['crossovered.budget.lines'] for confirmation in self: position = self.env['account.budget.post']._get_budget_position(confirmation.account_id.id) if not position: raise UserError(_('Confirmation Has no ...
Inherit to overwrite workflow mothods to reflect confirmation state in voucher line
AccountBudgetConfirmationInvoice
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AccountBudgetConfirmationInvoice: """Inherit to overwrite workflow mothods to reflect confirmation state in voucher line""" def check_budget_invoice(self): """This method check whether the budget line residual allow to validate this confirmation or not @return: boolean True if budget...
stack_v2_sparse_classes_36k_train_028344
25,644
no_license
[ { "docstring": "This method check whether the budget line residual allow to validate this confirmation or not @return: boolean True if budget line residual more that confirm amount, or False", "name": "check_budget_invoice", "signature": "def check_budget_invoice(self)" }, { "docstring": "overwr...
4
stack_v2_sparse_classes_30k_train_008147
Implement the Python class `AccountBudgetConfirmationInvoice` described below. Class description: Inherit to overwrite workflow mothods to reflect confirmation state in voucher line Method signatures and docstrings: - def check_budget_invoice(self): This method check whether the budget line residual allow to validate...
Implement the Python class `AccountBudgetConfirmationInvoice` described below. Class description: Inherit to overwrite workflow mothods to reflect confirmation state in voucher line Method signatures and docstrings: - def check_budget_invoice(self): This method check whether the budget line residual allow to validate...
0b997095c260d58b026440967fea3a202bef7efb
<|skeleton|> class AccountBudgetConfirmationInvoice: """Inherit to overwrite workflow mothods to reflect confirmation state in voucher line""" def check_budget_invoice(self): """This method check whether the budget line residual allow to validate this confirmation or not @return: boolean True if budget...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AccountBudgetConfirmationInvoice: """Inherit to overwrite workflow mothods to reflect confirmation state in voucher line""" def check_budget_invoice(self): """This method check whether the budget line residual allow to validate this confirmation or not @return: boolean True if budget line residua...
the_stack_v2_python_sparse
v_11/EBS-SVN/trunk/account_ebs/models/account.py
musabahmed/baba
train
0
f971f5fe79d150e03ecff1af845cbf26124763ab
[ "assert type(n) == int\nself.HAND_SIZE = n\nself.VOWELS = 'aeiou'\nself.CONSONANTS = 'bcdfghjklmnpqrstvwxyz'\nself.dealNewHand()", "self.hand = {}\nnumVowels = self.HAND_SIZE // 3\nfor i in range(numVowels):\n x = self.VOWELS[random.randrange(0, len(self.VOWELS))]\n self.hand[x] = self.hand.get(x, 0) + 1\nf...
<|body_start_0|> assert type(n) == int self.HAND_SIZE = n self.VOWELS = 'aeiou' self.CONSONANTS = 'bcdfghjklmnpqrstvwxyz' self.dealNewHand() <|end_body_0|> <|body_start_1|> self.hand = {} numVowels = self.HAND_SIZE // 3 for i in range(numVowels): ...
Hand
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Hand: def __init__(self, n): """Initialize a Hand. n: integer, the size of the hand.""" <|body_0|> def dealNewHand(self): """Deals a new hand, and sets the hand attribute to the new hand.""" <|body_1|> def setDummyHand(self, handString): """Allow...
stack_v2_sparse_classes_36k_train_028345
3,675
no_license
[ { "docstring": "Initialize a Hand. n: integer, the size of the hand.", "name": "__init__", "signature": "def __init__(self, n)" }, { "docstring": "Deals a new hand, and sets the hand attribute to the new hand.", "name": "dealNewHand", "signature": "def dealNewHand(self)" }, { "do...
6
null
Implement the Python class `Hand` described below. Class description: Implement the Hand class. Method signatures and docstrings: - def __init__(self, n): Initialize a Hand. n: integer, the size of the hand. - def dealNewHand(self): Deals a new hand, and sets the hand attribute to the new hand. - def setDummyHand(sel...
Implement the Python class `Hand` described below. Class description: Implement the Hand class. Method signatures and docstrings: - def __init__(self, n): Initialize a Hand. n: integer, the size of the hand. - def dealNewHand(self): Deals a new hand, and sets the hand attribute to the new hand. - def setDummyHand(sel...
4e8727154a24c7a1d05361a559a997c8d076480d
<|skeleton|> class Hand: def __init__(self, n): """Initialize a Hand. n: integer, the size of the hand.""" <|body_0|> def dealNewHand(self): """Deals a new hand, and sets the hand attribute to the new hand.""" <|body_1|> def setDummyHand(self, handString): """Allow...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Hand: def __init__(self, n): """Initialize a Hand. n: integer, the size of the hand.""" assert type(n) == int self.HAND_SIZE = n self.VOWELS = 'aeiou' self.CONSONANTS = 'bcdfghjklmnpqrstvwxyz' self.dealNewHand() def dealNewHand(self): """Deals a new...
the_stack_v2_python_sparse
01_MIT_Learning/week_5/lectures_and_examples/Section 2/exercises/hand.py
daftstar/learn_python
train
0
62534c46953b64cd752226e5d2d0844b49b08db2
[ "self.identifier = identifier\nself.name = name if name is not None else 'col_{}'.format(abs(identifier))\nself.data_type = data_type", "name = self.name\nif not self.data_type is None:\n name += '(' + str(self.data_type) + ')'\nreturn name" ]
<|body_start_0|> self.identifier = identifier self.name = name if name is not None else 'col_{}'.format(abs(identifier)) self.data_type = data_type <|end_body_0|> <|body_start_1|> name = self.name if not self.data_type is None: name += '(' + str(self.data_type) + ')'...
Column in a dataset. Each column has a unique identifier and a column name. Column names are not necessarily unique within a dataset. Attributes ---------- identifier: int Unique column identifier name: string Column name data_type: string, optional String representation of the column type in the database. By now the f...
DatasetColumn
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DatasetColumn: """Column in a dataset. Each column has a unique identifier and a column name. Column names are not necessarily unique within a dataset. Attributes ---------- identifier: int Unique column identifier name: string Column name data_type: string, optional String representation of the ...
stack_v2_sparse_classes_36k_train_028346
17,931
permissive
[ { "docstring": "Initialize the column object. Parameters ---------- identifier: int, optional Unique column identifier name: string, optional Column name data_type: string, optional String representation of the column data type.", "name": "__init__", "signature": "def __init__(self, identifier: int=-1, ...
2
null
Implement the Python class `DatasetColumn` described below. Class description: Column in a dataset. Each column has a unique identifier and a column name. Column names are not necessarily unique within a dataset. Attributes ---------- identifier: int Unique column identifier name: string Column name data_type: string,...
Implement the Python class `DatasetColumn` described below. Class description: Column in a dataset. Each column has a unique identifier and a column name. Column names are not necessarily unique within a dataset. Attributes ---------- identifier: int Unique column identifier name: string Column name data_type: string,...
e99f43df3df80ad5647f57d805c339257336ac73
<|skeleton|> class DatasetColumn: """Column in a dataset. Each column has a unique identifier and a column name. Column names are not necessarily unique within a dataset. Attributes ---------- identifier: int Unique column identifier name: string Column name data_type: string, optional String representation of the ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DatasetColumn: """Column in a dataset. Each column has a unique identifier and a column name. Column names are not necessarily unique within a dataset. Attributes ---------- identifier: int Unique column identifier name: string Column name data_type: string, optional String representation of the column type i...
the_stack_v2_python_sparse
vizier/datastore/dataset.py
VizierDB/web-api-async
train
2
c12db7c857d67856acbe1bbe263e661caf2ad3b2
[ "self._ts = datetime.fromtimestamp(unix_timestamp)\nself._cache_key: Optional[str] = None\nself._cache_str: Optional[str] = None", "if Conf.log_timestamp_format != self._cache_key:\n self._cache_str = self._ts.strftime(Conf.log_timestamp_format)\nreturn self._cache_str" ]
<|body_start_0|> self._ts = datetime.fromtimestamp(unix_timestamp) self._cache_key: Optional[str] = None self._cache_str: Optional[str] = None <|end_body_0|> <|body_start_1|> if Conf.log_timestamp_format != self._cache_key: self._cache_str = self._ts.strftime(Conf.log_timest...
A Log timestamp with formatting
LogTimeStamp
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LogTimeStamp: """A Log timestamp with formatting""" def __init__(self, unix_timestamp: int): """:param unix_time: The unix time the timestamp represents""" <|body_0|> def __str__(self) -> str: """Return the timestamp as a formatted string""" <|body_1|> <...
stack_v2_sparse_classes_36k_train_028347
2,873
permissive
[ { "docstring": ":param unix_time: The unix time the timestamp represents", "name": "__init__", "signature": "def __init__(self, unix_timestamp: int)" }, { "docstring": "Return the timestamp as a formatted string", "name": "__str__", "signature": "def __str__(self) -> str" } ]
2
null
Implement the Python class `LogTimeStamp` described below. Class description: A Log timestamp with formatting Method signatures and docstrings: - def __init__(self, unix_timestamp: int): :param unix_time: The unix time the timestamp represents - def __str__(self) -> str: Return the timestamp as a formatted string
Implement the Python class `LogTimeStamp` described below. Class description: A Log timestamp with formatting Method signatures and docstrings: - def __init__(self, unix_timestamp: int): :param unix_time: The unix time the timestamp represents - def __str__(self) -> str: Return the timestamp as a formatted string <|...
f28bfb1c34313c74f99691d0b47de1d90ebfd4ec
<|skeleton|> class LogTimeStamp: """A Log timestamp with formatting""" def __init__(self, unix_timestamp: int): """:param unix_time: The unix time the timestamp represents""" <|body_0|> def __str__(self) -> str: """Return the timestamp as a formatted string""" <|body_1|> <...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LogTimeStamp: """A Log timestamp with formatting""" def __init__(self, unix_timestamp: int): """:param unix_time: The unix time the timestamp represents""" self._ts = datetime.fromtimestamp(unix_timestamp) self._cache_key: Optional[str] = None self._cache_str: Optional[str...
the_stack_v2_python_sparse
angrmanagement/data/log.py
angr/angr-management
train
727
af75b471a6427d070f98b39082caf128095ef1f9
[ "version = versionutils.convert_version_to_tuple(cls.VERSION)\nif not hasattr(objects, cls.obj_name()):\n setattr(objects, cls.obj_name(), cls)\nelse:\n curr_version = versionutils.convert_version_to_tuple(getattr(objects, cls.obj_name()).VERSION)\n if version >= curr_version:\n setattr(objects, cls...
<|body_start_0|> version = versionutils.convert_version_to_tuple(cls.VERSION) if not hasattr(objects, cls.obj_name()): setattr(objects, cls.obj_name(), cls) else: curr_version = versionutils.convert_version_to_tuple(getattr(objects, cls.obj_name()).VERSION) if...
SenlinObjectRegistry
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SenlinObjectRegistry: def registration_hook(self, cls, index): """Callback for object registration. When an object is registered, this function will be called for maintaining senlin.objects.$OBJECT as the highest-versioned implementation of a given object.""" <|body_0|> def ...
stack_v2_sparse_classes_36k_train_028348
5,694
permissive
[ { "docstring": "Callback for object registration. When an object is registered, this function will be called for maintaining senlin.objects.$OBJECT as the highest-versioned implementation of a given object.", "name": "registration_hook", "signature": "def registration_hook(self, cls, index)" }, { ...
2
stack_v2_sparse_classes_30k_train_004187
Implement the Python class `SenlinObjectRegistry` described below. Class description: Implement the SenlinObjectRegistry class. Method signatures and docstrings: - def registration_hook(self, cls, index): Callback for object registration. When an object is registered, this function will be called for maintaining senl...
Implement the Python class `SenlinObjectRegistry` described below. Class description: Implement the SenlinObjectRegistry class. Method signatures and docstrings: - def registration_hook(self, cls, index): Callback for object registration. When an object is registered, this function will be called for maintaining senl...
4125b34e0a0dfeb77b8e62f169b41e8b584bb60e
<|skeleton|> class SenlinObjectRegistry: def registration_hook(self, cls, index): """Callback for object registration. When an object is registered, this function will be called for maintaining senlin.objects.$OBJECT as the highest-versioned implementation of a given object.""" <|body_0|> def ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SenlinObjectRegistry: def registration_hook(self, cls, index): """Callback for object registration. When an object is registered, this function will be called for maintaining senlin.objects.$OBJECT as the highest-versioned implementation of a given object.""" version = versionutils.convert_ver...
the_stack_v2_python_sparse
senlin/objects/base.py
openstack/senlin
train
47
ba93715786f1a6fed25ec3b8d8746d07ccbcefa9
[ "super(DecoderLayer, self).__init__()\nwith self.init_scope():\n self.self_attn = MultiHeadAttention(n_units, h, dropout=dropout, initialW=initialW, initial_bias=initial_bias)\n self.src_attn = MultiHeadAttention(n_units, h, dropout=dropout, initialW=initialW, initial_bias=initial_bias)\n self.feed_forward...
<|body_start_0|> super(DecoderLayer, self).__init__() with self.init_scope(): self.self_attn = MultiHeadAttention(n_units, h, dropout=dropout, initialW=initialW, initial_bias=initial_bias) self.src_attn = MultiHeadAttention(n_units, h, dropout=dropout, initialW=initialW, initial_...
Single decoder layer module. Args: n_units (int): Number of input/output dimension of a FeedForward layer. d_units (int): Number of units of hidden layer in a FeedForward layer. h (int): Number of attention heads. dropout (float): Dropout rate
DecoderLayer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DecoderLayer: """Single decoder layer module. Args: n_units (int): Number of input/output dimension of a FeedForward layer. d_units (int): Number of units of hidden layer in a FeedForward layer. h (int): Number of attention heads. dropout (float): Dropout rate""" def __init__(self, n_units, ...
stack_v2_sparse_classes_36k_train_028349
2,526
permissive
[ { "docstring": "Initialize DecoderLayer.", "name": "__init__", "signature": "def __init__(self, n_units, d_units=0, h=8, dropout=0.1, initialW=None, initial_bias=None)" }, { "docstring": "Compute Encoder layer. Args: e (chainer.Variable): Batch of padded features. (B, Lmax) s (chainer.Variable):...
2
stack_v2_sparse_classes_30k_train_004869
Implement the Python class `DecoderLayer` described below. Class description: Single decoder layer module. Args: n_units (int): Number of input/output dimension of a FeedForward layer. d_units (int): Number of units of hidden layer in a FeedForward layer. h (int): Number of attention heads. dropout (float): Dropout ra...
Implement the Python class `DecoderLayer` described below. Class description: Single decoder layer module. Args: n_units (int): Number of input/output dimension of a FeedForward layer. d_units (int): Number of units of hidden layer in a FeedForward layer. h (int): Number of attention heads. dropout (float): Dropout ra...
bcd20948db7846ee523443ef9fd78c7a1248c95e
<|skeleton|> class DecoderLayer: """Single decoder layer module. Args: n_units (int): Number of input/output dimension of a FeedForward layer. d_units (int): Number of units of hidden layer in a FeedForward layer. h (int): Number of attention heads. dropout (float): Dropout rate""" def __init__(self, n_units, ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DecoderLayer: """Single decoder layer module. Args: n_units (int): Number of input/output dimension of a FeedForward layer. d_units (int): Number of units of hidden layer in a FeedForward layer. h (int): Number of attention heads. dropout (float): Dropout rate""" def __init__(self, n_units, d_units=0, h=...
the_stack_v2_python_sparse
espnet/nets/chainer_backend/transformer/decoder_layer.py
espnet/espnet
train
7,242
2e687de7f1bddf9d30ef34bd24d1c217ba2428fb
[ "graph = defaultdict(list)\nfor u, v, w in times:\n graph[u].append((v, w))\ndist = {node: float('inf') for node in range(1, N + 1)}\nprint(dist)\nseen = [False] * (N + 1)\ndist[K] = 0\nwhile True:\n cand_node = -1\n cand_dist = float('inf')\n for i in range(1, N + 1):\n if not seen[i] and dist[i...
<|body_start_0|> graph = defaultdict(list) for u, v, w in times: graph[u].append((v, w)) dist = {node: float('inf') for node in range(1, N + 1)} print(dist) seen = [False] * (N + 1) dist[K] = 0 while True: cand_node = -1 cand_di...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def networkDelayTime(self, times, N, K): """:type times: List[List[int]] :type N: int :type K: int :rtype: int""" <|body_0|> def networkDelayTime_(self, times, N, K): """:type times: List[List[int]] :type N: int :type K: int :rtype: int""" <|body_1|...
stack_v2_sparse_classes_36k_train_028350
2,764
no_license
[ { "docstring": ":type times: List[List[int]] :type N: int :type K: int :rtype: int", "name": "networkDelayTime", "signature": "def networkDelayTime(self, times, N, K)" }, { "docstring": ":type times: List[List[int]] :type N: int :type K: int :rtype: int", "name": "networkDelayTime_", "si...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def networkDelayTime(self, times, N, K): :type times: List[List[int]] :type N: int :type K: int :rtype: int - def networkDelayTime_(self, times, N, K): :type times: List[List[int...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def networkDelayTime(self, times, N, K): :type times: List[List[int]] :type N: int :type K: int :rtype: int - def networkDelayTime_(self, times, N, K): :type times: List[List[int...
786075e0f9f61cf062703bc0b41cc3191d77f033
<|skeleton|> class Solution: def networkDelayTime(self, times, N, K): """:type times: List[List[int]] :type N: int :type K: int :rtype: int""" <|body_0|> def networkDelayTime_(self, times, N, K): """:type times: List[List[int]] :type N: int :type K: int :rtype: int""" <|body_1|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def networkDelayTime(self, times, N, K): """:type times: List[List[int]] :type N: int :type K: int :rtype: int""" graph = defaultdict(list) for u, v, w in times: graph[u].append((v, w)) dist = {node: float('inf') for node in range(1, N + 1)} print(...
the_stack_v2_python_sparse
743_networkDelayTime.py
Anirban2404/LeetCodePractice
train
1
ccd6f4f54e707fe8aa016c3c6b9407227f3fe0f0
[ "ENFORCER.enforce_call(action='identity:check_grant', build_target=_build_enforcement_target)\nPROVIDERS.assignment_api.get_grant(role_id, domain_id=domain_id, group_id=group_id, inherited_to_projects=False)\nreturn (None, http_client.NO_CONTENT)", "ENFORCER.enforce_call(action='identity:create_grant', build_targ...
<|body_start_0|> ENFORCER.enforce_call(action='identity:check_grant', build_target=_build_enforcement_target) PROVIDERS.assignment_api.get_grant(role_id, domain_id=domain_id, group_id=group_id, inherited_to_projects=False) return (None, http_client.NO_CONTENT) <|end_body_0|> <|body_start_1|> ...
DomainGroupResource
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DomainGroupResource: def get(self, domain_id=None, group_id=None, role_id=None): """Check if a group has a specific role on a domain. GET/HEAD /v3/domains/{domain_id}/groups/{group_id}/roles/{role_id}""" <|body_0|> def put(self, domain_id=None, group_id=None, role_id=None): ...
stack_v2_sparse_classes_36k_train_028351
19,761
permissive
[ { "docstring": "Check if a group has a specific role on a domain. GET/HEAD /v3/domains/{domain_id}/groups/{group_id}/roles/{role_id}", "name": "get", "signature": "def get(self, domain_id=None, group_id=None, role_id=None)" }, { "docstring": "Grant a role to a group on a domain. PUT /v3/domains/...
3
null
Implement the Python class `DomainGroupResource` described below. Class description: Implement the DomainGroupResource class. Method signatures and docstrings: - def get(self, domain_id=None, group_id=None, role_id=None): Check if a group has a specific role on a domain. GET/HEAD /v3/domains/{domain_id}/groups/{group...
Implement the Python class `DomainGroupResource` described below. Class description: Implement the DomainGroupResource class. Method signatures and docstrings: - def get(self, domain_id=None, group_id=None, role_id=None): Check if a group has a specific role on a domain. GET/HEAD /v3/domains/{domain_id}/groups/{group...
03a0a8146a78682ede9eca12a5a7fdacde2035c8
<|skeleton|> class DomainGroupResource: def get(self, domain_id=None, group_id=None, role_id=None): """Check if a group has a specific role on a domain. GET/HEAD /v3/domains/{domain_id}/groups/{group_id}/roles/{role_id}""" <|body_0|> def put(self, domain_id=None, group_id=None, role_id=None): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DomainGroupResource: def get(self, domain_id=None, group_id=None, role_id=None): """Check if a group has a specific role on a domain. GET/HEAD /v3/domains/{domain_id}/groups/{group_id}/roles/{role_id}""" ENFORCER.enforce_call(action='identity:check_grant', build_target=_build_enforcement_targe...
the_stack_v2_python_sparse
keystone/api/domains.py
sapcc/keystone
train
0
fe182f6a4259ce6281c8b7ac34da161be491bbc2
[ "assert len(input_string) > 0\nsuper().__init__(self.PROBLEM_NAME)\nself.input_string = input_string", "print('Solving {} problem ...'.format(self.PROBLEM_NAME))\njson = self.input_string\nif not json:\n return ''\nresult = []\nmultiplier = 0\ni = 0\nwhile i < len(json):\n if json[i] in self.OPENING_BRACKET...
<|body_start_0|> assert len(input_string) > 0 super().__init__(self.PROBLEM_NAME) self.input_string = input_string <|end_body_0|> <|body_start_1|> print('Solving {} problem ...'.format(self.PROBLEM_NAME)) json = self.input_string if not json: return '' ...
PrettyPrintJSON
PrettyPrintJSON
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PrettyPrintJSON: """PrettyPrintJSON""" def __init__(self, input_string): """Pretty Print JSON Note: Args: input_string: JSON string to be pretty-printed Returns: None Raises: None""" <|body_0|> def solve(self): """Solve the problem Args: Returns: string Raises: N...
stack_v2_sparse_classes_36k_train_028352
2,933
no_license
[ { "docstring": "Pretty Print JSON Note: Args: input_string: JSON string to be pretty-printed Returns: None Raises: None", "name": "__init__", "signature": "def __init__(self, input_string)" }, { "docstring": "Solve the problem Args: Returns: string Raises: None", "name": "solve", "signat...
2
null
Implement the Python class `PrettyPrintJSON` described below. Class description: PrettyPrintJSON Method signatures and docstrings: - def __init__(self, input_string): Pretty Print JSON Note: Args: input_string: JSON string to be pretty-printed Returns: None Raises: None - def solve(self): Solve the problem Args: Retu...
Implement the Python class `PrettyPrintJSON` described below. Class description: PrettyPrintJSON Method signatures and docstrings: - def __init__(self, input_string): Pretty Print JSON Note: Args: input_string: JSON string to be pretty-printed Returns: None Raises: None - def solve(self): Solve the problem Args: Retu...
11f4d25cb211740514c119a60962d075a0817abd
<|skeleton|> class PrettyPrintJSON: """PrettyPrintJSON""" def __init__(self, input_string): """Pretty Print JSON Note: Args: input_string: JSON string to be pretty-printed Returns: None Raises: None""" <|body_0|> def solve(self): """Solve the problem Args: Returns: string Raises: N...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PrettyPrintJSON: """PrettyPrintJSON""" def __init__(self, input_string): """Pretty Print JSON Note: Args: input_string: JSON string to be pretty-printed Returns: None Raises: None""" assert len(input_string) > 0 super().__init__(self.PROBLEM_NAME) self.input_string = input...
the_stack_v2_python_sparse
python/problems/string/pretty_print_json.py
santhosh-kumar/AlgorithmsAndDataStructures
train
2
ecf8987c17870b9818691d5a1434b9bb6c143743
[ "data = {'article': request.data.get('id', None), 'user_id': request._request.uid, 'content': request.data.get('content', None)}\ns = ArticleCommentSerializer(data=data)\ns.is_valid()\nif s.errors:\n return self.error(errorcode.MSG_INVALID_DATA, errorcode.INVALID_DATA)\narticle = s.validated_data['article']\ns.v...
<|body_start_0|> data = {'article': request.data.get('id', None), 'user_id': request._request.uid, 'content': request.data.get('content', None)} s = ArticleCommentSerializer(data=data) s.is_valid() if s.errors: return self.error(errorcode.MSG_INVALID_DATA, errorcode.INVALID_D...
CommentView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CommentView: def post(self, request): """评论文章,必须是已发表的文章""" <|body_0|> def delete(self, request): """删除本人的评论""" <|body_1|> def put(self, request): """修改本人的评论""" <|body_2|> <|end_skeleton|> <|body_start_0|> data = {'article': requ...
stack_v2_sparse_classes_36k_train_028353
12,861
no_license
[ { "docstring": "评论文章,必须是已发表的文章", "name": "post", "signature": "def post(self, request)" }, { "docstring": "删除本人的评论", "name": "delete", "signature": "def delete(self, request)" }, { "docstring": "修改本人的评论", "name": "put", "signature": "def put(self, request)" } ]
3
stack_v2_sparse_classes_30k_train_002594
Implement the Python class `CommentView` described below. Class description: Implement the CommentView class. Method signatures and docstrings: - def post(self, request): 评论文章,必须是已发表的文章 - def delete(self, request): 删除本人的评论 - def put(self, request): 修改本人的评论
Implement the Python class `CommentView` described below. Class description: Implement the CommentView class. Method signatures and docstrings: - def post(self, request): 评论文章,必须是已发表的文章 - def delete(self, request): 删除本人的评论 - def put(self, request): 修改本人的评论 <|skeleton|> class CommentView: def post(self, request)...
6a68fb207f43e5ed65299cc08535b35d5e934ead
<|skeleton|> class CommentView: def post(self, request): """评论文章,必须是已发表的文章""" <|body_0|> def delete(self, request): """删除本人的评论""" <|body_1|> def put(self, request): """修改本人的评论""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CommentView: def post(self, request): """评论文章,必须是已发表的文章""" data = {'article': request.data.get('id', None), 'user_id': request._request.uid, 'content': request.data.get('content', None)} s = ArticleCommentSerializer(data=data) s.is_valid() if s.errors: retur...
the_stack_v2_python_sparse
apps/articles/views.py
Slowhalfframe/fanyijiang-API
train
0
a0c114483329b253162e84fc8b70f93bd9eaa3e2
[ "value = None\ncache = None\nprefix = None\nif self.should_cache():\n prefix = '%s:%s:string' % (self.get_cache_version(), self.get_cache_prefix())\n cache = router.router.get_cache(prefix)\n value = cache.get(prefix)\nif not value:\n value = super(CacheView, self).get_as_string(request, *args, **kwargs...
<|body_start_0|> value = None cache = None prefix = None if self.should_cache(): prefix = '%s:%s:string' % (self.get_cache_version(), self.get_cache_prefix()) cache = router.router.get_cache(prefix) value = cache.get(prefix) if not value: ...
A class based view that overrides the default dispatch method to determine the cache_prefix. If the cms view is available this class will inherit from there otherwise it will inherit from django's generic class View. :param cache_time: How long should we cache this attribute. This gets passed to django middleware and d...
CacheView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CacheView: """A class based view that overrides the default dispatch method to determine the cache_prefix. If the cms view is available this class will inherit from there otherwise it will inherit from django's generic class View. :param cache_time: How long should we cache this attribute. This g...
stack_v2_sparse_classes_36k_train_028354
7,096
permissive
[ { "docstring": "Should only be used when inheriting from cms View. Gets the response as a string and caches it with a separate prefix", "name": "get_as_string", "signature": "def get_as_string(self, request, *args, **kwargs)" }, { "docstring": "Overrides Django's default dispatch to provide cach...
2
stack_v2_sparse_classes_30k_train_014331
Implement the Python class `CacheView` described below. Class description: A class based view that overrides the default dispatch method to determine the cache_prefix. If the cms view is available this class will inherit from there otherwise it will inherit from django's generic class View. :param cache_time: How long...
Implement the Python class `CacheView` described below. Class description: A class based view that overrides the default dispatch method to determine the cache_prefix. If the cms view is available this class will inherit from there otherwise it will inherit from django's generic class View. :param cache_time: How long...
9f5ac28618059eef99152214c7a90ad78151629e
<|skeleton|> class CacheView: """A class based view that overrides the default dispatch method to determine the cache_prefix. If the cms view is available this class will inherit from there otherwise it will inherit from django's generic class View. :param cache_time: How long should we cache this attribute. This g...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CacheView: """A class based view that overrides the default dispatch method to determine the cache_prefix. If the cms view is available this class will inherit from there otherwise it will inherit from django's generic class View. :param cache_time: How long should we cache this attribute. This gets passed to...
the_stack_v2_python_sparse
scarlet/cache/views.py
markmiscavage/scarlet
train
1
a02aae8b0ad9829c94253ecbd7d633c80ff9b73a
[ "super().__init__(config)\nself.in_proj_weight = nn.Parameter(torch.cat([vilt_layer.attention.attention.query.weight, vilt_layer.attention.attention.key.weight, vilt_layer.attention.attention.value.weight]))\nself.in_proj_bias = nn.Parameter(torch.cat([vilt_layer.attention.attention.query.bias, vilt_layer.attention...
<|body_start_0|> super().__init__(config) self.in_proj_weight = nn.Parameter(torch.cat([vilt_layer.attention.attention.query.weight, vilt_layer.attention.attention.key.weight, vilt_layer.attention.attention.value.weight])) self.in_proj_bias = nn.Parameter(torch.cat([vilt_layer.attention.attentio...
ViltLayerBetterTransformer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ViltLayerBetterTransformer: def __init__(self, vilt_layer, config): """A simple conversion of the VilTLayer to its `BetterTransformer` implementation. Args: vilt_layer (`torch.nn.Module`): The original `VilTLayer` where the weights needs to be retrieved.""" <|body_0|> def fo...
stack_v2_sparse_classes_36k_train_028355
43,670
no_license
[ { "docstring": "A simple conversion of the VilTLayer to its `BetterTransformer` implementation. Args: vilt_layer (`torch.nn.Module`): The original `VilTLayer` where the weights needs to be retrieved.", "name": "__init__", "signature": "def __init__(self, vilt_layer, config)" }, { "docstring": "T...
2
stack_v2_sparse_classes_30k_train_015342
Implement the Python class `ViltLayerBetterTransformer` described below. Class description: Implement the ViltLayerBetterTransformer class. Method signatures and docstrings: - def __init__(self, vilt_layer, config): A simple conversion of the VilTLayer to its `BetterTransformer` implementation. Args: vilt_layer (`tor...
Implement the Python class `ViltLayerBetterTransformer` described below. Class description: Implement the ViltLayerBetterTransformer class. Method signatures and docstrings: - def __init__(self, vilt_layer, config): A simple conversion of the VilTLayer to its `BetterTransformer` implementation. Args: vilt_layer (`tor...
7e55a422588c1d1e00f35a3d3a3ff896cce59e18
<|skeleton|> class ViltLayerBetterTransformer: def __init__(self, vilt_layer, config): """A simple conversion of the VilTLayer to its `BetterTransformer` implementation. Args: vilt_layer (`torch.nn.Module`): The original `VilTLayer` where the weights needs to be retrieved.""" <|body_0|> def fo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ViltLayerBetterTransformer: def __init__(self, vilt_layer, config): """A simple conversion of the VilTLayer to its `BetterTransformer` implementation. Args: vilt_layer (`torch.nn.Module`): The original `VilTLayer` where the weights needs to be retrieved.""" super().__init__(config) sel...
the_stack_v2_python_sparse
generated/test_huggingface_optimum.py
jansel/pytorch-jit-paritybench
train
35
f355c88e2f97bb9f9f6262b0a99eb2aec8920244
[ "labels_file = os.path.join(os.path.dirname(__file__), 'imagenet_labels.json.gz')\nwith gzip.open(labels_file, 'rb') as file_obj:\n labels = json.load(file_obj)\nreturn labels", "files = IOUtils.find_files(folder, '*.JPEG', recursively=True)\nrandom.shuffle(files)\nif num_files > 0 and num_files < len(files):\...
<|body_start_0|> labels_file = os.path.join(os.path.dirname(__file__), 'imagenet_labels.json.gz') with gzip.open(labels_file, 'rb') as file_obj: labels = json.load(file_obj) return labels <|end_body_0|> <|body_start_1|> files = IOUtils.find_files(folder, '*.JPEG', recursivel...
Filesystem
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Filesystem: def get_labels(): """Load labels from 'imagenet_labels.json.gz' that's located in the same directory as this file. :rtype: dict :return: Dictionary that maps ImageNet class folder ID to an object that contains two fields - 'label' and 'human_labels'. The 'label' is an integer...
stack_v2_sparse_classes_36k_train_028356
8,048
permissive
[ { "docstring": "Load labels from 'imagenet_labels.json.gz' that's located in the same directory as this file. :rtype: dict :return: Dictionary that maps ImageNet class folder ID to an object that contains two fields - 'label' and 'human_labels'. The 'label' is an integer index of a label from [0,1000) according...
2
stack_v2_sparse_classes_30k_train_009525
Implement the Python class `Filesystem` described below. Class description: Implement the Filesystem class. Method signatures and docstrings: - def get_labels(): Load labels from 'imagenet_labels.json.gz' that's located in the same directory as this file. :rtype: dict :return: Dictionary that maps ImageNet class fold...
Implement the Python class `Filesystem` described below. Class description: Implement the Filesystem class. Method signatures and docstrings: - def get_labels(): Load labels from 'imagenet_labels.json.gz' that's located in the same directory as this file. :rtype: dict :return: Dictionary that maps ImageNet class fold...
834350c81154e48af132b7d27874e30a7b80a78c
<|skeleton|> class Filesystem: def get_labels(): """Load labels from 'imagenet_labels.json.gz' that's located in the same directory as this file. :rtype: dict :return: Dictionary that maps ImageNet class folder ID to an object that contains two fields - 'label' and 'human_labels'. The 'label' is an integer...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Filesystem: def get_labels(): """Load labels from 'imagenet_labels.json.gz' that's located in the same directory as this file. :rtype: dict :return: Dictionary that maps ImageNet class folder ID to an object that contains two fields - 'label' and 'human_labels'. The 'label' is an integer index of a la...
the_stack_v2_python_sparse
python/dlbs/data/imagenet/tensorflow_data.py
HewlettPackard/dlcookbook-dlbs
train
132
6bf7841f022e6ba384158abc4cc218f8be6fb3ed
[ "smrys = [x.tojson() for x in SummaryModel.query.filter_by(surveyid=surveyid)]\nif smrys == []:\n return ({'message': \"no summary found for surveyid '{}' \".format(surveyid)}, 400)\nreturn {'summaries': smrys}", "data = resources.parsers.ParseSummariesPost.parser.parse_args()\nsmmry = SummaryModel(data['qid']...
<|body_start_0|> smrys = [x.tojson() for x in SummaryModel.query.filter_by(surveyid=surveyid)] if smrys == []: return ({'message': "no summary found for surveyid '{}' ".format(surveyid)}, 400) return {'summaries': smrys} <|end_body_0|> <|body_start_1|> data = resources.parse...
Internal REST resource: Returns all summaries belonging to a specific survey id. Returns a list with a summary of evaluated reports to an surveyid
Summary
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Summary: """Internal REST resource: Returns all summaries belonging to a specific survey id. Returns a list with a summary of evaluated reports to an surveyid""" def get(self, surveyid): """Internal REST resource: Returns all summaries belonging to a specific survey id. Returns a lis...
stack_v2_sparse_classes_36k_train_028357
3,418
no_license
[ { "docstring": "Internal REST resource: Returns all summaries belonging to a specific survey id. Returns a list with a summary of evaluated reports to an surveyid", "name": "get", "signature": "def get(self, surveyid)" }, { "docstring": "Server REST testing resource: Creates a summary for a spec...
3
stack_v2_sparse_classes_30k_train_002751
Implement the Python class `Summary` described below. Class description: Internal REST resource: Returns all summaries belonging to a specific survey id. Returns a list with a summary of evaluated reports to an surveyid Method signatures and docstrings: - def get(self, surveyid): Internal REST resource: Returns all s...
Implement the Python class `Summary` described below. Class description: Internal REST resource: Returns all summaries belonging to a specific survey id. Returns a list with a summary of evaluated reports to an surveyid Method signatures and docstrings: - def get(self, surveyid): Internal REST resource: Returns all s...
619a7040ab339097b19cf5daccf94c58ee4e2870
<|skeleton|> class Summary: """Internal REST resource: Returns all summaries belonging to a specific survey id. Returns a list with a summary of evaluated reports to an surveyid""" def get(self, surveyid): """Internal REST resource: Returns all summaries belonging to a specific survey id. Returns a lis...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Summary: """Internal REST resource: Returns all summaries belonging to a specific survey id. Returns a list with a summary of evaluated reports to an surveyid""" def get(self, surveyid): """Internal REST resource: Returns all summaries belonging to a specific survey id. Returns a list with a summ...
the_stack_v2_python_sparse
server/resources/summaries.py
yrtsprmb/zappor
train
0
0510b7b92de218233c6649a7fa3f4ae176eea17b
[ "if arr is None:\n return arr\nn = len(arr)\nif n <= 1:\n return arr\nfor i in range(0, n):\n for j in range(0, n - i - 1):\n if arr[j] > arr[j + 1]:\n arr[j + 1], arr[j] = (arr[j], arr[j + 1])\nreturn arr", "if arr is None:\n return arr\nn = len(arr)\nif n <= 1:\n return arr\nfor...
<|body_start_0|> if arr is None: return arr n = len(arr) if n <= 1: return arr for i in range(0, n): for j in range(0, n - i - 1): if arr[j] > arr[j + 1]: arr[j + 1], arr[j] = (arr[j], arr[j + 1]) return arr ...
BubbleSort
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BubbleSort: def bubble_sort(arr): """Bubble sort. :param arr: List[int], list to be sorted :return: List[int], sorted list""" <|body_0|> def bubble_sort_optimized(arr): """Optimized bubble sort. :param arr: List[int], list to be sorted :return: List[int], sorted list...
stack_v2_sparse_classes_36k_train_028358
2,435
permissive
[ { "docstring": "Bubble sort. :param arr: List[int], list to be sorted :return: List[int], sorted list", "name": "bubble_sort", "signature": "def bubble_sort(arr)" }, { "docstring": "Optimized bubble sort. :param arr: List[int], list to be sorted :return: List[int], sorted list", "name": "bub...
2
stack_v2_sparse_classes_30k_train_017192
Implement the Python class `BubbleSort` described below. Class description: Implement the BubbleSort class. Method signatures and docstrings: - def bubble_sort(arr): Bubble sort. :param arr: List[int], list to be sorted :return: List[int], sorted list - def bubble_sort_optimized(arr): Optimized bubble sort. :param ar...
Implement the Python class `BubbleSort` described below. Class description: Implement the BubbleSort class. Method signatures and docstrings: - def bubble_sort(arr): Bubble sort. :param arr: List[int], list to be sorted :return: List[int], sorted list - def bubble_sort_optimized(arr): Optimized bubble sort. :param ar...
8504db89a3f6a1596c0bb7343a4936884b44e6ea
<|skeleton|> class BubbleSort: def bubble_sort(arr): """Bubble sort. :param arr: List[int], list to be sorted :return: List[int], sorted list""" <|body_0|> def bubble_sort_optimized(arr): """Optimized bubble sort. :param arr: List[int], list to be sorted :return: List[int], sorted list...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BubbleSort: def bubble_sort(arr): """Bubble sort. :param arr: List[int], list to be sorted :return: List[int], sorted list""" if arr is None: return arr n = len(arr) if n <= 1: return arr for i in range(0, n): for j in range(0, n - i ...
the_stack_v2_python_sparse
sorting/bubble_sort.py
fimh/dsa-py
train
2
a4600be0a16ad03e0b8c064d10dda43288b92713
[ "context = super().get_serializer_context()\ncontext.update({'redis': self.redis})\nreturn context", "if is_remember:\n response.set_cookie('login_id', login_id, max_age=7 * 24 * 3600)\nelse:\n response.delete_cookie('login_id', login_id)", "serializer = self.get_serializer(data=request.data)\nserializer....
<|body_start_0|> context = super().get_serializer_context() context.update({'redis': self.redis}) return context <|end_body_0|> <|body_start_1|> if is_remember: response.set_cookie('login_id', login_id, max_age=7 * 24 * 3600) else: response.delete_cookie(...
使用JWT登录
LoginAPIView
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LoginAPIView: """使用JWT登录""" def get_serializer_context(self): """添加redis到额外环境中""" <|body_0|> def remember_username(response, is_remember, login_id): """设置cookie,本地暂存用户名1周""" <|body_1|> def post(self, request, *args, **kwargs): """用户登录""" ...
stack_v2_sparse_classes_36k_train_028359
6,225
permissive
[ { "docstring": "添加redis到额外环境中", "name": "get_serializer_context", "signature": "def get_serializer_context(self)" }, { "docstring": "设置cookie,本地暂存用户名1周", "name": "remember_username", "signature": "def remember_username(response, is_remember, login_id)" }, { "docstring": "用户登录", ...
3
null
Implement the Python class `LoginAPIView` described below. Class description: 使用JWT登录 Method signatures and docstrings: - def get_serializer_context(self): 添加redis到额外环境中 - def remember_username(response, is_remember, login_id): 设置cookie,本地暂存用户名1周 - def post(self, request, *args, **kwargs): 用户登录
Implement the Python class `LoginAPIView` described below. Class description: 使用JWT登录 Method signatures and docstrings: - def get_serializer_context(self): 添加redis到额外环境中 - def remember_username(response, is_remember, login_id): 设置cookie,本地暂存用户名1周 - def post(self, request, *args, **kwargs): 用户登录 <|skeleton|> class Lo...
13cb59130d15e782f78bc5148409bef0f1c516e0
<|skeleton|> class LoginAPIView: """使用JWT登录""" def get_serializer_context(self): """添加redis到额外环境中""" <|body_0|> def remember_username(response, is_remember, login_id): """设置cookie,本地暂存用户名1周""" <|body_1|> def post(self, request, *args, **kwargs): """用户登录""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LoginAPIView: """使用JWT登录""" def get_serializer_context(self): """添加redis到额外环境中""" context = super().get_serializer_context() context.update({'redis': self.redis}) return context def remember_username(response, is_remember, login_id): """设置cookie,本地暂存用户名1周""" ...
the_stack_v2_python_sparse
user_app/views/login_register_api.py
lmyfzx/Django-Mall
train
0
a87e1a14a40b4284005aea9c105bbf086018622d
[ "if not change:\n obj.created_by = request.user\nreturn super(AbstractBaseAdmin, self).save_model(request, obj, form, change)", "for form in formset.extra_forms:\n if form.has_changed:\n form.instance.created_by = request.user\nreturn super(AbstractBaseAdmin, self).save_formset(request, form, formset...
<|body_start_0|> if not change: obj.created_by = request.user return super(AbstractBaseAdmin, self).save_model(request, obj, form, change) <|end_body_0|> <|body_start_1|> for form in formset.extra_forms: if form.has_changed: form.instance.created_by = req...
AbstractBaseAdmin
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AbstractBaseAdmin: def save_model(self, request, obj, form, change): """Populate AbstractBase.created_by with the user who submitted the request.""" <|body_0|> def save_formset(self, request, form, formset, change): """Populate AbstractBase.created_by on inlined rela...
stack_v2_sparse_classes_36k_train_028360
1,179
permissive
[ { "docstring": "Populate AbstractBase.created_by with the user who submitted the request.", "name": "save_model", "signature": "def save_model(self, request, obj, form, change)" }, { "docstring": "Populate AbstractBase.created_by on inlined relations with the user who submitted the request.", ...
2
stack_v2_sparse_classes_30k_train_020629
Implement the Python class `AbstractBaseAdmin` described below. Class description: Implement the AbstractBaseAdmin class. Method signatures and docstrings: - def save_model(self, request, obj, form, change): Populate AbstractBase.created_by with the user who submitted the request. - def save_formset(self, request, fo...
Implement the Python class `AbstractBaseAdmin` described below. Class description: Implement the AbstractBaseAdmin class. Method signatures and docstrings: - def save_model(self, request, obj, form, change): Populate AbstractBase.created_by with the user who submitted the request. - def save_formset(self, request, fo...
a271d40922eaad682a76d7700beafc7a5df51fac
<|skeleton|> class AbstractBaseAdmin: def save_model(self, request, obj, form, change): """Populate AbstractBase.created_by with the user who submitted the request.""" <|body_0|> def save_formset(self, request, form, formset, change): """Populate AbstractBase.created_by on inlined rela...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AbstractBaseAdmin: def save_model(self, request, obj, form, change): """Populate AbstractBase.created_by with the user who submitted the request.""" if not change: obj.created_by = request.user return super(AbstractBaseAdmin, self).save_model(request, obj, form, change) ...
the_stack_v2_python_sparse
quizard/admin/AbstractBaseAdmin.py
E7ernal/quizwhiz
train
1
f1ff90793c7bfa2adbf724f453f5b6743233e8a2
[ "self.terminator = '\\n'\nlogging.Handler.__init__(self)\nif stream is None:\n stream = sys.stderr\nself.stream = stream", "self.acquire()\ntry:\n if self.stream and hasattr(self.stream, 'flush'):\n self.stream.flush()\nfinally:\n self.release()", "try:\n msg = self.format(record)\n stream...
<|body_start_0|> self.terminator = '\n' logging.Handler.__init__(self) if stream is None: stream = sys.stderr self.stream = stream <|end_body_0|> <|body_start_1|> self.acquire() try: if self.stream and hasattr(self.stream, 'flush'): ...
Modified from logging.py
CustomStreamHandler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomStreamHandler: """Modified from logging.py""" def __init__(self, stream=None): """Initialize the handler. If stream is not specified, sys.stderr is used.""" <|body_0|> def flush(self): """Flushes the stream.""" <|body_1|> def emit(self, record)...
stack_v2_sparse_classes_36k_train_028361
20,556
permissive
[ { "docstring": "Initialize the handler. If stream is not specified, sys.stderr is used.", "name": "__init__", "signature": "def __init__(self, stream=None)" }, { "docstring": "Flushes the stream.", "name": "flush", "signature": "def flush(self)" }, { "docstring": "Emit a record. ...
3
stack_v2_sparse_classes_30k_train_017277
Implement the Python class `CustomStreamHandler` described below. Class description: Modified from logging.py Method signatures and docstrings: - def __init__(self, stream=None): Initialize the handler. If stream is not specified, sys.stderr is used. - def flush(self): Flushes the stream. - def emit(self, record): Em...
Implement the Python class `CustomStreamHandler` described below. Class description: Modified from logging.py Method signatures and docstrings: - def __init__(self, stream=None): Initialize the handler. If stream is not specified, sys.stderr is used. - def flush(self): Flushes the stream. - def emit(self, record): Em...
6659d953b217748d0b15f0da4cd27fe789e3cd50
<|skeleton|> class CustomStreamHandler: """Modified from logging.py""" def __init__(self, stream=None): """Initialize the handler. If stream is not specified, sys.stderr is used.""" <|body_0|> def flush(self): """Flushes the stream.""" <|body_1|> def emit(self, record)...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CustomStreamHandler: """Modified from logging.py""" def __init__(self, stream=None): """Initialize the handler. If stream is not specified, sys.stderr is used.""" self.terminator = '\n' logging.Handler.__init__(self) if stream is None: stream = sys.stderr ...
the_stack_v2_python_sparse
utool/util_logging.py
Erotemic/utool
train
8
442149997ec81c3ed94adde7d66c8a5e0d2fe72f
[ "super().__init__(screen)\nself._parameters = (screen, position, title, buttons)\nif not isinstance(position, str) or position not in acceptable_positions:\n raise ValueError('Menu->Constructor: position parameter must be one of following strings: left, right, or middle')\nif not isinstance(title, str):\n rai...
<|body_start_0|> super().__init__(screen) self._parameters = (screen, position, title, buttons) if not isinstance(position, str) or position not in acceptable_positions: raise ValueError('Menu->Constructor: position parameter must be one of following strings: left, right, or middle')...
Menu
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Menu: def __init__(self, screen, position, title, buttons): """Constructor constructs Menu object, which will setup the font, title, and all variables required for a menu with buttons""" <|body_0|> def add_button(self, text, callback): """Adds a button to the button ...
stack_v2_sparse_classes_36k_train_028362
4,542
no_license
[ { "docstring": "Constructor constructs Menu object, which will setup the font, title, and all variables required for a menu with buttons", "name": "__init__", "signature": "def __init__(self, screen, position, title, buttons)" }, { "docstring": "Adds a button to the button list on the menu. Take...
4
stack_v2_sparse_classes_30k_train_016230
Implement the Python class `Menu` described below. Class description: Implement the Menu class. Method signatures and docstrings: - def __init__(self, screen, position, title, buttons): Constructor constructs Menu object, which will setup the font, title, and all variables required for a menu with buttons - def add_b...
Implement the Python class `Menu` described below. Class description: Implement the Menu class. Method signatures and docstrings: - def __init__(self, screen, position, title, buttons): Constructor constructs Menu object, which will setup the font, title, and all variables required for a menu with buttons - def add_b...
53f2f04c258051f89bdacf988267bf1cb414d9dd
<|skeleton|> class Menu: def __init__(self, screen, position, title, buttons): """Constructor constructs Menu object, which will setup the font, title, and all variables required for a menu with buttons""" <|body_0|> def add_button(self, text, callback): """Adds a button to the button ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Menu: def __init__(self, screen, position, title, buttons): """Constructor constructs Menu object, which will setup the font, title, and all variables required for a menu with buttons""" super().__init__(screen) self._parameters = (screen, position, title, buttons) if not isins...
the_stack_v2_python_sparse
lib/modules/gui/menu.py
Jacob-Brink/game
train
0
06c9f3d4d9930778900caad8f2978278d9ffb0fe
[ "super(SpfModel, self).__init__()\nself.config = config\nif self.config.mode == 'attn':\n self.multi_head_attention = attn.MultiHeadAttentionLayer(num_heads=config.num_heads, attention_class='SelfAttentionLayer', dim_in=2 * config.dim_embedding, dim_out=config.dim_attn_out, dim_hidden=config.dim_attn_hidden)\n ...
<|body_start_0|> super(SpfModel, self).__init__() self.config = config if self.config.mode == 'attn': self.multi_head_attention = attn.MultiHeadAttentionLayer(num_heads=config.num_heads, attention_class='SelfAttentionLayer', dim_in=2 * config.dim_embedding, dim_out=config.dim_attn_ou...
Implements a neural network with two inputs: 1) Embeddings of neighbors. 2) Embedding of destination The neighborhood encoding is inserted into a multi-head attention mechanism. The embedding of the destination serves as query. The neighborhood embedding as keys and values. The output is passed through a sequence of fu...
SpfModel
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SpfModel: """Implements a neural network with two inputs: 1) Embeddings of neighbors. 2) Embedding of destination The neighborhood encoding is inserted into a multi-head attention mechanism. The embedding of the destination serves as query. The neighborhood embedding as keys and values. The outpu...
stack_v2_sparse_classes_36k_train_028363
11,352
no_license
[ { "docstring": "Initializes object. Args: config:", "name": "__init__", "signature": "def __init__(self, config: SpfConfig)" }, { "docstring": "Perform forward pass. Args: queries: Queries of shape (BS, 1, E). others: Values and Keys of shape (BS, T_max, E). mask: Attention mask of shape (BS, T_...
2
stack_v2_sparse_classes_30k_train_005081
Implement the Python class `SpfModel` described below. Class description: Implements a neural network with two inputs: 1) Embeddings of neighbors. 2) Embedding of destination The neighborhood encoding is inserted into a multi-head attention mechanism. The embedding of the destination serves as query. The neighborhood ...
Implement the Python class `SpfModel` described below. Class description: Implements a neural network with two inputs: 1) Embeddings of neighbors. 2) Embedding of destination The neighborhood encoding is inserted into a multi-head attention mechanism. The embedding of the destination serves as query. The neighborhood ...
914e38474a8dea667e239785f84245eefce10db2
<|skeleton|> class SpfModel: """Implements a neural network with two inputs: 1) Embeddings of neighbors. 2) Embedding of destination The neighborhood encoding is inserted into a multi-head attention mechanism. The embedding of the destination serves as query. The neighborhood embedding as keys and values. The outpu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SpfModel: """Implements a neural network with two inputs: 1) Embeddings of neighbors. 2) Embedding of destination The neighborhood encoding is inserted into a multi-head attention mechanism. The embedding of the destination serves as query. The neighborhood embedding as keys and values. The output is passed t...
the_stack_v2_python_sparse
models/sponly.py
ano-iclr22/mistill
train
0
8d45a3efa38afa94a7bc2263211536f069456f2a
[ "if data is None:\n if lambtha <= 0:\n raise ValueError('lambtha must be a positive value')\n self.lambtha = float(lambtha)\nelif type(data) is not list:\n raise TypeError('data must be a list')\nelif len(data) < 2:\n raise ValueError('data must contain multiple values')\nelse:\n self.lambtha ...
<|body_start_0|> if data is None: if lambtha <= 0: raise ValueError('lambtha must be a positive value') self.lambtha = float(lambtha) elif type(data) is not list: raise TypeError('data must be a list') elif len(data) < 2: raise Valu...
Tye class to call methods of Poisson distribution CDF and PDF
Poisson
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Poisson: """Tye class to call methods of Poisson distribution CDF and PDF""" def __init__(self, data=None, lambtha=1.0): """Initialize method data: type list of given numbers lambtha: type lambda factor to calculate mean of data""" <|body_0|> def pmf(self, k): ""...
stack_v2_sparse_classes_36k_train_028364
1,588
no_license
[ { "docstring": "Initialize method data: type list of given numbers lambtha: type lambda factor to calculate mean of data", "name": "__init__", "signature": "def __init__(self, data=None, lambtha=1.0)" }, { "docstring": "Method Probability Mass Function for Poisson k: integer value of the data re...
3
null
Implement the Python class `Poisson` described below. Class description: Tye class to call methods of Poisson distribution CDF and PDF Method signatures and docstrings: - def __init__(self, data=None, lambtha=1.0): Initialize method data: type list of given numbers lambtha: type lambda factor to calculate mean of dat...
Implement the Python class `Poisson` described below. Class description: Tye class to call methods of Poisson distribution CDF and PDF Method signatures and docstrings: - def __init__(self, data=None, lambtha=1.0): Initialize method data: type list of given numbers lambtha: type lambda factor to calculate mean of dat...
7f9a040f23eda32c5aa154c991c930a01b490f0f
<|skeleton|> class Poisson: """Tye class to call methods of Poisson distribution CDF and PDF""" def __init__(self, data=None, lambtha=1.0): """Initialize method data: type list of given numbers lambtha: type lambda factor to calculate mean of data""" <|body_0|> def pmf(self, k): ""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Poisson: """Tye class to call methods of Poisson distribution CDF and PDF""" def __init__(self, data=None, lambtha=1.0): """Initialize method data: type list of given numbers lambtha: type lambda factor to calculate mean of data""" if data is None: if lambtha <= 0: ...
the_stack_v2_python_sparse
math/0x03-probability/poisson.py
dbaroli/holbertonschool-machine_learning
train
0
623b601cc60ddc8c53f32b4acb616684179ef870
[ "del observation\ndel a\nreturn -1", "del reward\ndel observation\ndel a\nreturn -1" ]
<|body_start_0|> del observation del a return -1 <|end_body_0|> <|body_start_1|> del reward del observation del a return -1 <|end_body_1|>
A MockExploration class that always returns -1.
MockExploration
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MockExploration: """A MockExploration class that always returns -1.""" def begin_episode(self, observation: np.ndarray, a: int) -> int: """Returns the same action passed by the agent.""" <|body_0|> def step(self, reward: float, observation: np.ndarray, a: int) -> int: ...
stack_v2_sparse_classes_36k_train_028365
11,665
permissive
[ { "docstring": "Returns the same action passed by the agent.", "name": "begin_episode", "signature": "def begin_episode(self, observation: np.ndarray, a: int) -> int" }, { "docstring": "Returns the same action passed by the agent.", "name": "step", "signature": "def step(self, reward: fl...
2
stack_v2_sparse_classes_30k_val_000797
Implement the Python class `MockExploration` described below. Class description: A MockExploration class that always returns -1. Method signatures and docstrings: - def begin_episode(self, observation: np.ndarray, a: int) -> int: Returns the same action passed by the agent. - def step(self, reward: float, observation...
Implement the Python class `MockExploration` described below. Class description: A MockExploration class that always returns -1. Method signatures and docstrings: - def begin_episode(self, observation: np.ndarray, a: int) -> int: Returns the same action passed by the agent. - def step(self, reward: float, observation...
72082feccf404e5bf946e513e4f6c0ae8fb279ad
<|skeleton|> class MockExploration: """A MockExploration class that always returns -1.""" def begin_episode(self, observation: np.ndarray, a: int) -> int: """Returns the same action passed by the agent.""" <|body_0|> def step(self, reward: float, observation: np.ndarray, a: int) -> int: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MockExploration: """A MockExploration class that always returns -1.""" def begin_episode(self, observation: np.ndarray, a: int) -> int: """Returns the same action passed by the agent.""" del observation del a return -1 def step(self, reward: float, observation: np.nda...
the_stack_v2_python_sparse
balloon_learning_environment/agents/quantile_agent_test.py
google/balloon-learning-environment
train
108
1310921dc60ff7eec19f424a4298c77c7fc6f917
[ "self.total = total\nself.solved = solved\nself.others = others\nself.locked = locked\nself.time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())\nself.msg = '# Keep thinking, keep alive\\nUntil {}, I have solved **{}** / **{}** problems while **{}** are still locked.\\n\\nCompletion statistic: \\n1. JavaScri...
<|body_start_0|> self.total = total self.solved = solved self.others = others self.locked = locked self.time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) self.msg = '# Keep thinking, keep alive\nUntil {}, I have solved **{}** / **{}** problems while **{}** are s...
generate folder and markdown file update README.md when you finish one problem by some language
Readme
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Readme: """generate folder and markdown file update README.md when you finish one problem by some language""" def __init__(self, total, solved, locked, others=None): """:param total: total problems nums :param solved: solved problem nums :param others: 暂时还没用,我想做扩展""" <|body_0...
stack_v2_sparse_classes_36k_train_028366
10,467
permissive
[ { "docstring": ":param total: total problems nums :param solved: solved problem nums :param others: 暂时还没用,我想做扩展", "name": "__init__", "signature": "def __init__(self, total, solved, locked, others=None)" }, { "docstring": "create REAdME.md :return:", "name": "create_leetcode_readme", "si...
2
stack_v2_sparse_classes_30k_train_021220
Implement the Python class `Readme` described below. Class description: generate folder and markdown file update README.md when you finish one problem by some language Method signatures and docstrings: - def __init__(self, total, solved, locked, others=None): :param total: total problems nums :param solved: solved pr...
Implement the Python class `Readme` described below. Class description: generate folder and markdown file update README.md when you finish one problem by some language Method signatures and docstrings: - def __init__(self, total, solved, locked, others=None): :param total: total problems nums :param solved: solved pr...
f71118e8e05d4bcdcfb2dfc42187c73961b8b926
<|skeleton|> class Readme: """generate folder and markdown file update README.md when you finish one problem by some language""" def __init__(self, total, solved, locked, others=None): """:param total: total problems nums :param solved: solved problem nums :param others: 暂时还没用,我想做扩展""" <|body_0...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Readme: """generate folder and markdown file update README.md when you finish one problem by some language""" def __init__(self, total, solved, locked, others=None): """:param total: total problems nums :param solved: solved problem nums :param others: 暂时还没用,我想做扩展""" self.total = total ...
the_stack_v2_python_sparse
scripts/readme.py
bbruceyuan/algorithms-and-oj
train
11
6364968a8d0c1cb2c18f1c467261b272386e1e38
[ "user = get_authentication(self.request)\nqueryset = Favorites.objects.filter(user=user, is_used=True)\nreturn queryset", "if self.request.method == 'GET':\n serializer_class = FavoriteModelSerializer\nelif self.request.method == 'POST':\n serializer_class = FavoriteCreateSerializer\nelif self.action == 'de...
<|body_start_0|> user = get_authentication(self.request) queryset = Favorites.objects.filter(user=user, is_used=True) return queryset <|end_body_0|> <|body_start_1|> if self.request.method == 'GET': serializer_class = FavoriteModelSerializer elif self.request.method ...
Create favorite items and delete them as well.
FavoritesView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FavoritesView: """Create favorite items and delete them as well.""" def get_queryset(self): """Get the favorite items of the user.""" <|body_0|> def get_serializer_class(self, *args, **kwargs): """Get the serializer class depending of the request method.""" ...
stack_v2_sparse_classes_36k_train_028367
12,742
no_license
[ { "docstring": "Get the favorite items of the user.", "name": "get_queryset", "signature": "def get_queryset(self)" }, { "docstring": "Get the serializer class depending of the request method.", "name": "get_serializer_class", "signature": "def get_serializer_class(self, *args, **kwargs)...
6
stack_v2_sparse_classes_30k_train_007347
Implement the Python class `FavoritesView` described below. Class description: Create favorite items and delete them as well. Method signatures and docstrings: - def get_queryset(self): Get the favorite items of the user. - def get_serializer_class(self, *args, **kwargs): Get the serializer class depending of the req...
Implement the Python class `FavoritesView` described below. Class description: Create favorite items and delete them as well. Method signatures and docstrings: - def get_queryset(self): Get the favorite items of the user. - def get_serializer_class(self, *args, **kwargs): Get the serializer class depending of the req...
cd8767b5eeaef3a09d77c936781b4126fd8591de
<|skeleton|> class FavoritesView: """Create favorite items and delete them as well.""" def get_queryset(self): """Get the favorite items of the user.""" <|body_0|> def get_serializer_class(self, *args, **kwargs): """Get the serializer class depending of the request method.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FavoritesView: """Create favorite items and delete them as well.""" def get_queryset(self): """Get the favorite items of the user.""" user = get_authentication(self.request) queryset = Favorites.objects.filter(user=user, is_used=True) return queryset def get_serialize...
the_stack_v2_python_sparse
api/services/views.py
ignite7/backproject
train
0
654b20e76d60557a7104d47149aaff209de3d9d1
[ "self.big = big\nself.medium = medium\nself.small = small", "if carType == 1:\n if self.big == 0:\n return False\n else:\n self.big -= 1\n return True\nelif carType == 2:\n if self.medium == 0:\n return False\n else:\n self.medium -= 1\n return True\nelif carT...
<|body_start_0|> self.big = big self.medium = medium self.small = small <|end_body_0|> <|body_start_1|> if carType == 1: if self.big == 0: return False else: self.big -= 1 return True elif carType == 2: ...
ParkingSystem
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ParkingSystem: def __init__(self, big, medium, small): """:type big: int :type medium: int :type small: int""" <|body_0|> def addCar(self, carType): """:type carType: int :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.big = big ...
stack_v2_sparse_classes_36k_train_028368
1,674
permissive
[ { "docstring": ":type big: int :type medium: int :type small: int", "name": "__init__", "signature": "def __init__(self, big, medium, small)" }, { "docstring": ":type carType: int :rtype: bool", "name": "addCar", "signature": "def addCar(self, carType)" } ]
2
stack_v2_sparse_classes_30k_val_000476
Implement the Python class `ParkingSystem` described below. Class description: Implement the ParkingSystem class. Method signatures and docstrings: - def __init__(self, big, medium, small): :type big: int :type medium: int :type small: int - def addCar(self, carType): :type carType: int :rtype: bool
Implement the Python class `ParkingSystem` described below. Class description: Implement the ParkingSystem class. Method signatures and docstrings: - def __init__(self, big, medium, small): :type big: int :type medium: int :type small: int - def addCar(self, carType): :type carType: int :rtype: bool <|skeleton|> cla...
b19ae99715f4b7a0d95e32b128a3679e6a298a6f
<|skeleton|> class ParkingSystem: def __init__(self, big, medium, small): """:type big: int :type medium: int :type small: int""" <|body_0|> def addCar(self, carType): """:type carType: int :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ParkingSystem: def __init__(self, big, medium, small): """:type big: int :type medium: int :type small: int""" self.big = big self.medium = medium self.small = small def addCar(self, carType): """:type carType: int :rtype: bool""" if carType == 1: ...
the_stack_v2_python_sparse
1603_design_parking_system.py
mjtsai/leetcode
train
0
333747b2aa8ee2f33516b982a945f2998eeae0e3
[ "a = AssetResolver('pyramid_oereb')\nresolver = a.resolve('lib/renderer/getegrid/templates/xml')\nself.template_dir = resolver.abspath()\nsuper(Renderer, self).__init__(info)", "response = self.get_response(system)\nif isinstance(response, Response) and response.content_type == response.default_content_type:\n ...
<|body_start_0|> a = AssetResolver('pyramid_oereb') resolver = a.resolve('lib/renderer/getegrid/templates/xml') self.template_dir = resolver.abspath() super(Renderer, self).__init__(info) <|end_body_0|> <|body_start_1|> response = self.get_response(system) if isinstance(...
Renderer
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Renderer: def __init__(self, info): """Creates a new XML renderer instance for versions rendering. Args: info (pyramid.interfaces.IRendererInfo): Info object.""" <|body_0|> def __call__(self, value, system): """Returns the XML encoded versions response according to t...
stack_v2_sparse_classes_36k_train_028369
1,690
permissive
[ { "docstring": "Creates a new XML renderer instance for versions rendering. Args: info (pyramid.interfaces.IRendererInfo): Info object.", "name": "__init__", "signature": "def __init__(self, info)" }, { "docstring": "Returns the XML encoded versions response according to the specification. Args:...
2
stack_v2_sparse_classes_30k_train_015188
Implement the Python class `Renderer` described below. Class description: Implement the Renderer class. Method signatures and docstrings: - def __init__(self, info): Creates a new XML renderer instance for versions rendering. Args: info (pyramid.interfaces.IRendererInfo): Info object. - def __call__(self, value, syst...
Implement the Python class `Renderer` described below. Class description: Implement the Renderer class. Method signatures and docstrings: - def __init__(self, info): Creates a new XML renderer instance for versions rendering. Args: info (pyramid.interfaces.IRendererInfo): Info object. - def __call__(self, value, syst...
767375a4adda4589e12c4257377fc30258cdfcb3
<|skeleton|> class Renderer: def __init__(self, info): """Creates a new XML renderer instance for versions rendering. Args: info (pyramid.interfaces.IRendererInfo): Info object.""" <|body_0|> def __call__(self, value, system): """Returns the XML encoded versions response according to t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Renderer: def __init__(self, info): """Creates a new XML renderer instance for versions rendering. Args: info (pyramid.interfaces.IRendererInfo): Info object.""" a = AssetResolver('pyramid_oereb') resolver = a.resolve('lib/renderer/getegrid/templates/xml') self.template_dir = r...
the_stack_v2_python_sparse
pyramid_oereb/lib/renderer/getegrid/xml_.py
geo-bl-ch/pyramid_oereb
train
0
ec64bda35758a1c7da117bb9d1231a9c11a4aae0
[ "for line in self:\n price = line.price_unit * (1 - (line.discount or 0.0) / 100.0) * (1 - (line.discount2 or 0.0) / 100.0)\n taxes = line.tax_id.compute_all(price, line.order_id.currency_id, line.product_uom_qty, product=line.product_id, partner=line.order_id.partner_shipping_id)\n line.update({'price_tax...
<|body_start_0|> for line in self: price = line.price_unit * (1 - (line.discount or 0.0) / 100.0) * (1 - (line.discount2 or 0.0) / 100.0) taxes = line.tax_id.compute_all(price, line.order_id.currency_id, line.product_uom_qty, product=line.product_id, partner=line.order_id.partner_shippin...
SalesOrder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SalesOrder: def _compute_amount(self): """Compute the amounts of the SO line.""" <|body_0|> def _prepare_invoice_line(self, qty): """Prepare the dict of values to create the new invoice line for a sales order line. :param qty: float quantity to invoice""" <|b...
stack_v2_sparse_classes_36k_train_028370
3,359
no_license
[ { "docstring": "Compute the amounts of the SO line.", "name": "_compute_amount", "signature": "def _compute_amount(self)" }, { "docstring": "Prepare the dict of values to create the new invoice line for a sales order line. :param qty: float quantity to invoice", "name": "_prepare_invoice_lin...
2
stack_v2_sparse_classes_30k_train_011198
Implement the Python class `SalesOrder` described below. Class description: Implement the SalesOrder class. Method signatures and docstrings: - def _compute_amount(self): Compute the amounts of the SO line. - def _prepare_invoice_line(self, qty): Prepare the dict of values to create the new invoice line for a sales o...
Implement the Python class `SalesOrder` described below. Class description: Implement the SalesOrder class. Method signatures and docstrings: - def _compute_amount(self): Compute the amounts of the SO line. - def _prepare_invoice_line(self, qty): Prepare the dict of values to create the new invoice line for a sales o...
29909a40920ef3b6a8c6a1f311a8ad67cb6a7985
<|skeleton|> class SalesOrder: def _compute_amount(self): """Compute the amounts of the SO line.""" <|body_0|> def _prepare_invoice_line(self, qty): """Prepare the dict of values to create the new invoice line for a sales order line. :param qty: float quantity to invoice""" <|b...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SalesOrder: def _compute_amount(self): """Compute the amounts of the SO line.""" for line in self: price = line.price_unit * (1 - (line.discount or 0.0) / 100.0) * (1 - (line.discount2 or 0.0) / 100.0) taxes = line.tax_id.compute_all(price, line.order_id.currency_id, li...
the_stack_v2_python_sparse
custom/sales_order/models/sale_order.py
Rombituon-Resource/TRIMITRA
train
0
0a6f27ff0884cfe3fa3210adc5d6a3db4eb50b21
[ "ls_lines = FileUtil.ReadLines(ENF_file)\nls_record = []\nfor line in ls_lines:\n ls_record.append(line[:-1].split(';'))\nls_ENF = []\nfor record in ls_record:\n ls_ENF.append(format(float(record[0]), '.2f'))\njson_ENF = {}\njson_ENF['id'] = ENF_file\njson_ENF['ENF'] = ls_ENF\nreturn json_ENF", "ls_time_exe...
<|body_start_0|> ls_lines = FileUtil.ReadLines(ENF_file) ls_record = [] for line in ls_lines: ls_record.append(line[:-1].split(';')) ls_ENF = [] for record in ls_record: ls_ENF.append(format(float(record[0]), '.2f')) json_ENF = {} json_ENF[...
TenderUtils
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TenderUtils: def load_ENF(ENF_file): """Load ENF data from ENF_file Args: ENF_name: ENF file name Returns: json_ENF: json format ENF data""" <|body_0|> def verify_ENF(ENF_file): """Verify ENF value by querying from blockchain Args: ENF_name: ENF file name Returns: Ve...
stack_v2_sparse_classes_36k_train_028371
9,913
no_license
[ { "docstring": "Load ENF data from ENF_file Args: ENF_name: ENF file name Returns: json_ENF: json format ENF data", "name": "load_ENF", "signature": "def load_ENF(ENF_file)" }, { "docstring": "Verify ENF value by querying from blockchain Args: ENF_name: ENF file name Returns: Verified result: Tr...
3
stack_v2_sparse_classes_30k_train_016821
Implement the Python class `TenderUtils` described below. Class description: Implement the TenderUtils class. Method signatures and docstrings: - def load_ENF(ENF_file): Load ENF data from ENF_file Args: ENF_name: ENF file name Returns: json_ENF: json format ENF data - def verify_ENF(ENF_file): Verify ENF value by qu...
Implement the Python class `TenderUtils` described below. Class description: Implement the TenderUtils class. Method signatures and docstrings: - def load_ENF(ENF_file): Load ENF data from ENF_file Args: ENF_name: ENF file name Returns: json_ENF: json format ENF data - def verify_ENF(ENF_file): Verify ENF value by qu...
03ff57e6fe0114ffd2dd953e79a73a893a6bc0ad
<|skeleton|> class TenderUtils: def load_ENF(ENF_file): """Load ENF data from ENF_file Args: ENF_name: ENF file name Returns: json_ENF: json format ENF data""" <|body_0|> def verify_ENF(ENF_file): """Verify ENF value by querying from blockchain Args: ENF_name: ENF file name Returns: Ve...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TenderUtils: def load_ENF(ENF_file): """Load ENF data from ENF_file Args: ENF_name: ENF file name Returns: json_ENF: json format ENF data""" ls_lines = FileUtil.ReadLines(ENF_file) ls_record = [] for line in ls_lines: ls_record.append(line[:-1].split(';')) l...
the_stack_v2_python_sparse
Security/py_dev/BlendSPS/src/service_utils.py
samuelxu999/Research
train
1
7a45c01e5d8c04ca245da452b3c38e1ef9225b54
[ "with open(self.location, 'r') as csvfile:\n reader = csv.DictReader(csvfile)\n return reader.fieldnames", "try:\n with open(self.location, 'r') as csvfile:\n reader = csv.DictReader(csvfile)\n if params is None:\n params = {}\n rows = []\n for row in reader:\n ...
<|body_start_0|> with open(self.location, 'r') as csvfile: reader = csv.DictReader(csvfile) return reader.fieldnames <|end_body_0|> <|body_start_1|> try: with open(self.location, 'r') as csvfile: reader = csv.DictReader(csvfile) if par...
Data connector for retrieving data from CSV files.
CsvConnector
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CsvConnector: """Data connector for retrieving data from CSV files.""" def get_metadata(self, params: typing.Optional[typing.Mapping[str, str]]=None): """Return a JSON response from a CSV file. :param params: Query params - ignored :return: Metadata""" <|body_0|> def get...
stack_v2_sparse_classes_36k_train_028372
5,585
permissive
[ { "docstring": "Return a JSON response from a CSV file. :param params: Query params - ignored :return: Metadata", "name": "get_metadata", "signature": "def get_metadata(self, params: typing.Optional[typing.Mapping[str, str]]=None)" }, { "docstring": "Return a JSON response from a CSV file. CSV f...
2
null
Implement the Python class `CsvConnector` described below. Class description: Data connector for retrieving data from CSV files. Method signatures and docstrings: - def get_metadata(self, params: typing.Optional[typing.Mapping[str, str]]=None): Return a JSON response from a CSV file. :param params: Query params - ign...
Implement the Python class `CsvConnector` described below. Class description: Data connector for retrieving data from CSV files. Method signatures and docstrings: - def get_metadata(self, params: typing.Optional[typing.Mapping[str, str]]=None): Return a JSON response from a CSV file. :param params: Query params - ign...
25a111ac7cf4b23fee50ad8eac6ea21564954859
<|skeleton|> class CsvConnector: """Data connector for retrieving data from CSV files.""" def get_metadata(self, params: typing.Optional[typing.Mapping[str, str]]=None): """Return a JSON response from a CSV file. :param params: Query params - ignored :return: Metadata""" <|body_0|> def get...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CsvConnector: """Data connector for retrieving data from CSV files.""" def get_metadata(self, params: typing.Optional[typing.Mapping[str, str]]=None): """Return a JSON response from a CSV file. :param params: Query params - ignored :return: Metadata""" with open(self.location, 'r') as csv...
the_stack_v2_python_sparse
datasources/connectors/csv.py
PEDASI/PEDASI
train
0
dc8603948e13bba6de24566639f318c78b85c9cb
[ "queryset = get_user_model().objects.all()\nserializer = ProfileSerializer(queryset, many=True)\nreturn Response(serializer.data)", "data = request.data.get('profile')\nif not data:\n return Response({'response': 'error', 'message': 'profile 파라미터가 없습니다.'})\nserializer = ProfileSerializer(data=data)\nif seriali...
<|body_start_0|> queryset = get_user_model().objects.all() serializer = ProfileSerializer(queryset, many=True) return Response(serializer.data) <|end_body_0|> <|body_start_1|> data = request.data.get('profile') if not data: return Response({'response': 'error', 'mess...
CreateProfileView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CreateProfileView: def get(self, request, *args, **kwargs): """# 기능 전체 유저 조회""" <|body_0|> def post(self, request, *args, **kwargs): """# 기능 회원 가입 # example { "profile": { "username": "rkdalstjd1", "password": "password1", "email": "rkdalstjd9@naver.com", "nickname":...
stack_v2_sparse_classes_36k_train_028373
13,056
no_license
[ { "docstring": "# 기능 전체 유저 조회", "name": "get", "signature": "def get(self, request, *args, **kwargs)" }, { "docstring": "# 기능 회원 가입 # example { \"profile\": { \"username\": \"rkdalstjd1\", \"password\": \"password1\", \"email\": \"rkdalstjd9@naver.com\", \"nickname\": \"사장님2\", \"address\": \"서울...
2
stack_v2_sparse_classes_30k_train_003045
Implement the Python class `CreateProfileView` described below. Class description: Implement the CreateProfileView class. Method signatures and docstrings: - def get(self, request, *args, **kwargs): # 기능 전체 유저 조회 - def post(self, request, *args, **kwargs): # 기능 회원 가입 # example { "profile": { "username": "rkdalstjd1",...
Implement the Python class `CreateProfileView` described below. Class description: Implement the CreateProfileView class. Method signatures and docstrings: - def get(self, request, *args, **kwargs): # 기능 전체 유저 조회 - def post(self, request, *args, **kwargs): # 기능 회원 가입 # example { "profile": { "username": "rkdalstjd1",...
e7b1638a15a804faf513e25da57c4a2202b5cc0d
<|skeleton|> class CreateProfileView: def get(self, request, *args, **kwargs): """# 기능 전체 유저 조회""" <|body_0|> def post(self, request, *args, **kwargs): """# 기능 회원 가입 # example { "profile": { "username": "rkdalstjd1", "password": "password1", "email": "rkdalstjd9@naver.com", "nickname":...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CreateProfileView: def get(self, request, *args, **kwargs): """# 기능 전체 유저 조회""" queryset = get_user_model().objects.all() serializer = ProfileSerializer(queryset, many=True) return Response(serializer.data) def post(self, request, *args, **kwargs): """# 기능 회원 가입 # ...
the_stack_v2_python_sparse
laundry_guest/backend/src/project/myauth/views.py
serverdevcamp/camp4_ing
train
2
3659d158856a2feeb2e0680b0bf2eb2142f1c3a5
[ "k = None\ngo = True\nfor i in range(len(nums) - 1, -1, -1):\n for j in range(i + 1, len(nums)):\n if nums[i] < nums[j] and (k is None or nums[j] < nums[k]):\n k = j\n if k is not None:\n nums[i], nums[k] = (nums[k], nums[i])\n nums[i + 1:] = sorted(nums[i + 1:])\n break...
<|body_start_0|> k = None go = True for i in range(len(nums) - 1, -1, -1): for j in range(i + 1, len(nums)): if nums[i] < nums[j] and (k is None or nums[j] < nums[k]): k = j if k is not None: nums[i], nums[k] = (nums[k],...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def nextPermutation(self, nums): """:type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.""" <|body_0|> def permuteUnique(self, nums): """:type nums: List[int] :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_36k_train_028374
2,067
no_license
[ { "docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.", "name": "nextPermutation", "signature": "def nextPermutation(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: List[List[int]]", "name": "permuteUnique", "signature": "d...
2
stack_v2_sparse_classes_30k_train_013959
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def nextPermutation(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. - def permuteUnique(self, nums): :type nums: List[int] :...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def nextPermutation(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. - def permuteUnique(self, nums): :type nums: List[int] :...
c026f2969c784827fac702b34b07a9268b70b62a
<|skeleton|> class Solution: def nextPermutation(self, nums): """:type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.""" <|body_0|> def permuteUnique(self, nums): """:type nums: List[int] :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def nextPermutation(self, nums): """:type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.""" k = None go = True for i in range(len(nums) - 1, -1, -1): for j in range(i + 1, len(nums)): if nums[i] < nums[j]...
the_stack_v2_python_sparse
codes/contest/leetcode/permutations-ii.py
jiluhu/dirtysalt.github.io
train
0
e56ef8154e810b318a2c122efcf9df289d6bd2a6
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')" ]
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
Proto file describing the Asset service. Service to manage assets. Asset types can be created with AssetService are YoutubeVideoAsset, MediaBundleAsset and ImageAsset. TextAsset should be created with Ad inline.
AssetServiceServicer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AssetServiceServicer: """Proto file describing the Asset service. Service to manage assets. Asset types can be created with AssetService are YoutubeVideoAsset, MediaBundleAsset and ImageAsset. TextAsset should be created with Ad inline.""" def GetAsset(self, request, context): """Ret...
stack_v2_sparse_classes_36k_train_028375
5,542
permissive
[ { "docstring": "Returns the requested asset in full detail.", "name": "GetAsset", "signature": "def GetAsset(self, request, context)" }, { "docstring": "Creates assets. Operation statuses are returned.", "name": "MutateAssets", "signature": "def MutateAssets(self, request, context)" } ...
2
stack_v2_sparse_classes_30k_train_020666
Implement the Python class `AssetServiceServicer` described below. Class description: Proto file describing the Asset service. Service to manage assets. Asset types can be created with AssetService are YoutubeVideoAsset, MediaBundleAsset and ImageAsset. TextAsset should be created with Ad inline. Method signatures an...
Implement the Python class `AssetServiceServicer` described below. Class description: Proto file describing the Asset service. Service to manage assets. Asset types can be created with AssetService are YoutubeVideoAsset, MediaBundleAsset and ImageAsset. TextAsset should be created with Ad inline. Method signatures an...
a5b6cede64f4d9912ae6ad26927a54e40448c9fe
<|skeleton|> class AssetServiceServicer: """Proto file describing the Asset service. Service to manage assets. Asset types can be created with AssetService are YoutubeVideoAsset, MediaBundleAsset and ImageAsset. TextAsset should be created with Ad inline.""" def GetAsset(self, request, context): """Ret...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AssetServiceServicer: """Proto file describing the Asset service. Service to manage assets. Asset types can be created with AssetService are YoutubeVideoAsset, MediaBundleAsset and ImageAsset. TextAsset should be created with Ad inline.""" def GetAsset(self, request, context): """Returns the requ...
the_stack_v2_python_sparse
google/ads/google_ads/v5/proto/services/asset_service_pb2_grpc.py
fiboknacky/google-ads-python
train
0
1bf36e0a628b420712ed774573a5788398be10fb
[ "self.data_dir = data_dir\nself.batch_size = batch_size\nself.image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms_face_recog[x]) for x in ['train', 'val']}\nself.dataloaders = {x: torch.utils.data.DataLoader(self.image_datasets[x], batch_size=self.batch_size, shuffle=True, num_worke...
<|body_start_0|> self.data_dir = data_dir self.batch_size = batch_size self.image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms_face_recog[x]) for x in ['train', 'val']} self.dataloaders = {x: torch.utils.data.DataLoader(self.image_datasets[x], batch_size...
A class to dataset with its loader. ... Attributes ---------- dataloaders : torch dataloader dataset_sizes : length of train and validation dataset class_names : class names Methods ------- show_batch: Shows five sample images for verification of dataloaders
LoadFaceDataset
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LoadFaceDataset: """A class to dataset with its loader. ... Attributes ---------- dataloaders : torch dataloader dataset_sizes : length of train and validation dataset class_names : class names Methods ------- show_batch: Shows five sample images for verification of dataloaders""" def __init...
stack_v2_sparse_classes_36k_train_028376
9,192
permissive
[ { "docstring": "Initialize the class object. Dataset class ojbect", "name": "__init__", "signature": "def __init__(self, data_dir, batch_size)" }, { "docstring": "Show five sample images for verification of dataloaders. Get item internal fuction", "name": "show_batch", "signature": "def ...
2
stack_v2_sparse_classes_30k_train_014224
Implement the Python class `LoadFaceDataset` described below. Class description: A class to dataset with its loader. ... Attributes ---------- dataloaders : torch dataloader dataset_sizes : length of train and validation dataset class_names : class names Methods ------- show_batch: Shows five sample images for verific...
Implement the Python class `LoadFaceDataset` described below. Class description: A class to dataset with its loader. ... Attributes ---------- dataloaders : torch dataloader dataset_sizes : length of train and validation dataset class_names : class names Methods ------- show_batch: Shows five sample images for verific...
7c551e3894979cc425dd51baeddbfa5a51b7878d
<|skeleton|> class LoadFaceDataset: """A class to dataset with its loader. ... Attributes ---------- dataloaders : torch dataloader dataset_sizes : length of train and validation dataset class_names : class names Methods ------- show_batch: Shows five sample images for verification of dataloaders""" def __init...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LoadFaceDataset: """A class to dataset with its loader. ... Attributes ---------- dataloaders : torch dataloader dataset_sizes : length of train and validation dataset class_names : class names Methods ------- show_batch: Shows five sample images for verification of dataloaders""" def __init__(self, data...
the_stack_v2_python_sparse
Modules/data_loader.py
EVA4-RS-Group/Phase2
train
0
6f4cb55a74da7b43fc3207dbc5a2f8ed41a29270
[ "self.p = p\nself.k = k\nself.dat = dat", "J = V.shape[0]\nX = self.dat.data()\nn, d = X.shape\nfssd = FSSD(self.p, self.k, V, null_sim=None, alpha=None)\nblock_rows = util.constrain(50000 // (d * J), 10, 5000)\navg_rows = []\nfor f, t in util.ChunkIterable(start=0, end=n, chunk_size=block_rows):\n assert f < ...
<|body_start_0|> self.p = p self.k = k self.dat = dat <|end_body_0|> <|body_start_1|> J = V.shape[0] X = self.dat.data() n, d = X.shape fssd = FSSD(self.p, self.k, V, null_sim=None, alpha=None) block_rows = util.constrain(50000 // (d * J), 10, 5000) ...
Construct a callable object representing the Stein witness function. The witness function g is defined as in Eq. 1 of A Linear-Time Kernel Goodness-of-Fit Test Wittawat Jitkrittum, Wenkai Xu, Zoltan Szabo, Kenji Fukumizu, Arthur Gretton NIPS 2017 The witness function requires taking an expectation over the sample gener...
SteinWitness
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SteinWitness: """Construct a callable object representing the Stein witness function. The witness function g is defined as in Eq. 1 of A Linear-Time Kernel Goodness-of-Fit Test Wittawat Jitkrittum, Wenkai Xu, Zoltan Szabo, Kenji Fukumizu, Arthur Gretton NIPS 2017 The witness function requires tak...
stack_v2_sparse_classes_36k_train_028377
41,550
permissive
[ { "docstring": ":params p: an UnnormalizedDensity object :params k: a DifferentiableKernel :params dat: a kgof.data.Data", "name": "__init__", "signature": "def __init__(self, p, k, dat)" }, { "docstring": ":params V: a numpy array of size J x d (data matrix) :returns (J x d) numpy array represe...
2
stack_v2_sparse_classes_30k_train_006106
Implement the Python class `SteinWitness` described below. Class description: Construct a callable object representing the Stein witness function. The witness function g is defined as in Eq. 1 of A Linear-Time Kernel Goodness-of-Fit Test Wittawat Jitkrittum, Wenkai Xu, Zoltan Szabo, Kenji Fukumizu, Arthur Gretton NIPS...
Implement the Python class `SteinWitness` described below. Class description: Construct a callable object representing the Stein witness function. The witness function g is defined as in Eq. 1 of A Linear-Time Kernel Goodness-of-Fit Test Wittawat Jitkrittum, Wenkai Xu, Zoltan Szabo, Kenji Fukumizu, Arthur Gretton NIPS...
039a95ed9d8062e283da6bd051b7161a190b4876
<|skeleton|> class SteinWitness: """Construct a callable object representing the Stein witness function. The witness function g is defined as in Eq. 1 of A Linear-Time Kernel Goodness-of-Fit Test Wittawat Jitkrittum, Wenkai Xu, Zoltan Szabo, Kenji Fukumizu, Arthur Gretton NIPS 2017 The witness function requires tak...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SteinWitness: """Construct a callable object representing the Stein witness function. The witness function g is defined as in Eq. 1 of A Linear-Time Kernel Goodness-of-Fit Test Wittawat Jitkrittum, Wenkai Xu, Zoltan Szabo, Kenji Fukumizu, Arthur Gretton NIPS 2017 The witness function requires taking an expect...
the_stack_v2_python_sparse
kgof/goftest.py
wittawatj/kernel-gof
train
69
5fcbf9e26312bdeb82d6991a2b3d7997501675eb
[ "src_type, src_path = cls.identify_path_type(src)\ndest_type, dest_path = cls.identify_path_type(dest)\nformat_table = {'s3': cls.format_s3_path, 'local': cls.format_local_path}\nsrc_path = format_table[src_type](src_path)[0]\ndest_path, use_src_name = format_table[dest_type](dest_path)\nreturn {'dest': {'path': de...
<|body_start_0|> src_type, src_path = cls.identify_path_type(src) dest_type, dest_path = cls.identify_path_type(dest) format_table = {'s3': cls.format_s3_path, 'local': cls.format_local_path} src_path = format_table[src_type](src_path)[0] dest_path, use_src_name = format_table[de...
Path format base class.
FormatPath
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FormatPath: """Path format base class.""" def format(cls, src: str, dest: str) -> FormatPathResult: """Format the source and destination for use in the file factory.""" <|body_0|> def format_local_path(path: str, dir_op: bool=True) -> Tuple[str, bool]: """Format ...
stack_v2_sparse_classes_36k_train_028378
4,460
permissive
[ { "docstring": "Format the source and destination for use in the file factory.", "name": "format", "signature": "def format(cls, src: str, dest: str) -> FormatPathResult" }, { "docstring": "Format the path of local files. Returns whether the destination will keep its own name or take the source'...
4
stack_v2_sparse_classes_30k_train_020115
Implement the Python class `FormatPath` described below. Class description: Path format base class. Method signatures and docstrings: - def format(cls, src: str, dest: str) -> FormatPathResult: Format the source and destination for use in the file factory. - def format_local_path(path: str, dir_op: bool=True) -> Tupl...
Implement the Python class `FormatPath` described below. Class description: Path format base class. Method signatures and docstrings: - def format(cls, src: str, dest: str) -> FormatPathResult: Format the source and destination for use in the file factory. - def format_local_path(path: str, dir_op: bool=True) -> Tupl...
0763b06aee07d2cf3f037a49ca0cb81a048c5deb
<|skeleton|> class FormatPath: """Path format base class.""" def format(cls, src: str, dest: str) -> FormatPathResult: """Format the source and destination for use in the file factory.""" <|body_0|> def format_local_path(path: str, dir_op: bool=True) -> Tuple[str, bool]: """Format ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FormatPath: """Path format base class.""" def format(cls, src: str, dest: str) -> FormatPathResult: """Format the source and destination for use in the file factory.""" src_type, src_path = cls.identify_path_type(src) dest_type, dest_path = cls.identify_path_type(dest) for...
the_stack_v2_python_sparse
runway/core/providers/aws/s3/_helpers/format_path.py
onicagroup/runway
train
156
62f96a6d2ff09586914263ebfbdb2827d8ad5e38
[ "view = cls.as_view('annual_expenses')\napp.add_url_rule('/api/budgets/<int:budget_id>/annual-expenses', defaults={'expense_id': None}, view_func=view, methods=['GET'])\napp.add_url_rule('/api/budgets/<int:budget_id>/annual-expenses', view_func=view, methods=['POST'])\napp.add_url_rule('/api/budget-annual-expenses/...
<|body_start_0|> view = cls.as_view('annual_expenses') app.add_url_rule('/api/budgets/<int:budget_id>/annual-expenses', defaults={'expense_id': None}, view_func=view, methods=['GET']) app.add_url_rule('/api/budgets/<int:budget_id>/annual-expenses', view_func=view, methods=['POST']) app.a...
Annual expense REST resource view
AnnualExpensesView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AnnualExpensesView: """Annual expense REST resource view""" def register(cls, app: Flask): """Registers routes for this view""" <|body_0|> def get(budget_id: Optional[int], expense_id: Optional[int]): """Gets a specific annual expense or all expenses in the speci...
stack_v2_sparse_classes_36k_train_028379
17,779
permissive
[ { "docstring": "Registers routes for this view", "name": "register", "signature": "def register(cls, app: Flask)" }, { "docstring": "Gets a specific annual expense or all expenses in the specified budget", "name": "get", "signature": "def get(budget_id: Optional[int], expense_id: Optiona...
5
stack_v2_sparse_classes_30k_train_012066
Implement the Python class `AnnualExpensesView` described below. Class description: Annual expense REST resource view Method signatures and docstrings: - def register(cls, app: Flask): Registers routes for this view - def get(budget_id: Optional[int], expense_id: Optional[int]): Gets a specific annual expense or all ...
Implement the Python class `AnnualExpensesView` described below. Class description: Annual expense REST resource view Method signatures and docstrings: - def register(cls, app: Flask): Registers routes for this view - def get(budget_id: Optional[int], expense_id: Optional[int]): Gets a specific annual expense or all ...
20d992356952542fd79aab69849a04129fa22de2
<|skeleton|> class AnnualExpensesView: """Annual expense REST resource view""" def register(cls, app: Flask): """Registers routes for this view""" <|body_0|> def get(budget_id: Optional[int], expense_id: Optional[int]): """Gets a specific annual expense or all expenses in the speci...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AnnualExpensesView: """Annual expense REST resource view""" def register(cls, app: Flask): """Registers routes for this view""" view = cls.as_view('annual_expenses') app.add_url_rule('/api/budgets/<int:budget_id>/annual-expenses', defaults={'expense_id': None}, view_func=view, met...
the_stack_v2_python_sparse
backend/underbudget/views/budgets.py
vimofthevine/underbudget4
train
0
075e78da05c720e4cfb0370919761dff851a46be
[ "if not root:\n return 0\nchildren = [root.left, root.right]\nif not any(children):\n return 1\nmin_depth = float('inf')\nfor x in children:\n if x:\n min_depth = min(self.minDepth_BFS_recursion(x), min_depth)\nreturn min_depth + 1\npass", "if not root:\n return 0\nstack = deque([(root, 1)])\nw...
<|body_start_0|> if not root: return 0 children = [root.left, root.right] if not any(children): return 1 min_depth = float('inf') for x in children: if x: min_depth = min(self.minDepth_BFS_recursion(x), min_depth) return...
1.栈 2.递归 return: 返回数字代表二叉树的深度。
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: """1.栈 2.递归 return: 返回数字代表二叉树的深度。""" def minDepth_DFS_recursion(self, root: TreeNode): """递归遍历,找出最小深度 复杂度分析 N - 节点数量 时间复杂度:O(N) 访问所有节点一次 空间复杂度: 最坏情况下,树是非平衡树,O(N) 最好情况下,完全平衡树,高度只有log(N),这时复杂度只有O(log(N)) :param root: :return:""" <|body_0|> def minDepth_BFS_queue(...
stack_v2_sparse_classes_36k_train_028380
2,378
no_license
[ { "docstring": "递归遍历,找出最小深度 复杂度分析 N - 节点数量 时间复杂度:O(N) 访问所有节点一次 空间复杂度: 最坏情况下,树是非平衡树,O(N) 最好情况下,完全平衡树,高度只有log(N),这时复杂度只有O(log(N)) :param root: :return:", "name": "minDepth_DFS_recursion", "signature": "def minDepth_DFS_recursion(self, root: TreeNode)" }, { "docstring": ":param root: :return:", ...
2
null
Implement the Python class `Solution` described below. Class description: 1.栈 2.递归 return: 返回数字代表二叉树的深度。 Method signatures and docstrings: - def minDepth_DFS_recursion(self, root: TreeNode): 递归遍历,找出最小深度 复杂度分析 N - 节点数量 时间复杂度:O(N) 访问所有节点一次 空间复杂度: 最坏情况下,树是非平衡树,O(N) 最好情况下,完全平衡树,高度只有log(N),这时复杂度只有O(log(N)) :param root: :r...
Implement the Python class `Solution` described below. Class description: 1.栈 2.递归 return: 返回数字代表二叉树的深度。 Method signatures and docstrings: - def minDepth_DFS_recursion(self, root: TreeNode): 递归遍历,找出最小深度 复杂度分析 N - 节点数量 时间复杂度:O(N) 访问所有节点一次 空间复杂度: 最坏情况下,树是非平衡树,O(N) 最好情况下,完全平衡树,高度只有log(N),这时复杂度只有O(log(N)) :param root: :r...
62ad010a992c031e8c0fe4d1a9b6f9364f96ed4c
<|skeleton|> class Solution: """1.栈 2.递归 return: 返回数字代表二叉树的深度。""" def minDepth_DFS_recursion(self, root: TreeNode): """递归遍历,找出最小深度 复杂度分析 N - 节点数量 时间复杂度:O(N) 访问所有节点一次 空间复杂度: 最坏情况下,树是非平衡树,O(N) 最好情况下,完全平衡树,高度只有log(N),这时复杂度只有O(log(N)) :param root: :return:""" <|body_0|> def minDepth_BFS_queue(...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: """1.栈 2.递归 return: 返回数字代表二叉树的深度。""" def minDepth_DFS_recursion(self, root: TreeNode): """递归遍历,找出最小深度 复杂度分析 N - 节点数量 时间复杂度:O(N) 访问所有节点一次 空间复杂度: 最坏情况下,树是非平衡树,O(N) 最好情况下,完全平衡树,高度只有log(N),这时复杂度只有O(log(N)) :param root: :return:""" if not root: return 0 children =...
the_stack_v2_python_sparse
leetcode/solved/111_.py
usnnu/python_foundation
train
0
5ab1ef018811ab2e46fbd5412ac2ca820e9a5588
[ "try:\n setattr(type(self), '__optimize_not_implemented__', True)\n out = self.self_optimize_with_info(dataset, **kwargs)[0]\n delattr(type(self), '__optimize_not_implemented__')\nexcept NotImplementedError as e:\n raise NotImplementedError() from e\nreturn out", "try:\n if getattr(type(self), '__o...
<|body_start_0|> try: setattr(type(self), '__optimize_not_implemented__', True) out = self.self_optimize_with_info(dataset, **kwargs)[0] delattr(type(self), '__optimize_not_implemented__') except NotImplementedError as e: raise NotImplementedError() from e...
Pipeline with custom ways to optimize and/or train input parameters. OptimizablePipelines are expected to implement a concrete way to train internal models or optimize parameters. This should not be a reimplementation of GridSearch or similar methods. For this :class:`tpcp.pipelines.GridSearch` should be used directly....
OptimizablePipeline
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OptimizablePipeline: """Pipeline with custom ways to optimize and/or train input parameters. OptimizablePipelines are expected to implement a concrete way to train internal models or optimize parameters. This should not be a reimplementation of GridSearch or similar methods. For this :class:`tpcp...
stack_v2_sparse_classes_36k_train_028381
7,840
permissive
[ { "docstring": "Optimize the input parameters of the pipeline or algorithm using any logic. This method can be used to adapt the input parameters (values provided in the init) based on any data driven heuristic. .. note:: The optimizations must only modify the input parameters (aka `self.clone` should retain th...
2
stack_v2_sparse_classes_30k_train_013845
Implement the Python class `OptimizablePipeline` described below. Class description: Pipeline with custom ways to optimize and/or train input parameters. OptimizablePipelines are expected to implement a concrete way to train internal models or optimize parameters. This should not be a reimplementation of GridSearch or...
Implement the Python class `OptimizablePipeline` described below. Class description: Pipeline with custom ways to optimize and/or train input parameters. OptimizablePipelines are expected to implement a concrete way to train internal models or optimize parameters. This should not be a reimplementation of GridSearch or...
75b958ee691d6d5b0eee070c1eb20d1017ec619b
<|skeleton|> class OptimizablePipeline: """Pipeline with custom ways to optimize and/or train input parameters. OptimizablePipelines are expected to implement a concrete way to train internal models or optimize parameters. This should not be a reimplementation of GridSearch or similar methods. For this :class:`tpcp...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OptimizablePipeline: """Pipeline with custom ways to optimize and/or train input parameters. OptimizablePipelines are expected to implement a concrete way to train internal models or optimize parameters. This should not be a reimplementation of GridSearch or similar methods. For this :class:`tpcp.pipelines.Gr...
the_stack_v2_python_sparse
tpcp/_pipeline.py
mad-lab-fau/tpcp
train
11
3ebe466b39a087faf193e6e556191f7af318a320
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AuthenticationMethodsPolicy()", "from .authentication_method_configuration import AuthenticationMethodConfiguration\nfrom .authentication_methods_policy_migration_state import AuthenticationMethodsPolicyMigrationState\nfrom .entity imp...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return AuthenticationMethodsPolicy() <|end_body_0|> <|body_start_1|> from .authentication_method_configuration import AuthenticationMethodConfiguration from .authentication_methods_policy_migra...
AuthenticationMethodsPolicy
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AuthenticationMethodsPolicy: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuthenticationMethodsPolicy: """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 a...
stack_v2_sparse_classes_36k_train_028382
5,875
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: AuthenticationMethodsPolicy", "name": "create_from_discriminator_value", "signature": "def create_from_discr...
3
null
Implement the Python class `AuthenticationMethodsPolicy` described below. Class description: Implement the AuthenticationMethodsPolicy class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuthenticationMethodsPolicy: Creates a new instance of the appr...
Implement the Python class `AuthenticationMethodsPolicy` described below. Class description: Implement the AuthenticationMethodsPolicy class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuthenticationMethodsPolicy: Creates a new instance of the appr...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class AuthenticationMethodsPolicy: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuthenticationMethodsPolicy: """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 a...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AuthenticationMethodsPolicy: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuthenticationMethodsPolicy: """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 ...
the_stack_v2_python_sparse
msgraph/generated/models/authentication_methods_policy.py
microsoftgraph/msgraph-sdk-python
train
135
74e3565f82b2a7eb54cdf3d676b33f0c4d62fc49
[ "self.screen_width = 1200\nself.screen_height = 800\nself.bg_color = (230, 230, 230)\nself.ship_limit = 3\nself.bullet_width = 10\nself.bullet_height = 15\nself.bullet_color = (60, 60, 60)\nself.bullets_allowed = 6\nself.fleet_drop_speed = 20\nself.speedup_scale = 1.1\nself.score_scale = 1.5\nself.initialize_dynami...
<|body_start_0|> self.screen_width = 1200 self.screen_height = 800 self.bg_color = (230, 230, 230) self.ship_limit = 3 self.bullet_width = 10 self.bullet_height = 15 self.bullet_color = (60, 60, 60) self.bullets_allowed = 6 self.fleet_drop_speed = ...
存储《外星人入侵》的所有设置的类
Settings
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Settings: """存储《外星人入侵》的所有设置的类""" def __init__(self): """初始化游戏的静态设置""" <|body_0|> def initialize_dynamic_settings(self): """初始化随着游戏进行而变化的设置""" <|body_1|> def increase_speed(self): """提高速度设置""" <|body_2|> <|end_skeleton|> <|body_start...
stack_v2_sparse_classes_36k_train_028383
1,704
no_license
[ { "docstring": "初始化游戏的静态设置", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "初始化随着游戏进行而变化的设置", "name": "initialize_dynamic_settings", "signature": "def initialize_dynamic_settings(self)" }, { "docstring": "提高速度设置", "name": "increase_speed", "signa...
3
stack_v2_sparse_classes_30k_train_002956
Implement the Python class `Settings` described below. Class description: 存储《外星人入侵》的所有设置的类 Method signatures and docstrings: - def __init__(self): 初始化游戏的静态设置 - def initialize_dynamic_settings(self): 初始化随着游戏进行而变化的设置 - def increase_speed(self): 提高速度设置
Implement the Python class `Settings` described below. Class description: 存储《外星人入侵》的所有设置的类 Method signatures and docstrings: - def __init__(self): 初始化游戏的静态设置 - def initialize_dynamic_settings(self): 初始化随着游戏进行而变化的设置 - def increase_speed(self): 提高速度设置 <|skeleton|> class Settings: """存储《外星人入侵》的所有设置的类""" def __...
61e92d51227962d361123109d5d4a2b460175069
<|skeleton|> class Settings: """存储《外星人入侵》的所有设置的类""" def __init__(self): """初始化游戏的静态设置""" <|body_0|> def initialize_dynamic_settings(self): """初始化随着游戏进行而变化的设置""" <|body_1|> def increase_speed(self): """提高速度设置""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Settings: """存储《外星人入侵》的所有设置的类""" def __init__(self): """初始化游戏的静态设置""" self.screen_width = 1200 self.screen_height = 800 self.bg_color = (230, 230, 230) self.ship_limit = 3 self.bullet_width = 10 self.bullet_height = 15 self.bullet_color = (6...
the_stack_v2_python_sparse
aliens/settings.py
yangrencong/pythonstudy
train
0
94d722f388d674c4b4bb8fdf9a1434a2c73d061e
[ "super(AgeFilter, self).__init__(order)\nself.age = age\nself.ageField = ageField\nself.ageTolerance = ageTolerance\nif self.ageTolerance < 0:\n self.ageTolerance = 0\nself.minAgeField = minAgeField\nself.maxAgeField = maxAgeField\nself.rejectUnclassified = rejectUnclassified", "for result in results:\n if ...
<|body_start_0|> super(AgeFilter, self).__init__(order) self.age = age self.ageField = ageField self.ageTolerance = ageTolerance if self.ageTolerance < 0: self.ageTolerance = 0 self.minAgeField = minAgeField self.maxAgeField = maxAgeField self....
Filters search results based on either a specific age or if the age is within an age range defined by the result. Note: there is no default value for 'age' it must be passed to this filter so that it can be customised for the application using it. Options: * order (int): filter precedence * age (integer) : the age of t...
AgeFilter
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AgeFilter: """Filters search results based on either a specific age or if the age is within an age range defined by the result. Note: there is no default value for 'age' it must be passed to this filter so that it can be customised for the application using it. Options: * order (int): filter prec...
stack_v2_sparse_classes_36k_train_028384
2,776
permissive
[ { "docstring": "Constructor for AgeFilter", "name": "__init__", "signature": "def __init__(self, age, ageField=None, ageTolerance=3, minAgeField='minAge', maxAgeField='maxAge', order=0, rejectUnclassified=False)" }, { "docstring": "Filters the results according to a given range in which the resu...
2
stack_v2_sparse_classes_30k_train_013863
Implement the Python class `AgeFilter` described below. Class description: Filters search results based on either a specific age or if the age is within an age range defined by the result. Note: there is no default value for 'age' it must be passed to this filter so that it can be customised for the application using ...
Implement the Python class `AgeFilter` described below. Class description: Filters search results based on either a specific age or if the age is within an age range defined by the result. Note: there is no default value for 'age' it must be passed to this filter so that it can be customised for the application using ...
ed72aee466649bd834d5b4459eb6e0173df6e2ec
<|skeleton|> class AgeFilter: """Filters search results based on either a specific age or if the age is within an age range defined by the result. Note: there is no default value for 'age' it must be passed to this filter so that it can be customised for the application using it. Options: * order (int): filter prec...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AgeFilter: """Filters search results based on either a specific age or if the age is within an age range defined by the result. Note: there is no default value for 'age' it must be passed to this filter so that it can be customised for the application using it. Options: * order (int): filter precedence * age ...
the_stack_v2_python_sparse
reference-code/puppy/result/filter/ageFilter.py
Granvanoeli/ifind
train
0
8c69076d6771f495c32aedeb40fa7c6e1815beae
[ "assert next is Node.empty or isinstance(next, Node)\nself.item = item\nself.next = next", "if self.next:\n next_str = ', ' + repr(self.next)\nelse:\n next_str = ''\nreturn 'Node({0}{1})'.format(self.item, next_str)" ]
<|body_start_0|> assert next is Node.empty or isinstance(next, Node) self.item = item self.next = next <|end_body_0|> <|body_start_1|> if self.next: next_str = ', ' + repr(self.next) else: next_str = '' return 'Node({0}{1})'.format(self.item, next...
Node
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Node: def __init__(self, item, next=empty): """init a node""" <|body_0|> def __repr__(self): """它实现Node类的repr()函数""" <|body_1|> <|end_skeleton|> <|body_start_0|> assert next is Node.empty or isinstance(next, Node) self.item = item se...
stack_v2_sparse_classes_36k_train_028385
3,171
no_license
[ { "docstring": "init a node", "name": "__init__", "signature": "def __init__(self, item, next=empty)" }, { "docstring": "它实现Node类的repr()函数", "name": "__repr__", "signature": "def __repr__(self)" } ]
2
stack_v2_sparse_classes_30k_train_019671
Implement the Python class `Node` described below. Class description: Implement the Node class. Method signatures and docstrings: - def __init__(self, item, next=empty): init a node - def __repr__(self): 它实现Node类的repr()函数
Implement the Python class `Node` described below. Class description: Implement the Node class. Method signatures and docstrings: - def __init__(self, item, next=empty): init a node - def __repr__(self): 它实现Node类的repr()函数 <|skeleton|> class Node: def __init__(self, item, next=empty): """init a node""" ...
c431569ae08fb77c67e948f5ded75c306af20ba2
<|skeleton|> class Node: def __init__(self, item, next=empty): """init a node""" <|body_0|> def __repr__(self): """它实现Node类的repr()函数""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Node: def __init__(self, item, next=empty): """init a node""" assert next is Node.empty or isinstance(next, Node) self.item = item self.next = next def __repr__(self): """它实现Node类的repr()函数""" if self.next: next_str = ', ' + repr(self.next) ...
the_stack_v2_python_sparse
algo-lib/1_basic/Python/LinkedQueue.py
itrowa/arsenal
train
0
197829184cb24021170fa3b05836ea0ef845c0dc
[ "self.type = type\nself.name = name\nself.width = width\nself.cls = cls", "assert elem.tag in ['input', 'output', 'clock'], elem.tag\nport = Port(type=PortType.from_string(elem.tag), name=elem.attrib['name'], width=int(elem.get('num_pins', '1')), cls=elem.get('port_class', None))\nreturn port", "if range_spec i...
<|body_start_0|> self.type = type self.name = name self.width = width self.cls = cls <|end_body_0|> <|body_start_1|> assert elem.tag in ['input', 'output', 'clock'], elem.tag port = Port(type=PortType.from_string(elem.tag), name=elem.attrib['name'], width=int(elem.get('n...
A port of pb_type
Port
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Port: """A port of pb_type""" def __init__(self, type, name, width=1, cls=None): """Basic constructor""" <|body_0|> def from_etree(elem): """Create the object from its ElementTree representation""" <|body_1|> def yield_pins(self, range_spec=None): ...
stack_v2_sparse_classes_36k_train_028386
11,880
permissive
[ { "docstring": "Basic constructor", "name": "__init__", "signature": "def __init__(self, type, name, width=1, cls=None)" }, { "docstring": "Create the object from its ElementTree representation", "name": "from_etree", "signature": "def from_etree(elem)" }, { "docstring": "Yields ...
3
stack_v2_sparse_classes_30k_train_018450
Implement the Python class `Port` described below. Class description: A port of pb_type Method signatures and docstrings: - def __init__(self, type, name, width=1, cls=None): Basic constructor - def from_etree(elem): Create the object from its ElementTree representation - def yield_pins(self, range_spec=None): Yields...
Implement the Python class `Port` described below. Class description: A port of pb_type Method signatures and docstrings: - def __init__(self, type, name, width=1, cls=None): Basic constructor - def from_etree(elem): Create the object from its ElementTree representation - def yield_pins(self, range_spec=None): Yields...
835a40534f9efd70770d74f56f25fef6cfc6ebc6
<|skeleton|> class Port: """A port of pb_type""" def __init__(self, type, name, width=1, cls=None): """Basic constructor""" <|body_0|> def from_etree(elem): """Create the object from its ElementTree representation""" <|body_1|> def yield_pins(self, range_spec=None): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Port: """A port of pb_type""" def __init__(self, type, name, width=1, cls=None): """Basic constructor""" self.type = type self.name = name self.width = width self.cls = cls def from_etree(elem): """Create the object from its ElementTree representation"...
the_stack_v2_python_sparse
f4pga/utils/quicklogic/repacker/pb_type.py
f4pga/f4pga
train
19
f81f8f325de4d2b29662b70777cf97b8fc5957d1
[ "Parametre.__init__(self, 'vitesse', 'speed')\nself.schema = '<vitesse_rames>'\nself.aide_courte = 'change la vitesse des rames'\nself.aide_longue = \"Cette commande permet de modifier la vitesse des rames que vous tenez en main. Les vitesses disponibles sont |cmd|arrière|ff| (pour aller en marche arrière), |cmd|im...
<|body_start_0|> Parametre.__init__(self, 'vitesse', 'speed') self.schema = '<vitesse_rames>' self.aide_courte = 'change la vitesse des rames' self.aide_longue = "Cette commande permet de modifier la vitesse des rames que vous tenez en main. Les vitesses disponibles sont |cmd|arrière|ff|...
Commande 'rames vitesse'.
PrmVitesse
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PrmVitesse: """Commande 'rames vitesse'.""" def __init__(self): """Constructeur du paramètre""" <|body_0|> def interpreter(self, personnage, dic_masques): """Interprétation du paramètre""" <|body_1|> <|end_skeleton|> <|body_start_0|> Parametre._...
stack_v2_sparse_classes_36k_train_028387
3,270
permissive
[ { "docstring": "Constructeur du paramètre", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Interprétation du paramètre", "name": "interpreter", "signature": "def interpreter(self, personnage, dic_masques)" } ]
2
stack_v2_sparse_classes_30k_train_008797
Implement the Python class `PrmVitesse` described below. Class description: Commande 'rames vitesse'. Method signatures and docstrings: - def __init__(self): Constructeur du paramètre - def interpreter(self, personnage, dic_masques): Interprétation du paramètre
Implement the Python class `PrmVitesse` described below. Class description: Commande 'rames vitesse'. Method signatures and docstrings: - def __init__(self): Constructeur du paramètre - def interpreter(self, personnage, dic_masques): Interprétation du paramètre <|skeleton|> class PrmVitesse: """Commande 'rames v...
7e93bff08cdf891352efba587e89c40f3b4a2301
<|skeleton|> class PrmVitesse: """Commande 'rames vitesse'.""" def __init__(self): """Constructeur du paramètre""" <|body_0|> def interpreter(self, personnage, dic_masques): """Interprétation du paramètre""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PrmVitesse: """Commande 'rames vitesse'.""" def __init__(self): """Constructeur du paramètre""" Parametre.__init__(self, 'vitesse', 'speed') self.schema = '<vitesse_rames>' self.aide_courte = 'change la vitesse des rames' self.aide_longue = "Cette commande permet d...
the_stack_v2_python_sparse
src/secondaires/navigation/commandes/rames/vitesse.py
vincent-lg/tsunami
train
5
7f33c54c5db11af6c66d07aa6980ebd34bdda34e
[ "super().__init__()\nself._securities_cache: Optional[pd.DataFrame] = None\nself._cache_lock = asyncio.Lock()", "name = self._log_and_validate_group(table_name, outer.SECURITIES)\nif name != outer.SECURITIES:\n raise outer.DataError(f'Некорректное имя таблицы для обновления {table_name}')\nasync with self._cac...
<|body_start_0|> super().__init__() self._securities_cache: Optional[pd.DataFrame] = None self._cache_lock = asyncio.Lock() <|end_body_0|> <|body_start_1|> name = self._log_and_validate_group(table_name, outer.SECURITIES) if name != outer.SECURITIES: raise outer.Data...
Информация о всех торгующихся акциях.
SecuritiesLoader
[ "Unlicense" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SecuritiesLoader: """Информация о всех торгующихся акциях.""" def __init__(self) -> None: """Кэшируются данные, чтобы сократить количество обращений к серверу MOEX.""" <|body_0|> async def get(self, table_name: outer.TableName) -> pd.DataFrame: """Получение списк...
stack_v2_sparse_classes_36k_train_028388
6,612
permissive
[ { "docstring": "Кэшируются данные, чтобы сократить количество обращений к серверу MOEX.", "name": "__init__", "signature": "def __init__(self) -> None" }, { "docstring": "Получение списка торгуемых акций с регистрационным номером и размером лота.", "name": "get", "signature": "async def ...
2
stack_v2_sparse_classes_30k_train_015611
Implement the Python class `SecuritiesLoader` described below. Class description: Информация о всех торгующихся акциях. Method signatures and docstrings: - def __init__(self) -> None: Кэшируются данные, чтобы сократить количество обращений к серверу MOEX. - async def get(self, table_name: outer.TableName) -> pd.DataF...
Implement the Python class `SecuritiesLoader` described below. Class description: Информация о всех торгующихся акциях. Method signatures and docstrings: - def __init__(self) -> None: Кэшируются данные, чтобы сократить количество обращений к серверу MOEX. - async def get(self, table_name: outer.TableName) -> pd.DataF...
e5d0f2c28de25568e4515b63aaad4aa337e2e522
<|skeleton|> class SecuritiesLoader: """Информация о всех торгующихся акциях.""" def __init__(self) -> None: """Кэшируются данные, чтобы сократить количество обращений к серверу MOEX.""" <|body_0|> async def get(self, table_name: outer.TableName) -> pd.DataFrame: """Получение списк...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SecuritiesLoader: """Информация о всех торгующихся акциях.""" def __init__(self) -> None: """Кэшируются данные, чтобы сократить количество обращений к серверу MOEX.""" super().__init__() self._securities_cache: Optional[pd.DataFrame] = None self._cache_lock = asyncio.Lock(...
the_stack_v2_python_sparse
poptimizer/data/adapters/loaders/moex.py
chekanskiy/poptimizer
train
0
b544a372cea723344477e32bd93eb56a61f278dc
[ "i = 0\nj = len(height) - 1\nres = 0\nwhile i < j:\n tmp = min(height[j], height[i]) * (j - i)\n if tmp > res:\n res = tmp\n if height[i] < height[j]:\n i += 1\n else:\n j -= 1\nreturn res", "i, j, max_v = (0, len(height) - 1, 0)\nwhile i < j:\n if height[i] < height[j]:\n ...
<|body_start_0|> i = 0 j = len(height) - 1 res = 0 while i < j: tmp = min(height[j], height[i]) * (j - i) if tmp > res: res = tmp if height[i] < height[j]: i += 1 else: j -= 1 return r...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxArea(self, height): """:type height: List[int] :rtype: int""" <|body_0|> def maxArea0(self, height): """:type height: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> i = 0 j = len(height) - 1 re...
stack_v2_sparse_classes_36k_train_028389
1,039
no_license
[ { "docstring": ":type height: List[int] :rtype: int", "name": "maxArea", "signature": "def maxArea(self, height)" }, { "docstring": ":type height: List[int] :rtype: int", "name": "maxArea0", "signature": "def maxArea0(self, height)" } ]
2
stack_v2_sparse_classes_30k_train_012716
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxArea(self, height): :type height: List[int] :rtype: int - def maxArea0(self, height): :type height: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxArea(self, height): :type height: List[int] :rtype: int - def maxArea0(self, height): :type height: List[int] :rtype: int <|skeleton|> class Solution: def maxArea(se...
9e49b2c6003b957276737005d4aaac276b44d251
<|skeleton|> class Solution: def maxArea(self, height): """:type height: List[int] :rtype: int""" <|body_0|> def maxArea0(self, height): """:type height: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxArea(self, height): """:type height: List[int] :rtype: int""" i = 0 j = len(height) - 1 res = 0 while i < j: tmp = min(height[j], height[i]) * (j - i) if tmp > res: res = tmp if height[i] < height[j]: ...
the_stack_v2_python_sparse
PythonCode/src/0011_Container_With_Most_Water.py
oneyuan/CodeforFun
train
0
34987daad6f9d8bf613f54da8ab0978568c8ace2
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.appleManagedIdentityProvider'.casefold():\n...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') try: mapping_value = parse_node.get_child_node('@odata.type').get_str_value() except AttributeError: mapping_value = None if mapping_value and mapping_value.casefold() ==...
IdentityProviderBase
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IdentityProviderBase: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityProviderBase: """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 ...
stack_v2_sparse_classes_36k_train_028390
4,982
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: IdentityProviderBase", "name": "create_from_discriminator_value", "signature": "def create_from_discriminato...
3
null
Implement the Python class `IdentityProviderBase` described below. Class description: Implement the IdentityProviderBase class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityProviderBase: Creates a new instance of the appropriate class based o...
Implement the Python class `IdentityProviderBase` described below. Class description: Implement the IdentityProviderBase class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityProviderBase: Creates a new instance of the appropriate class based o...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class IdentityProviderBase: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityProviderBase: """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 ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class IdentityProviderBase: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityProviderBase: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns...
the_stack_v2_python_sparse
msgraph/generated/models/identity_provider_base.py
microsoftgraph/msgraph-sdk-python
train
135
6f07312fa13518413ccaa6d8a4b00f67d49a1d93
[ "self._check_access(request)\nawait self._change_password(data[ATTR_USERNAME], data[ATTR_PASSWORD])\nreturn web.Response(status=HTTP_OK)", "provider = self._get_provider()\ntry:\n await self.hass.async_add_executor_job(provider.data.change_password, username, password)\n await provider.data.async_save()\nex...
<|body_start_0|> self._check_access(request) await self._change_password(data[ATTR_USERNAME], data[ATTR_PASSWORD]) return web.Response(status=HTTP_OK) <|end_body_0|> <|body_start_1|> provider = self._get_provider() try: await self.hass.async_add_executor_job(provider...
Hass.io view to handle password reset requests.
HassIOPasswordReset
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HassIOPasswordReset: """Hass.io view to handle password reset requests.""" async def post(self, request, data): """Handle password reset requests.""" <|body_0|> async def _change_password(self, username, password): """Check User credentials.""" <|body_1|>...
stack_v2_sparse_classes_36k_train_028391
4,251
permissive
[ { "docstring": "Handle password reset requests.", "name": "post", "signature": "async def post(self, request, data)" }, { "docstring": "Check User credentials.", "name": "_change_password", "signature": "async def _change_password(self, username, password)" } ]
2
null
Implement the Python class `HassIOPasswordReset` described below. Class description: Hass.io view to handle password reset requests. Method signatures and docstrings: - async def post(self, request, data): Handle password reset requests. - async def _change_password(self, username, password): Check User credentials.
Implement the Python class `HassIOPasswordReset` described below. Class description: Hass.io view to handle password reset requests. Method signatures and docstrings: - async def post(self, request, data): Handle password reset requests. - async def _change_password(self, username, password): Check User credentials. ...
ba55b4b8338a2dc0ba3f1d750efea49d86571291
<|skeleton|> class HassIOPasswordReset: """Hass.io view to handle password reset requests.""" async def post(self, request, data): """Handle password reset requests.""" <|body_0|> async def _change_password(self, username, password): """Check User credentials.""" <|body_1|>...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HassIOPasswordReset: """Hass.io view to handle password reset requests.""" async def post(self, request, data): """Handle password reset requests.""" self._check_access(request) await self._change_password(data[ATTR_USERNAME], data[ATTR_PASSWORD]) return web.Response(statu...
the_stack_v2_python_sparse
homeassistant/components/hassio/auth.py
basnijholt/home-assistant
train
5
ceb4452c1d2962045cef531f5f74ea60a19c819d
[ "super(CustomBatchNormManualModule, self).__init__()\nself.n_neurons = n_neurons\nself.eps = eps\nself.params = nn.ParameterDict({'gamma': nn.Parameter(torch.ones(n_neurons)), 'beta': nn.Parameter(torch.zeros(n_neurons))})", "_n_batch, n_neurons = input.shape\nassert n_neurons == self.n_neurons\np = self.params\n...
<|body_start_0|> super(CustomBatchNormManualModule, self).__init__() self.n_neurons = n_neurons self.eps = eps self.params = nn.ParameterDict({'gamma': nn.Parameter(torch.ones(n_neurons)), 'beta': nn.Parameter(torch.zeros(n_neurons))}) <|end_body_0|> <|body_start_1|> _n_batch, n...
This nn.module implements a custom version of the batch norm operation for MLPs. In self.forward the functional version CustomBatchNormManualFunction.forward is called. The automatic differentiation of PyTorch calls the backward method of this function in the backward pass.
CustomBatchNormManualModule
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomBatchNormManualModule: """This nn.module implements a custom version of the batch norm operation for MLPs. In self.forward the functional version CustomBatchNormManualFunction.forward is called. The automatic differentiation of PyTorch calls the backward method of this function in the backw...
stack_v2_sparse_classes_36k_train_028392
7,737
no_license
[ { "docstring": "Initializes CustomBatchNormManualModule object. Args: n_neurons: int specifying the number of neurons eps: small float to be added to the variance for stability", "name": "__init__", "signature": "def __init__(self, n_neurons, eps=1e-05)" }, { "docstring": "Compute the batch norm...
2
stack_v2_sparse_classes_30k_train_006549
Implement the Python class `CustomBatchNormManualModule` described below. Class description: This nn.module implements a custom version of the batch norm operation for MLPs. In self.forward the functional version CustomBatchNormManualFunction.forward is called. The automatic differentiation of PyTorch calls the backwa...
Implement the Python class `CustomBatchNormManualModule` described below. Class description: This nn.module implements a custom version of the batch norm operation for MLPs. In self.forward the functional version CustomBatchNormManualFunction.forward is called. The automatic differentiation of PyTorch calls the backwa...
b2cd0d67337b101f3e204e519625e1aaf3cea43b
<|skeleton|> class CustomBatchNormManualModule: """This nn.module implements a custom version of the batch norm operation for MLPs. In self.forward the functional version CustomBatchNormManualFunction.forward is called. The automatic differentiation of PyTorch calls the backward method of this function in the backw...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CustomBatchNormManualModule: """This nn.module implements a custom version of the batch norm operation for MLPs. In self.forward the functional version CustomBatchNormManualFunction.forward is called. The automatic differentiation of PyTorch calls the backward method of this function in the backward pass.""" ...
the_stack_v2_python_sparse
assignment_1/code/custom_batchnorm.py
Ivan-Yovchev/uvadlc_practicals_2019
train
0
05003744d55b715b69a9d752c97af9a6ed80b796
[ "if energy_modes is None:\n energy_modes = [1, 2, 3, 4]\nsuper().__init__((npart, None, np.dtype('float64')))\nself._makeAttributeAndRegister('npart', 'alpha', 'k', 'energy_modes', localVars=locals(), readOnly=True)\nself.dx = self.npart / 32 / (self.npart + 1)\nself.xvalues = np.array([(i + 1) * self.dx for i i...
<|body_start_0|> if energy_modes is None: energy_modes = [1, 2, 3, 4] super().__init__((npart, None, np.dtype('float64'))) self._makeAttributeAndRegister('npart', 'alpha', 'k', 'energy_modes', localVars=locals(), readOnly=True) self.dx = self.npart / 32 / (self.npart + 1) ...
Example implementing the outer solar system problem TODO : doku
fermi_pasta_ulam_tsingou
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class fermi_pasta_ulam_tsingou: """Example implementing the outer solar system problem TODO : doku""" def __init__(self, npart=2048, alpha=0.25, k=1.0, energy_modes=None): """Initialization routine""" <|body_0|> def eval_f(self, u, t): """Routine to compute the right-h...
stack_v2_sparse_classes_36k_train_028393
4,420
permissive
[ { "docstring": "Initialization routine", "name": "__init__", "signature": "def __init__(self, npart=2048, alpha=0.25, k=1.0, energy_modes=None)" }, { "docstring": "Routine to compute the right-hand side of the problem. Parameters ---------- u : dtype_u Current values of the numerical solution. t...
5
null
Implement the Python class `fermi_pasta_ulam_tsingou` described below. Class description: Example implementing the outer solar system problem TODO : doku Method signatures and docstrings: - def __init__(self, npart=2048, alpha=0.25, k=1.0, energy_modes=None): Initialization routine - def eval_f(self, u, t): Routine t...
Implement the Python class `fermi_pasta_ulam_tsingou` described below. Class description: Example implementing the outer solar system problem TODO : doku Method signatures and docstrings: - def __init__(self, npart=2048, alpha=0.25, k=1.0, energy_modes=None): Initialization routine - def eval_f(self, u, t): Routine t...
1a51834bedffd4472e344bed28f4d766614b1537
<|skeleton|> class fermi_pasta_ulam_tsingou: """Example implementing the outer solar system problem TODO : doku""" def __init__(self, npart=2048, alpha=0.25, k=1.0, energy_modes=None): """Initialization routine""" <|body_0|> def eval_f(self, u, t): """Routine to compute the right-h...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class fermi_pasta_ulam_tsingou: """Example implementing the outer solar system problem TODO : doku""" def __init__(self, npart=2048, alpha=0.25, k=1.0, energy_modes=None): """Initialization routine""" if energy_modes is None: energy_modes = [1, 2, 3, 4] super().__init__((npa...
the_stack_v2_python_sparse
pySDC/implementations/problem_classes/FermiPastaUlamTsingou.py
Parallel-in-Time/pySDC
train
30
09edf147777f1ff5956cb528ee35ae9c7e033b25
[ "super(DeviceTarget, self).__init__()\nself.region = region\nself.role = role\nself.network = network\nself.hostname = hostname\nself.realm = 'ACQ_CHROME'\nself.alertable = True\nself._fields = ('region', 'role', 'network', 'hostname')", "collection.network_device.metro = self.region\ncollection.network_device.ro...
<|body_start_0|> super(DeviceTarget, self).__init__() self.region = region self.role = role self.network = network self.hostname = hostname self.realm = 'ACQ_CHROME' self.alertable = True self._fields = ('region', 'role', 'network', 'hostname') <|end_body_...
Monitoring interface class for monitoring specific hosts or devices.
DeviceTarget
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DeviceTarget: """Monitoring interface class for monitoring specific hosts or devices.""" def __init__(self, region, role, network, hostname): """Create a Target object exporting info about a specific device. Args: region (str): physical region in which the device is located. role (st...
stack_v2_sparse_classes_36k_train_028394
4,448
permissive
[ { "docstring": "Create a Target object exporting info about a specific device. Args: region (str): physical region in which the device is located. role (str): role of the device. network (str): virtual network on which the device is located. hostname (str): name by which the device self-identifies.", "name"...
2
null
Implement the Python class `DeviceTarget` described below. Class description: Monitoring interface class for monitoring specific hosts or devices. Method signatures and docstrings: - def __init__(self, region, role, network, hostname): Create a Target object exporting info about a specific device. Args: region (str):...
Implement the Python class `DeviceTarget` described below. Class description: Monitoring interface class for monitoring specific hosts or devices. Method signatures and docstrings: - def __init__(self, region, role, network, hostname): Create a Target object exporting info about a specific device. Args: region (str):...
53102de187a48ac2cfc241fef54dcbc29c453a8e
<|skeleton|> class DeviceTarget: """Monitoring interface class for monitoring specific hosts or devices.""" def __init__(self, region, role, network, hostname): """Create a Target object exporting info about a specific device. Args: region (str): physical region in which the device is located. role (st...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DeviceTarget: """Monitoring interface class for monitoring specific hosts or devices.""" def __init__(self, region, role, network, hostname): """Create a Target object exporting info about a specific device. Args: region (str): physical region in which the device is located. role (str): role of t...
the_stack_v2_python_sparse
third_party/gae_ts_mon/gae_ts_mon/common/targets.py
catapult-project/catapult
train
2,032
a031cf07188b030fd2f62a91a875c51551611af2
[ "self = object.__new__(cls)\nself.entity_id = entity_id\nself.max_level = max_level\nself.expires_at = 0.0\nKOKORO.call_after(SEX_RESET_AFTER, self)\nreturn self", "expires_at = self.expires_at\nif expires_at:\n KOKORO.call_at(expires_at + SEX_RESET_AFTER, self)\nelse:\n try:\n del SEX_SPAM_LOCK[self...
<|body_start_0|> self = object.__new__(cls) self.entity_id = entity_id self.max_level = max_level self.expires_at = 0.0 KOKORO.call_after(SEX_RESET_AFTER, self) return self <|end_body_0|> <|body_start_1|> expires_at = self.expires_at if expires_at: ...
Sex spam lock used to avoid sex spam. Or you could say to promote it by not giving. Attributes ----------- entity_id : `int` The locked entity's identifier. expires_at : `float` When the lock expires in monotonic time. max_level : `int` The max allowed sex rarity level.
SexSpamLock
[ "LicenseRef-scancode-warranty-disclaimer" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SexSpamLock: """Sex spam lock used to avoid sex spam. Or you could say to promote it by not giving. Attributes ----------- entity_id : `int` The locked entity's identifier. expires_at : `float` When the lock expires in monotonic time. max_level : `int` The max allowed sex rarity level.""" de...
stack_v2_sparse_classes_36k_train_028395
2,651
no_license
[ { "docstring": "Creates a new sex spam lock. Parameters ---------- entity_id : `int` The locked entity's identifier. max_level : `int` The max allowed sex rarity level.", "name": "__new__", "signature": "def __new__(cls, entity_id, max_level)" }, { "docstring": "Called when sex lock expires. Set...
3
null
Implement the Python class `SexSpamLock` described below. Class description: Sex spam lock used to avoid sex spam. Or you could say to promote it by not giving. Attributes ----------- entity_id : `int` The locked entity's identifier. expires_at : `float` When the lock expires in monotonic time. max_level : `int` The m...
Implement the Python class `SexSpamLock` described below. Class description: Sex spam lock used to avoid sex spam. Or you could say to promote it by not giving. Attributes ----------- entity_id : `int` The locked entity's identifier. expires_at : `float` When the lock expires in monotonic time. max_level : `int` The m...
74f92b598e86606ea3a269311316cddd84a5215f
<|skeleton|> class SexSpamLock: """Sex spam lock used to avoid sex spam. Or you could say to promote it by not giving. Attributes ----------- entity_id : `int` The locked entity's identifier. expires_at : `float` When the lock expires in monotonic time. max_level : `int` The max allowed sex rarity level.""" de...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SexSpamLock: """Sex spam lock used to avoid sex spam. Or you could say to promote it by not giving. Attributes ----------- entity_id : `int` The locked entity's identifier. expires_at : `float` When the lock expires in monotonic time. max_level : `int` The max allowed sex rarity level.""" def __new__(cls...
the_stack_v2_python_sparse
koishi/plugins/sex/lock.py
HuyaneMatsu/Koishi
train
17
823bc1e89d231d64d9d94568134e5d365a373315
[ "list_of_links = response.xpath('//*/a[@class=\"exhibitorName\"]/@href').extract()\nfor link in list_of_links:\n yield scrapy.Request(response.urljoin(link), callback=self.parse_data)", "url = 'https://retailx.a2zinc.net/RetailX2020/Public/Exhibitors.aspx?ID=23735'\nitem = RetailXItem()\nitem['url'] = url\nnam...
<|body_start_0|> list_of_links = response.xpath('//*/a[@class="exhibitorName"]/@href').extract() for link in list_of_links: yield scrapy.Request(response.urljoin(link), callback=self.parse_data) <|end_body_0|> <|body_start_1|> url = 'https://retailx.a2zinc.net/RetailX2020/Public/Exh...
Spider to get the data from the online.marketing
RetailX
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RetailX: """Spider to get the data from the online.marketing""" def parse(self, response): """Method checks for the shops :param response: the fully downloaded webpagage :return:""" <|body_0|> def parse_data(self, response): """Method get the the data of the tool...
stack_v2_sparse_classes_36k_train_028396
2,112
no_license
[ { "docstring": "Method checks for the shops :param response: the fully downloaded webpagage :return:", "name": "parse", "signature": "def parse(self, response)" }, { "docstring": "Method get the the data of the tools :param response: :return:", "name": "parse_data", "signature": "def par...
2
stack_v2_sparse_classes_30k_train_003149
Implement the Python class `RetailX` described below. Class description: Spider to get the data from the online.marketing Method signatures and docstrings: - def parse(self, response): Method checks for the shops :param response: the fully downloaded webpagage :return: - def parse_data(self, response): Method get the...
Implement the Python class `RetailX` described below. Class description: Spider to get the data from the online.marketing Method signatures and docstrings: - def parse(self, response): Method checks for the shops :param response: the fully downloaded webpagage :return: - def parse_data(self, response): Method get the...
64a7ec204166532fc653f7001f288179e45d1046
<|skeleton|> class RetailX: """Spider to get the data from the online.marketing""" def parse(self, response): """Method checks for the shops :param response: the fully downloaded webpagage :return:""" <|body_0|> def parse_data(self, response): """Method get the the data of the tool...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RetailX: """Spider to get the data from the online.marketing""" def parse(self, response): """Method checks for the shops :param response: the fully downloaded webpagage :return:""" list_of_links = response.xpath('//*/a[@class="exhibitorName"]/@href').extract() for link in list_of...
the_stack_v2_python_sparse
AutoScrapy/spiders/retailx.py
SpaceZZ/AutoScrapyProject2
train
0
57b1e04975007a3ef7f568210e2df10349342df9
[ "super().__init__(name, 's')\nself.n_points_per_dim = n_points_per_dim\nself.predictions_dict = dict()\nself.hidden_outputs_dict = dict()\nself.x_unique = np.linspace(dataset.test.x.min(axis=1), dataset.test.x.max(axis=1), num=n_points_per_dim, axis=1)\nx_mesh = np.meshgrid(*self.x_unique)\nself.x_pred = np.stack([...
<|body_start_0|> super().__init__(name, 's') self.n_points_per_dim = n_points_per_dim self.predictions_dict = dict() self.hidden_outputs_dict = dict() self.x_unique = np.linspace(dataset.test.x.min(axis=1), dataset.test.x.max(axis=1), num=n_points_per_dim, axis=1) x_mesh ...
This column is for storing predictions of the model during training. Once training is complete, this object can be passed to the plot_predictions_gif object to plot a gif of the predictions evolving during training. See the test_predictions_column function in the Tests/test_columns.py module for a usage example of this...
Predictions
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Predictions: """This column is for storing predictions of the model during training. Once training is complete, this object can be passed to the plot_predictions_gif object to plot a gif of the predictions evolving during training. See the test_predictions_column function in the Tests/test_column...
stack_v2_sparse_classes_36k_train_028397
20,983
no_license
[ { "docstring": "Initialise this Predictions column. Inputs: - dataset: dataset that the model is about to be trained on. The training set from this dataset is used to calculate the upper and lower limits of the prediction inputs used by this object - n_points_per_dim: the number of unique prediction inputs to u...
2
stack_v2_sparse_classes_30k_val_000118
Implement the Python class `Predictions` described below. Class description: This column is for storing predictions of the model during training. Once training is complete, this object can be passed to the plot_predictions_gif object to plot a gif of the predictions evolving during training. See the test_predictions_c...
Implement the Python class `Predictions` described below. Class description: This column is for storing predictions of the model during training. Once training is complete, this object can be passed to the plot_predictions_gif object to plot a gif of the predictions evolving during training. See the test_predictions_c...
389dbb3c4f84f8498ea879980b82e2cf543e5441
<|skeleton|> class Predictions: """This column is for storing predictions of the model during training. Once training is complete, this object can be passed to the plot_predictions_gif object to plot a gif of the predictions evolving during training. See the test_predictions_column function in the Tests/test_column...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Predictions: """This column is for storing predictions of the model during training. Once training is complete, this object can be passed to the plot_predictions_gif object to plot a gif of the predictions evolving during training. See the test_predictions_column function in the Tests/test_columns.py module f...
the_stack_v2_python_sparse
optimisers/columns.py
jakelevi1996/backprop2
train
0
2430e6b9239b54be7ebc8e7eb20c27916e59751f
[ "self.column_index = column_index\nself.range_start = range_start if not range_start is None else 0\nself.range_end = range_end\nself.cast_to_number = cast_to_number\nself.values: List[Any] = list()\nself.values_caveats: List[bool] = list()", "if row_index >= self.range_start and (self.range_end is None or row_in...
<|body_start_0|> self.column_index = column_index self.range_start = range_start if not range_start is None else 0 self.range_end = range_end self.cast_to_number = cast_to_number self.values: List[Any] = list() self.values_caveats: List[bool] = list() <|end_body_0|> <|bo...
Consumer for data rows. The row consumers are used to filter cell values for a given column and a range interval of rows. The result is a list of values that represent a data series in a chart plot. Attributes ---------- values: list List of values in the resulting data series
DataStreamConsumer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataStreamConsumer: """Consumer for data rows. The row consumers are used to filter cell values for a given column and a range interval of rows. The result is a list of values that represent a data series in a chart plot. Attributes ---------- values: list List of values in the resulting data ser...
stack_v2_sparse_classes_36k_train_028398
7,684
permissive
[ { "docstring": "Initialize the index position for the column in the dataset schema that is being consumed and the range interval of row indexes. If range_start is None the considered interval of rows starts at 0. If range_end is None all rows until the end of the dataset are being consumed. Parameters ---------...
2
stack_v2_sparse_classes_30k_train_011765
Implement the Python class `DataStreamConsumer` described below. Class description: Consumer for data rows. The row consumers are used to filter cell values for a given column and a range interval of rows. The result is a list of values that represent a data series in a chart plot. Attributes ---------- values: list L...
Implement the Python class `DataStreamConsumer` described below. Class description: Consumer for data rows. The row consumers are used to filter cell values for a given column and a range interval of rows. The result is a list of values that represent a data series in a chart plot. Attributes ---------- values: list L...
e99f43df3df80ad5647f57d805c339257336ac73
<|skeleton|> class DataStreamConsumer: """Consumer for data rows. The row consumers are used to filter cell values for a given column and a range interval of rows. The result is a list of values that represent a data series in a chart plot. Attributes ---------- values: list List of values in the resulting data ser...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DataStreamConsumer: """Consumer for data rows. The row consumers are used to filter cell values for a given column and a range interval of rows. The result is a list of values that represent a data series in a chart plot. Attributes ---------- values: list List of values in the resulting data series""" d...
the_stack_v2_python_sparse
vizier/engine/packages/plot/query.py
VizierDB/web-api-async
train
2
b03336620a74a6518aecba253737eb2d8fbdbc62
[ "super(SlideT, self).__init__()\nself.a = array_check(a, 1)\nself.n_1 = int_check(n_1, 1)\nself.n_2 = int_check(n_2, 1)", "t = np.zeros(shape=self.a.shape)\nfor i, in np.ndindex(self.a.shape):\n if self.n_1 <= i <= self.a.size - self.n_2 - 1:\n x_forward = self.a[i - self.n_1:i]\n x_backward = se...
<|body_start_0|> super(SlideT, self).__init__() self.a = array_check(a, 1) self.n_1 = int_check(n_1, 1) self.n_2 = int_check(n_2, 1) <|end_body_0|> <|body_start_1|> t = np.zeros(shape=self.a.shape) for i, in np.ndindex(self.a.shape): if self.n_1 <= i <= self....
Slide T method.
SlideT
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SlideT: """Slide T method.""" def __init__(self, a: array_like, n_1: int, n_2: int) -> None: """:param a: array_like 1-D array :param n_1: int left testing length :param n_2: int right test length""" <|body_0|> def testing(self): """Slide and test. :return: class...
stack_v2_sparse_classes_36k_train_028399
8,892
no_license
[ { "docstring": ":param a: array_like 1-D array :param n_1: int left testing length :param n_2: int right test length", "name": "__init__", "signature": "def __init__(self, a: array_like, n_1: int, n_2: int) -> None" }, { "docstring": "Slide and test. :return: class self", "name": "testing", ...
3
stack_v2_sparse_classes_30k_train_004302
Implement the Python class `SlideT` described below. Class description: Slide T method. Method signatures and docstrings: - def __init__(self, a: array_like, n_1: int, n_2: int) -> None: :param a: array_like 1-D array :param n_1: int left testing length :param n_2: int right test length - def testing(self): Slide and...
Implement the Python class `SlideT` described below. Class description: Slide T method. Method signatures and docstrings: - def __init__(self, a: array_like, n_1: int, n_2: int) -> None: :param a: array_like 1-D array :param n_1: int left testing length :param n_2: int right test length - def testing(self): Slide and...
1c8d5fbf3676dc81e9f143e93ee2564359519b11
<|skeleton|> class SlideT: """Slide T method.""" def __init__(self, a: array_like, n_1: int, n_2: int) -> None: """:param a: array_like 1-D array :param n_1: int left testing length :param n_2: int right test length""" <|body_0|> def testing(self): """Slide and test. :return: class...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SlideT: """Slide T method.""" def __init__(self, a: array_like, n_1: int, n_2: int) -> None: """:param a: array_like 1-D array :param n_1: int left testing length :param n_2: int right test length""" super(SlideT, self).__init__() self.a = array_check(a, 1) self.n_1 = int_...
the_stack_v2_python_sparse
statistics/mutation.py
qliu0/PythonInAirSeaScience
train
0